java 生成二维码

一步一步用 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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/392670.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

leetcode 922. 按奇偶排序数组 II(双指针)

给定一个非负整数数组 A&#xff0c; A 中一半整数是奇数&#xff0c;一半整数是偶数。 对数组进行排序&#xff0c;以便当 A[i] 为奇数时&#xff0c;i 也是奇数&#xff1b;当 A[i] 为偶数时&#xff0c; i 也是偶数。 你可以返回任何满足上述条件的数组作为答案。 示例&a…

机器学习 深度学习 ai_如何突破AI炒作成为机器学习工程师

机器学习 深度学习 aiI’m sure you’ve heard of the incredible artificial intelligence applications out there — from programs that can beat the world’s best Go players to self-driving cars.我敢肯定&#xff0c;您已经听说过令人难以置信的人工智能应用程序-从可…

arcgis插值不覆盖区划图_ArcGIS绘图—空气质量站点数据插值绘制等值线图

作者&#xff1a;吴琳&#xff1b;陈天舒&#xff0c;山东大学环境科学&#xff08;大气化学&#xff09;博士在读数据&#xff08;Excel格式&#xff09;&#xff1a;多站点污染物数据&#xff08;国&#xff0c;省&#xff0c;市控点&#xff09;&#xff0c;站点经纬度信息绘…

数字校验

