一步一步用 java 设计生成二维码

转至 http://blog.sina.com.cn/s/blog_5a6efa330102v1lb.html

在物联网的时代,二维码是个很重要的东西了,现在无论什么东西都要搞个二维码标志,唯恐落伍,就差人没有用二维码识别了。也许有一天生分证或者户口本都会用二维码识别了。今天心血来潮,看见别人都为自己的博客添加了二维码,我也想搞一个测试一下.

主要用来实现两点:

1. 生成任意文字的二维码.

2. 在二维码的中间加入图像.

3.

下载QR二维码包。

首先得下载 zxing.jar 包, 我这里用的是3.0 版本的core包

下载地址: 现在已经迁移到了github: https://github.com/zxing/zxing/wiki/Getting-Started-Developing,

当然你也可以从maven仓库下载jar 包: http://central.maven.org/maven2/com/google/zxing/core/

package qrcodesoft;import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;import com.google.zxing.LuminanceSource;public class BufferedImageLuminanceSource extends LuminanceSource {private final BufferedImage image;private final int left;private final int top;public BufferedImageLuminanceSource(BufferedImage image) {this(image, 0, 0, image.getWidth(), image.getHeight());}public BufferedImageLuminanceSource(BufferedImage image, int left,int top, int width, int height) {super(width, height);int sourceWidth = image.getWidth();int sourceHeight = image.getHeight();if (left + width > sourceWidth || top + height > sourceHeight) {throw new IllegalArgumentException("Crop rectangle does not fit within image data.");}for (int y = top; y < top + height; y++) {for (int x = left; x < left + width; x++) {if ((image.getRGB(x, y) & 0xFF000000) == 0) {image.setRGB(x, y, 0xFFFFFFFF); // = white
                }}}this.image = new BufferedImage(sourceWidth, sourceHeight,BufferedImage.TYPE_BYTE_GRAY);this.image.getGraphics().drawImage(image, 0, 0, null);this.left = left;this.top = top;}public byte[] getRow(int y, byte[] row) {if (y < 0 || y >= getHeight()) {throw new IllegalArgumentException("Requested row is outside the image: " + y);}int width = getWidth();if (row == null || row.length < width) {row = new byte[width];}image.getRaster().getDataElements(left, top + y, width, 1, row);return row;}public byte[] getMatrix() {int width = getWidth();int height = getHeight();int area = width * height;byte[] matrix = new byte[area];image.getRaster().getDataElements(left, top, width, height, matrix);return matrix;}public boolean isCropSupported() {return true;}public LuminanceSource crop(int left, int top, int width, int height) {return new BufferedImageLuminanceSource(image, this.left + left,this.top + top, width, height);}public boolean isRotateSupported() {return true;}public LuminanceSource rotateCounterClockwise() {int sourceWidth = image.getWidth();int sourceHeight = image.getHeight();AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0,0.0, 0.0, sourceWidth);BufferedImage rotatedImage = new BufferedImage(sourceHeight,sourceWidth, BufferedImage.TYPE_BYTE_GRAY);Graphics2D g = rotatedImage.createGraphics();g.drawImage(image, transform, null);g.dispose();int width = getWidth();return new BufferedImageLuminanceSource(rotatedImage, top,sourceWidth - (left + width), getHeight(), width);}
}

