java实现生成二维码

  1. package com.cn.test;
  2. import java.awt.Graphics2D;
  3. import java.awt.geom.AffineTransform;
  4. import java.awt.image.BufferedImage;
  5. import com.google.zxing.LuminanceSource;
  6. public class BufferedImageLuminanceSource extends LuminanceSource{
  7. private final BufferedImage image;
  8. private final int left;
  9. private final int top;
  10. public BufferedImageLuminanceSource(BufferedImage image) {
  11. this(image, 0, 0, image.getWidth(), image.getHeight());
  12. }
  13. public BufferedImageLuminanceSource(BufferedImage image, int left,
  14. int top, int width, int height) {
  15. super(width, height);
  16. int sourceWidth = image.getWidth();
  17. int sourceHeight = image.getHeight();
  18. if (left + width > sourceWidth || top + height > sourceHeight) {
  19. throw new IllegalArgumentException(
  20. "Crop rectangle does not fit within image data.");
  21. }
  22. for (int y = top; y < top + height; y++) {
  23. for (int x = left; x < left + width; x++) {
  24. if ((image.getRGB(x, y) & 0xFF000000) == 0) {
  25. image.setRGB(x, y, 0xFFFFFFFF); // = white
  26. }
  27. }
  28. }
  29. this.image = new BufferedImage(sourceWidth, sourceHeight,
  30. BufferedImage.TYPE_BYTE_GRAY);
  31. this.image.getGraphics().drawImage(image, 0, 0, null);
  32. this.left = left;
  33. this.top = top;
  34. }
  35. public byte[] getRow(int y, byte[] row) {
  36. if (y < 0 || y >= getHeight()) {
  37. throw new IllegalArgumentException(
  38. "Requested row is outside the image: " + y);
  39. }
  40. int width = getWidth();
  41. if (row == null || row.length < width) {
  42. row = new byte[width];
  43. }
  44. image.getRaster().getDataElements(left, top + y, width, 1, row);
  45. return row;
  46. }
  47. public byte[] getMatrix() {
  48. int width = getWidth();
  49. int height = getHeight();
  50. int area = width * height;
  51. byte[] matrix = new byte[area];
  52. image.getRaster().getDataElements(left, top, width, height, matrix);
  53. return matrix;
  54. }
  55. public boolean isCropSupported() {
  56. return true;
  57. }
  58. public LuminanceSource crop(int left, int top, int width, int height) {
  59. return new BufferedImageLuminanceSource(image, this.left + left,
  60. this.top + top, width, height);
  61. }
  62. public boolean isRotateSupported() {
  63. return true;
  64. }
  65. public LuminanceSource rotateCounterClockwise() {
  66. int sourceWidth = image.getWidth();
  67. int sourceHeight = image.getHeight();
  68. AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0,
  69. 0.0, 0.0, sourceWidth);
  70. BufferedImage rotatedImage = new BufferedImage(sourceHeight,
  71. sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
  72. Graphics2D g = rotatedImage.createGraphics();
  73. g.drawImage(image, transform, null);
  74. g.dispose();
  75. int width = getWidth();
  76. return new BufferedImageLuminanceSource(rotatedImage, top,
  77. sourceWidth - (left + width), getHeight(), width);
  78. }
  79. }