1 function validNumber(fieldname,fielddesc){2 var value $.trim($("#key_"fieldname).val());3 var num /^([0-9.])$/;4 5 var flag num.test(value);6 if(!flag) {7 alert("【"fielddesc"】只能输入数字");8 …

JavaScript覆盖率统计实现

主要需求 1、 支持browser & nodejs 由于javascript既能够在浏览器环境执行&#xff0c;也能够在nodejs环境执行&#xff0c;因此须要能够统计两种环境下单元測试的覆盖率情况。 2、 透明、无缝 用户写单元測试用例的时候&#xff0c;不须要为了支持覆盖率统计多写代码&…

leetcode 328. 奇偶链表(双指针)

给定一个单链表&#xff0c;把所有的奇数节点和偶数节点分别排在一起。请注意&#xff0c;这里的奇数节点和偶数节点指的是节点编号的奇偶性&#xff0c;而不是节点的值的奇偶性。 请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1)&#xff0c;时间复杂度应为 O(nodes)…

NSLog打印当前文件,当前函数,当前行数

NSLog(”%s, %s, %d”, __FILE__, __FUNCTION__, __LINE__); 转载于:https://www.cnblogs.com/shenfei2031/archive/2011/08/06/2129636.html

单元格内容分列多行_姓名太多,放在一列打印时浪费纸张,可以分成多行多列打印...

在日常工作中&#xff0c;往往会碰到这种情况(如下图)&#xff1a;只有一列数据&#xff0c;而且比较多&#xff0c;如果打印起来就浪费纸张&#xff0c;然后复制、粘贴把表格变成几列&#xff0c;方便打印。今天小编和大家分享不用复制、粘贴&#xff0c;就能快速完成一列分成…

caesar加密_如何编写Caesar密码:基本加密简介

caesar加密by Brendan Massey由布伦丹梅西(Brendan Massey) The Caesar Cipher is a famous implementation of early day encryption. It would take a sentence and reorganize it based on a key that is enacted upon the alphabet. Take, for example, a key of 3 and th…

Java中接口、抽象类与内部类学习

2019独角兽企业重金招聘Python工程师标准>>> Java中接口、抽象类与内部类学习 接口与内部类为我们提供了一种将接口与实现分离的更加结构化的方法。 抽象类和抽象方法 抽象方法&#xff1a;仅有声明而没有方法体。 抽象类&#xff1a;包含一个或多个抽象方法的类&am…

leetcode 402. 移掉K位数字(贪心算法)

给定一个以字符串表示的非负整数 num&#xff0c;移除这个数中的 k 位数字&#xff0c;使得剩下的数字最小。 注意: num 的长度小于 10002 且 ≥ k。 num 不会包含任何前导零。 示例 1 : 输入: num “1432219”, k 3 输出: “1219” 解释: 移除掉三个数字 4, 3, 和 2 形成…

javascript 自定义Map

迁移时间&#xff1a;2017年5月25日08:24:19 Author:Marydon 三、自定义Map数据格式 需特别注意的是&#xff1a; js中没有像java中的Map数据格式&#xff0c;js自带的map()方法用于&#xff1a;返回一个由原数组中的每个元素调用一个指定方法后的返回值组成的新数组。 map()使…

gif分解合成_如何通过分解和合成使复杂的问题更容易

gif分解合成Discover Functional JavaScript was named one of the best new Functional Programming books by BookAuthority!“发现功能JavaScript”被BookAuthority评为最佳新功能编程书籍之一 &#xff01; Our natural way of dealing with complexity is to break it in…

vs2005 新建项目一片空白

最近在研究 workflow fundation ,但是在安装了他的extensions之后&#xff0c;发现VS2005 新建项目一片空白&#xff0c;除开workflow其他的项目模板全部丢失&#xff0c;新建项目对话框中空空如也。查阅资料后发现&#xff0c;可以通过 命令 devenv.exe /InstallVSTemplates 来…

docker导入镜像 liunx_docker扫盲?面试连这都不会就等着挂吧

推荐阅读&#xff1a;java喵&#xff1a;6大面试技能树&#xff1a;JAVA基础JVM算法数据库计算机网络操作系统​zhuanlan.zhihu.com一只Tom猫&#xff1a;都是“Redis惹的祸”&#xff0c;害我差点挂在美团三面&#xff0c;真是“虚惊一场”&#xff01;​zhuanlan.zhihu.com现…

crontab里shell脚本将top信息写入文件

crontab里shell脚本将top信息写入文件&#xff1a; 注&#xff1a; 1、top -n 1代表执行1次退出&#xff08;默认top是不退出的&#xff09;,-d 1代表每1秒执行1次 2、crontab里需加/bin/bash # crontab -e */5 * * * * /bin/bash /usr/local/bin/top.sh # vi top.sh #!/bin/ba…

leetcode 1030. 距离顺序排列矩阵单元格(bfs)

给出 R 行 C 列的矩阵&#xff0c;其中的单元格的整数坐标为 (r, c)&#xff0c;满足 0 < r < R 且 0 < c < C。 另外&#xff0c;我们在该矩阵中给出了一个坐标为 (r0, c0) 的单元格。 返回矩阵中的所有单元格的坐标&#xff0c;并按到 (r0, c0) 的距离从最小到…

Linux iptables:规则原理和基础

什么是iptables&#xff1f; iptables是Linux下功能强大的应用层防火墙工具&#xff0c;但了解其规则原理和基础后&#xff0c;配置起来也非常简单。 什么是Netfilter&#xff1f; 说到iptables必然提到Netfilter&#xff0c;iptables是应用层的&#xff0c;其实质是一个定义规…

太阳系八大行星碰撞的视频_火星的身世:从太阳系的起源说起

大约46亿年前盘状的太阳星云从一大片又冷又暗的气体云中诞生太阳自己并没有任何暴露确切年龄的线索&#xff0c;我们之所以能够知道太阳系的“生日”&#xff0c;是因为迄今从陨石中找到的最古老固体物质&#xff0c;年龄约为45.68亿年。一般认为&#xff0c;太阳系的各个地方是…

refract推导_我们如何利用Refract来利用React式编程的力量

refract推导by Joe McGrath通过乔麦克格拉斯 我们如何利用Refract来利用React式编程的力量 (How we harnessed the power of reactive programming with Refract) Have you ever wondered how open-source libraries built by companies come into existence?您是否想过公司建…