java根据内容生成二维码图片
1 package util; 2 3 import java.awt.image.BufferedImage; 4 5 import java.io.File; 6 import java.io.IOException; 7 import java.io.OutputStream; 8 9 import javax.imageio.ImageIO; 10 11 import java.util.Hashtable; 12 13 import com.google.zxing.common.BitMatrix; 14 import com.google.zxing.BarcodeFormat; 15 import com.google.zxing.EncodeHintType; 16 import com.google.zxing.MultiFormatWriter; 17 18 /** 19 * 二维码的生成需要借助MatrixToImageWriter类,该类是由Google提供的,可以将该类直接拷贝到源码中使用 20 */ 21 public class MatrixToImageWriter { 22 private static final int BLACK = 0xFF000000; 23 private static final int WHITE = 0xFFFFFFFF; 24 25 private MatrixToImageWriter() { 26 } 27 28 public static BufferedImage toBufferedImage(BitMatrix matrix) { 29 int width = matrix.getWidth(); 30 int height = matrix.getHeight(); 31 BufferedImage image = new BufferedImage(width, height, 32 BufferedImage.TYPE_INT_RGB); 33 for (int x = 0; x < width; x++) { 34 for (int y = 0; y < height; y++) { 35 image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE); 36 } 37 } 38 return image; 39 } 40 41 public static void writeToFile(BitMatrix matrix, String format, File file) 42 throws IOException { 43 BufferedImage image = toBufferedImage(matrix); 44 if (!ImageIO.write(image, format, file)) { 45 throw new IOException("Could not write an image of format " 46 + format + " to " + file); 47 } 48 } 49 50 public static void writeToStream(BitMatrix matrix, String format, 51 OutputStream stream) throws IOException { 52 BufferedImage image = toBufferedImage(matrix); 53 if (!ImageIO.write(image, format, stream)) { 54 throw new IOException("Could not write an image of format " + format); 55 } 56 } 57 58 public static void main(String[] args) throws Exception { 59 String text = "http://www.baidu.com"; // 二维码内容 60 int width = 300; // 二维码图片宽度 61 int height = 300; // 二维码图片高度 62 String format = "jpg";// 二维码的图片格式 63 64 Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); 65 hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码 66 67 BitMatrix bitMatrix = new MultiFormatWriter().encode(text, 68 BarcodeFormat.QR_CODE, width, height, hints); 69 // 生成二维码 70 File outputFile = new File("d:" + File.separator + "new.jpg"); 71 MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile); 72 } 73 }