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实现生成二维码的更多相关文章

  1. 在java中生成二维码,并直接输出到jsp页面

    在java中生成的二维码不存到磁盘里要直接输出到页面上,这就需要把生成的二维码直接以流的形式输出到页面上,我用的是myeclipse 和 tomcat 它的原理是:在加载页面时,根据img的src(c ...

  2. java springMVC生成二维码

    Zxing是Google提供的工具,提供了二维码的生成与解析的方法,现在使用Java利用Zxing生成二维码 1),二维码的生成 将Zxing-core.jar 包加入到classpath下. 我的下 ...

  3. java zxing生成二维码

    package zxing.test; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; i ...

  4. java Springboot 生成 二维码 +logo

    上码,如有问题或者优化,劳请广友下方留言 1.工具类 import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHint ...

  5. Java——CaptchaUtil生成二维码乱码

    前言 这个问题就是因为Linux上没有字体,你可以有两种方法,一个在生成的时候设置字体,一个就是安装字体. 默认的字体为Courier 乱码情况 步骤 安装字体工具 yum install -y fo ...

  6. Java zxing生成二维码所需的jar包

    免费的,不需要积分. 共有2个jar包, 链接: https://pan.baidu.com/s/1QJcEkRQOp1NdrNAgGC6LvQ 密码: 4524

  7. java url生成二维码保存到本地

    http://blog.sina.com.cn/s/blog_5a6efa330102v1lb.html http://blog.csdn.net/about58238/article/details ...

  8. 根据短链生成二维码并上传七牛云(Java)

    通过短链生成二维码并上传七牛云(Java) 前言 网上这种帖子其实也是很多,大部分搜出来的是CSDN的,然后点进去一看都几乎一样:所以这次给个自己实践的例子记录. 这次也是通过搜索得到的一部分能实现这 ...

  9. java生成二维码(需导入第三方ZXing.jar包)

    //这个类是用来解析,通过图片解析该图片的网页链接是什么 package util; import java.awt.Graphics2D;import java.awt.geom.AffineTra ...

随机推荐

  1. PAT 乙级 1060 爱丁顿数(25) C++版

    1060. 爱丁顿数(25) 时间限制 250 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 CHEN, Yue 英国天文学家爱丁顿很喜欢骑车.据说他 ...

  2. IRQL Ring0实现

    一,IRQL的定义Interrupt ReQuest Level     DDK对IRQL的定义是:中断请求级(IRQL)标示中断的优先级.处理器在一个IRQL上执行线程代码,IRQL是帮助决定线程如 ...

  3. JAVA Map 和 List 排序方法

    private Map<String,String> mapDate; //正序 mapDate=new TreeMap<String, String>(new Compara ...

  4. UI相关教程:HUD、UMG和Widget

    转自:http://aigo.iteye.com/blog/2258612 蓝图脚本来处理 ================================================== 用UM ...

  5. linux下新建(mkdir)、删除(rmdir)文件夹

    mkdir: 该命令:mkdir  ./folder2/folder3 ./当前文件下下一级目录 rmdir:移除文件夹

  6. spark streaming插入hbase

    import java.sql.{DriverManager, ResultSet} import org.apache.spark._ import org.apache.spark.streami ...

  7. python3基础操作

    ubuntu下python连接mysql apt-get install python-mysqldb 获取当前时间 >>> from datetime import datetim ...

  8. Apache提供的dbUtils

    一.介绍 apache组织为我们提供了dbUtils实用工具(一些jar包),封装了一些查询的类和借口,相对自己定义的来说,可以简化很多操作 dbUtils提供了核心功能 1.QueryRunner  ...

  9. python数字

    #=====>part1:数字类型#掌握:int,float#了解:Long(在python2中才有),complex# num=10# num=int(10)# print(type(num) ...

  10. webpack2.0配置postcss-loader

    使用webpack2.0配置postcssloader 安装postcss-loader npm install --save-dev postcss-loader 然后配置webpack.confi ...