---------------------------------------------------------------------------------------

  

  1. package com.cn.test;
  2. import java.awt.BasicStroke;
  3. import java.awt.Graphics;
  4. import java.awt.Graphics2D;
  5. import java.awt.Image;
  6. import java.awt.Shape;
  7. import java.awt.geom.RoundRectangle2D;
  8. import java.awt.image.BufferedImage;
  9. import java.io.File;
  10. import java.io.OutputStream;
  11. import java.text.SimpleDateFormat;
  12. import java.util.Date;
  13. import java.util.Hashtable;
  14. import java.util.Random;
  15. import javax.imageio.ImageIO;
  16. import com.google.zxing.BarcodeFormat;
  17. import com.google.zxing.BinaryBitmap;
  18. import com.google.zxing.DecodeHintType;
  19. import com.google.zxing.EncodeHintType;
  20. import com.google.zxing.MultiFormatReader;
  21. import com.google.zxing.MultiFormatWriter;
  22. import com.google.zxing.Result;
  23. import com.google.zxing.common.BitMatrix;
  24. import com.google.zxing.common.HybridBinarizer;
  25. import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
  26. public class QRCodeUtil {
  27. //二维码编码
  28. private static final String CHARSET = "utf-8";
  29. //二维码图片格式
  30. private static final String FORMAT_NAME = "JPG";
  31. // 二维码尺寸
  32. private static final int QRCODE_SIZE = 300;
  33. // LOGO宽度
  34. private static final int WIDTH = 60;
  35. // LOGO高度
  36. private static final int HEIGHT = 60;
  37. private static BufferedImage createImage(String content, String imgPath,
  38. boolean needCompress) throws Exception {
  39. // 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
  40. Hashtable hints = new Hashtable();
  41. //设置二维码容错率,从大到小依次H,Q,M,L,
  42. hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
  43. //设置编码类型
  44. hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
  45. //设置二维码编辑宽度
  46. hints.put(EncodeHintType.MARGIN, 1);
  47. BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
  48. BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
  49. int width = bitMatrix.getWidth();
  50. int height = bitMatrix.getHeight();
  51. // 二维矩阵转为一维像素数组,也就是一直横着排了
  52. BufferedImage image = new BufferedImage(width, height,
  53. BufferedImage.TYPE_INT_RGB);
  54. for (int x = 0; x < width; x++) {
  55. for (int y = 0; y < height; y++) {
  56. image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000
  57. : 0xFFFFFFFF);
  58. }
  59. }
  60. if (imgPath == null || "".equals(imgPath)) {
  61. return image;
  62. }
  63. // 插入图片
  64. QRCodeUtil.insertImage(image, imgPath, needCompress);
  65. return image;
  66. }
  67. private static void insertImage(BufferedImage source, String imgPath,
  68. boolean needCompress) throws Exception {
  69. File file = new File(imgPath);
  70. if (!file.exists()) {
  71. System.err.println(""+imgPath+" 该文件不存在!");
  72. return;
  73. }
  74. Image src = ImageIO.read(new File(imgPath));
  75. int width = src.getWidth(null);
  76. int height = src.getHeight(null);
  77. if (needCompress) { // 压缩LOGO
  78. if (width > WIDTH) {
  79. width = WIDTH;
  80. }
  81. if (height > HEIGHT) {
  82. height = HEIGHT;
  83. }
  84. Image image = src.getScaledInstance(width, height,
  85. Image.SCALE_SMOOTH);
  86. BufferedImage tag = new BufferedImage(width, height,
  87. BufferedImage.TYPE_INT_RGB);
  88. Graphics g = tag.getGraphics();
  89. g.drawImage(image, 0, 0, null); // 绘制缩小后的图
  90. g.dispose();
  91. src = image;
  92. }
  93. // 插入LOGO
  94. Graphics2D graph = source.createGraphics();
  95. int x = (QRCODE_SIZE - width) / 2;
  96. int y = (QRCODE_SIZE - height) / 2;
  97. graph.drawImage(src, x, y, width, height, null);
  98. Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
  99. graph.setStroke(new BasicStroke(3f));
  100. graph.draw(shape);
  101. graph.dispose();
  102. }
  103. public static void encode(String content, String imgPath, String destPath,
  104. boolean needCompress) throws Exception {
  105. BufferedImage image = QRCodeUtil.createImage(content, imgPath,
  106. needCompress);
  107. mkdirs(destPath);
  108. // String file = new Random().nextInt(99999999)+".jpg";
  109. String file = new SimpleDateFormat("yyyy_MM_dd").format(new Date()).toString()+"_"+new Random().nextInt(99999999)+".jpg";
  110. ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
  111. }
  112. public static void mkdirs(String destPath) {
  113. File file =new File(destPath);
  114. //当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
  115. if (!file.exists() && !file.isDirectory()) {
  116. file.mkdirs();
  117. }
  118. }
  119. //二维码带图片的logo
  120. public static void encode(String content, String imgPath, String destPath)
  121. throws Exception {
  122. QRCodeUtil.encode(content, imgPath, destPath, false);
  123. }
  124. //二维码不带图片的logo
  125. public static void encode(String content, String destPath,
  126. boolean needCompress) throws Exception {
  127. QRCodeUtil.encode(content, null, destPath, needCompress);
  128. }
  129. public static void encode(String content, String destPath) throws Exception {
  130. QRCodeUtil.encode(content, null, destPath, false);
  131. }
  132. public static void encode(String content, String imgPath,
  133. OutputStream output, boolean needCompress) throws Exception {
  134. BufferedImage image = QRCodeUtil.createImage(content, imgPath,
  135. needCompress);
  136. ImageIO.write(image, FORMAT_NAME, output);
  137. }
  138. public static void encode(String content, OutputStream output)
  139. throws Exception {
  140. QRCodeUtil.encode(content, null, output, false);
  141. }
  142. public static String decode(File file) throws Exception {
  143. BufferedImage image;
  144. image = ImageIO.read(file);
  145. if (image == null) {
  146. return null;
  147. }
  148. BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(
  149. image);
  150. BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
  151. Result result;
  152. Hashtable hints = new Hashtable();
  153. hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
  154. result = new MultiFormatReader().decode(bitmap, hints);
  155. String resultStr = result.getText();
  156. return resultStr;
  157. }
  158. public static String decode(String path) throws Exception {
  159. return QRCodeUtil.decode(new File(path));
  160. }
  161. public static void main(String[] args) throws Exception {
  162. String text = "http://obctop.tcl.com.cn/topsale/m/examination/exam_secondary.jsp";
  163. // FileUpLoadUtil ful = new FileUpLoadUtil();
  164. // String targetDirectory="/var/www/topsale/topsale/train/cover/";
  165. //上传图片的路径
  166. // ful.beginUpload(targetDirectory);
  167. //创建二维码logo
  168. //QRCodeUtil.encode(text, "D:/AAAAA/AAAAA/Training---PH/July/Template-Training Summary-English June/幻灯片1.jpg", "D:/AAAAA/AAAAA/Training---PH/July/Template-Training Summary-English June", true);
  169. // QRCodeUtil.encode(text, "", "D:/AAAAA/AAAAA/Training---PH/July/Template-Training Summary-English June", true);
  170. QRCodeUtil.encode(text, "","D:/DW/cover", true);
  171. }
  172. }

需要用到的jar。包java实现生成二维码

上一篇:通过OCI 处理 Oracle 10g 中处理Clob大字段写入


下一篇:J2EE: JCA (Java Connector Architecture) [转]