qr 生成二维码
package com.common; import com.swetake.util.Qrcode; import jp.sourceforge.qrcode.QRCodeDecoder; import com.swetake.util.Qrcode; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Created by lxl on 2016-09-10. */ public class QRCodeUtils { /** * 生成二维码 * @param qrContent 存入的内容 * @param w 二维码 宽度 * @param h 二维码 高度 * @param filePath 二维码 存储路径 * @param fileName 二维码 名称 * @return 返回文件名称 */ public static String encoderQRCode(String qrContent, int w, int h, String filePath, String fileName) { Lock lock = new ReentrantLock(); lock.lock(); String FilePath = ""; try { Qrcode qrcode = new Qrcode(); qrcode.setQrcodeErrorCorrect('M'); qrcode.setQrcodeEncodeMode('B'); qrcode.setQrcodeVersion(7); //如果给定的路径不存在创建 File fp = new File(filePath); if (!fp.exists()) { fp.mkdirs(); } byte[] d = new byte[0]; try { d = qrContent.getBytes("GBK"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } BufferedImage bi = new BufferedImage(139, 139, BufferedImage.TYPE_INT_RGB); // createGraphics Graphics2D g = bi.createGraphics(); // set background g.setBackground(Color.WHITE); g.clearRect(0, 0, w, h); g.setColor(Color.BLACK); if (d.length > 0 && d.length < 123) { boolean[][] b = qrcode.calQrcode(d); for (int ii = 0; ii < b.length; ii++) { for (int j = 0; j < b.length; j++) { if (b[j][ii]) { g.fillRect(j * 3 + 2, ii * 3 + 2, 3, 3); } } } } g.dispose(); bi.flush(); FilePath = filePath + fileName; File f = new File(FilePath); try { ImageIO.write(bi, "png", f); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { } finally { lock.unlock(); } System.out.println("doned!"); return fileName; } /** * 读取二维码内容 * @param imageFile * @return */ public static String decoderQRCode(File imageFile) { Lock lock = new ReentrantLock(); lock.lock(); String decodedData = null; try { QRCodeDecoder decoder = new QRCodeDecoder(); BufferedImage image = null; try { image = ImageIO.read(imageFile); } catch (IOException e) { System.out.println("Error: " + e.getMessage()); } try { decodedData = new String(decoder.decode(new J2SEImage(image)), "GBK"); System.out.println("Output Decoded Data is:" + decodedData); } catch (Exception dfe) { System.out.println("Error: " + dfe.getMessage()); } } catch (Exception e) { } finally { lock.unlock(); } return decodedData; } }
------------------------------------------------------------end--------------------------------------------------------------------------
下面部分是扩展部分
二维中不仅可以存储字符,还可以存储图片,需要将要存储的图片转换成字节流,注意图片最大只可以存储2kb左右,对你没有听错,就是2kb
/** * 将指定的图片转换为字节 * @param path * @return */ public static byte[] image2byte(String path){ byte[] data = null; FileImageInputStream input = null; try { input = new FileImageInputStream(new File(path)); ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int numBytesRead = 0; while ((numBytesRead = input.read(buf)) != -1) { output.write(buf, 0, numBytesRead); } data = output.toByteArray(); output.close(); input.close(); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); } catch (IOException ex1) { ex1.printStackTrace(); } return data; }
将二维码中读取出的字节转换成图片
/** * 将二维码中读取出的字节转换成图片 * @param data * @param path */ public static void byte2image(byte[] data,String path){ if(data.length<3||path.equals("")) return; try{ FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path)); imageOutput.write(data, 0, data.length); imageOutput.close(); } catch(Exception ex) { System.out.println("Exception: " + ex); ex.printStackTrace(); } }
完成代码
package hbxt; import com.swetake.util.Qrcode; import jp.sourceforge.qrcode.QRCodeDecoder; import jp.sourceforge.qrcode.exception.DecodingFailedException; import org.apache.commons.codec.binary.Base64; import javax.imageio.ImageIO; import javax.imageio.stream.FileImageInputStream; import javax.imageio.stream.FileImageOutputStream; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; /** * Hello world! * */ public class App { static int size=40; // 图片尺寸 static int imgSize = 500 + 12 * (size - 1); public static byte[] createQRCode(String imgPath) { byte[] result = null; try { Qrcode qrcodeHandler = new Qrcode(); qrcodeHandler.setQrcodeErrorCorrect('M'); qrcodeHandler.setQrcodeEncodeMode('B'); qrcodeHandler.setQrcodeVersion(size); byte[] contentBytes =image2byte(imgPath); BufferedImage bufferImgage = new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = bufferImgage.createGraphics(); graphics2D.setBackground(Color.WHITE); graphics2D.clearRect(0, 0, imgSize, imgSize); graphics2D.setColor(Color.BLACK); int pixoff = 10; if (contentBytes.length > 0 && contentBytes.length < 3000) { boolean[][] matrix = qrcodeHandler.calQrcode(contentBytes); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix.length; j++) { if (matrix[j][i]) { graphics2D.fillRect(j * 4 + pixoff, i * 4 + pixoff, 4, 4); } } } } else { } graphics2D.dispose(); bufferImgage.flush(); ByteArrayOutputStream output = new ByteArrayOutputStream(); ImageIO.write(bufferImgage, "png", output); result = output.toByteArray(); output.close(); } catch (Exception e) { e.printStackTrace(); } return result; } public static void saveImage(byte[] data, String fileName,String type) { BufferedImage image = new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_BYTE_BINARY); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); try { ImageIO.write(image, type, byteOutputStream); // byte[] date = byteOutputStream.toByteArray(); byte[] bytes = data; System.out.println("path:" + fileName); RandomAccessFile file = new RandomAccessFile(fileName, "rw"); file.write(bytes); file.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 将二维码中读取出的字节转换成图片 * @param data * @param path */ public static void byte2image(byte[] data,String path){ if(data.length<3||path.equals("")) return; try{ FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path)); imageOutput.write(data, 0, data.length); imageOutput.close(); } catch(Exception ex) { System.out.println("Exception: " + ex); ex.printStackTrace(); } } /** * 解析二维码(QRCode) * @param imgPath 图片路径 * @return */ public static String decoderQRCode(String imgPath) { // QRCode 二维码图片的文件 File imageFile = new File(imgPath); BufferedImage bufImg = null; String content = null; try { bufImg = ImageIO.read(imageFile); QRCodeDecoder decoder = new QRCodeDecoder(); content = new String(decoder.decode(new TwoDimensionCodeImage(bufImg)), "utf-8"); } catch (IOException e) { System.out.println("Error: " + e.getMessage()); e.printStackTrace(); } catch (DecodingFailedException dfe) { System.out.println("Error: " + dfe.getMessage()); dfe.printStackTrace(); } return content; } /** * 将指定的图片转换为字节 * @param path * @return */ public static byte[] image2byte(String path){ byte[] data = null; FileImageInputStream input = null; try { input = new FileImageInputStream(new File(path)); ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int numBytesRead = 0; while ((numBytesRead = input.read(buf)) != -1) { output.write(buf, 0, numBytesRead); } data = output.toByteArray(); output.close(); input.close(); } catch (FileNotFoundException ex1) { ex1.printStackTrace(); } catch (IOException ex1) { ex1.printStackTrace(); } return data; } public static void main(String[] args) { byte[] imgs=App.createQRCode("d:/2.gif"); App.saveImage(imgs, "D:/1.png", "png"); System.out.println(imgs); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } decoderQRCode("D:/1.png"); } }
扩展类:
package hbxt; import jp.sourceforge.qrcode.data.QRCodeImage; import java.awt.image.BufferedImage; /** * Created by Administrator on 2016-10-20. */ public class TwoDimensionCodeImage implements QRCodeImage { BufferedImage bufImg; public TwoDimensionCodeImage(BufferedImage bufImg) { this.bufImg = bufImg; } @Override public int getHeight() { return bufImg.getHeight(); } @Override public int getPixel(int x, int y) { return bufImg.getRGB(x, y); } @Override public int getWidth() { return bufImg.getWidth(); } }
maven:
<dependency> <groupId>com.xiongyingqi</groupId> <artifactId>qrcode</artifactId> <version>0.1.10</version> </dependency>