package qrcodesoft;import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Random;import javax.imageio.ImageIO;import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;public class QRCodeUtil {private static final String CHARSET = "utf-8";private static final String FORMAT_NAME = "JPG";// 二维码尺寸private static final int QRCODE_SIZE = 300;// LOGO宽度private static final int WIDTH = 60;// LOGO高度private static final int HEIGHT = 60;private static BufferedImage createImage(String content, String imgPath,boolean needCompress) throws Exception {Hashtable hints = new Hashtable();hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);hints.put(EncodeHintType.CHARACTER_SET, CHARSET);hints.put(EncodeHintType.MARGIN, 1);BitMatrix bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);int width = bitMatrix.getWidth();int height = bitMatrix.getHeight();BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);for (int x = 0; x < width; x++) {for (int y = 0; y < height; y++) {image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000: 0xFFFFFFFF);}}if (imgPath == null || "".equals(imgPath)) {return image;}// 插入图片QRCodeUtil.insertImage(image, imgPath, needCompress);return image;}private static void insertImage(BufferedImage source, String imgPath,boolean needCompress) throws Exception {File file = new File(imgPath);if (!file.exists()) {System.err.println(""+imgPath+"   该文件不存在!");return;}Image src = ImageIO.read(new File(imgPath));int width = src.getWidth(null);int height = src.getHeight(null);if (needCompress) { // 压缩LOGOif (width > WIDTH) {width = WIDTH;}if (height > HEIGHT) {height = HEIGHT;}Image image = src.getScaledInstance(width, height,Image.SCALE_SMOOTH);BufferedImage tag = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);Graphics g = tag.getGraphics();g.drawImage(image, 0, 0, null); // 绘制缩小后的图g.dispose();src = image;}// 插入LOGOGraphics2D graph = source.createGraphics();int x = (QRCODE_SIZE - width) / 2;int y = (QRCODE_SIZE - height) / 2;graph.drawImage(src, x, y, width, height, null);Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);graph.setStroke(new BasicStroke(3f));graph.draw(shape);graph.dispose();}public static void encode(String content, String imgPath, String destPath,boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath,needCompress);mkdirs(destPath);String file = new Random().nextInt(99999999)+".jpg";ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));}public static void mkdirs(String destPath) {File file =new File(destPath);   //当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)if (!file.exists() && !file.isDirectory()) {file.mkdirs();}}public static void encode(String content, String imgPath, String destPath)throws Exception {QRCodeUtil.encode(content, imgPath, destPath, false);}public static void encode(String content, String destPath,boolean needCompress) throws Exception {QRCodeUtil.encode(content, null, destPath, needCompress);}public static void encode(String content, String destPath) throws Exception {QRCodeUtil.encode(content, null, destPath, false);}public static void encode(String content, String imgPath,OutputStream output, boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath,needCompress);ImageIO.write(image, FORMAT_NAME, output);}public static void encode(String content, OutputStream output)throws Exception {QRCodeUtil.encode(content, null, output, false);}public static String decode(File file) throws Exception {BufferedImage image;image = ImageIO.read(file);if (image == null) {return null;}BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));Result result;Hashtable hints = new Hashtable();hints.put(DecodeHintType.CHARACTER_SET, CHARSET);result = new MultiFormatReader().decode(bitmap, hints);String resultStr = result.getText();return resultStr;}public static String decode(String path) throws Exception {return QRCodeUtil.decode(new File(path));}public static void main(String[] args) throws Exception {String text = "http://www.dans88.com.cn";QRCodeUtil.encode(text, "d:/MyWorkDoc/my180.jpg", "d:/MyWorkDoc", true);}}

  

转载于:https://www.cnblogs.com/yujianhuang/p/6900042.html

java 生成二维码相关推荐

  1. java 生成二维码 QRCode、zxing 两种方式

    版权声明:本文为 testcs_dn(微wx笑) 原创文章,非商用自由转载-保持署名-注明出处,谢谢. https://blog.csdn.net/testcs_dn/article/details/ ...

  2. 二维码相关---java生成二维码名片,并且自动保存到手机通讯录中...

    二维码相关---java生成二维码名片,并且自动保存到手机通讯录中... 技术qq交流群:JavaDream:251572072 1.首先介绍一个api.   Zxing是Google提供的关于条码 ...

  3. java生成二维码打印到浏览器

    java生成二维码打印到浏览器 解决方法: pom.xml的依赖两个jar包: <!-- https://mvnrepository.com/artifact/com.google.zxing/ ...

  4. Java生成二维码带LOGO底部标题竖版字体

    前言 Java后端生成二维码 底部 侧面带有标题,可调节字号 参考文章 使用Java生成二维码图片(亲测) Reborn_YY使用Java生成二维码图片 图标素材库 Java后台生成图片,前台实现图片 ...

  5. java生成二维码,并在前端展示。

    java生成二维码,并在前端展示,扫码实现下载功能. 后端生成二维码以流的形式 前端接收二维码并展示 后端生成二维码以流的形式 这是以流的形式展示二维码.当然也可以以文件的格式,文件格式就是Path ...

  6. java生成二维码(链接生成二维码)

    Java二维码如何生成? awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import com. ...

  7. java生成二维码到文件,java生成二维码转成BASE64

    java生成二维码到文件,java生成二维码转成BASE64 如题,利用java和第三方库,把指定的字符串生成二维码,并且把二维码保存成图片,转换成BASE64格式. 需要的jar文件: packag ...

  8. java生成二维码扫描跳转到指定的路径URL

    java生成二维码扫描跳转到指定的路径URL 导入依赖 <dependency><groupId>com.google.zxing</groupId><art ...

  9. Java 生成二维码 zxing生成二维码 条形码 服务端生成二维码 Java生成条形码

    Java 生成二维码 zxing生成二维码 条形码 服务端生成二维码 Java生成条形码 一.关于ZXing 1.ZXing是谷歌开源的支持二维码.条形码 等图形的生成类库:支持生成.和解码功能. G ...

  10. java 生成二维码后叠加LOGO并转换成base64

    1.代码 见文末推荐 2.测试 测试1:生成base64码 public static void main(String[] args) throws Exception {String data = ...

最新文章

  1. 创建存储器_Microchip推出首款低功耗数模转换器,集成非易失性存储器,简化手持设备设计...
  2. NBT:设计稳定无毒的抗菌肽杀灭耐药菌
  3. 工具 - 硕思SWF Decompiler5.3Build528 含补丁
  4. [密码学] 消息认证码基础
  5. mysql innodb学习笔记
  6. 全网最详细SpringBatch读(Reader)跨多行文件讲解
  7. CAN总线的初步认识
  8. LeetCode 208. 实现 Trie (前缀树) —— 提供一套前缀树模板
  9. 深度学习2.0-24.过拟合与欠拟合
  10. wxpython列表控件listctrl设置某行颜色_改变ListCtrl某行的背景色或者字体颜色
  11. 操作系统概念第七章部分作业题答案
  12. Webpack5学习笔记(基础篇七)—— Loader加载器
  13. 【SQL实战项目】电商平台数据分析项目
  14. 【Spring源码三千问】BeanDefinition详解——什么是 RootBeanDefinition?merged bean definition 又是什么鬼?
  15. “ 流量or变现 “ 网销50条干货必备
  16. 人脸识别和人脸检测的区别
  17. 箕星药业任命罗万里任CEO;​赛诺菲成2024年巴黎奥运会和残奥会的高端合作伙伴 | 医药健闻...
  18. PowerDesign提示未安装打印机
  19. 阿里、百度、美团都在用的‘’高并发秒杀系统‘’;抢红包、秒杀活动、微博热搜、12306抢票等高并发场景
  20. Gravity bridge——IBC Bridge to Ethereum

热门文章

  1. php gps 坐标,php 计算gps坐标 距离
  2. php 开启命令模式,如何启用PhpStorm中的命令行工具
  3. android webview sql database,websql在openDatabase报version mismatch错误,请问怎么解决?
  4. php 编程祝新年快乐_用于测试自动化的7种编程语言
  5. 按条件分类_保税仓储企业能否同时存储非保货物?“仓储货物安装台分类监管”如何申请?...
  6. 8086减法指令SUB
  7. 向量余弦值python_向量/矩阵的余弦值打印(元素明智的操作) 使用Python的线性代数
  8. random.next_Java Random next()方法与示例
  9. mcq 队列_MCQ | 基础知识 免费和开源软件| 套装4
  10. 实训09.09:简单的彩票系统(注册信息)