Java生成二维码方法有三种:

1: 使用SwetakeQRCode在Java项目中生成二维码 

http://swetake.com/qr/ 下载地址 

或着http://sourceforge.jp/projects/qrcode/downloads/28391/qrcode.zip 

这个是日本人写的,生成的是我们常见的方形的二维码 

能够用中文 如:5677777ghjjjjj 



2: 使用BarCode4j生成条形码和二维码 

BarCode4j网址:http://sourceforge.net/projects/barcode4j/ 



barcode4j是使用datamatrix的二维码生成算法,为支持qr的算法 

datamatrix是欧美的标准。qr为日本的标准, 

barcode4j一般生成出来是长方形的



如:88777alec000yan 

这个博客这方面说的挺清楚的: 

http://baijinshan.iteye.com/blog/1004554

3、如今具体介绍第三种也是经常使用的方式:利用Zxing生成二维码

Zxing是Google提供的关于条码(一维码、二维码)的解析工具,提供了二维码的生成与解析的方法,如今我简介一下使用Java利用Zxing生成与解析二维码。

第一步:将Zxing-core.jar 包增加项目中。

第二步 加入下面三个Java文件,三个文件功能例如以下:

MatrixToImageWriter.java  生成二维码图片。

BufferedImageLuminanceSource.java   解析二维码图片。

BarcodeFactory.java  生成带头像的二维码。

MatrixToImageWriter.java

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix; import javax.imageio.ImageIO;
import java.io.File;
import java.io.OutputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.awt.image.BufferedImage; public final class MatrixToImageWriter { private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF; private MatrixToImageWriter() {
} public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.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, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
} public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
} public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, stream)) {
throw new IOException("Could not write an image of format " + format);
}
} public static void main(String[] args) throws Exception {
String text = "二维码内容,能够是链接也能够是文本";
int width = 300;
int height = 300;
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//内容所使用编码
BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints); File outputFile = new File("E:/qrtest/生成普通二维码.jpg");
//File.separator
String format = "jpg";//二维码的图片格式
MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile); }
}

BufferedImageLuminanceSource.java

import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer; import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map; import javax.imageio.ImageIO; public final 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;
} @Override
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;
} @Override
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;
} @Override
public boolean isCropSupported() {
return true;
} @Override
public LuminanceSource crop(int left, int top, int width, int height) {
return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
} @Override
public boolean isRotateSupported() {
return true;
} @Override
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);
} public static void main(String[] args) {
//解析二维码
try {
MultiFormatReader formatReader = new MultiFormatReader();
String filePath = "E:/qrtest/生成普通二维码.jpg";
File file = new File(filePath);
BufferedImage image = ImageIO.read(file);
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer); Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
Result result = formatReader.decode(binaryBitmap, hints); System.out.println("result = " + result.toString());
System.out.println("resultFormat = " + result.getBarcodeFormat());
System.out.println("resultText = " + result.getText());
} catch (Exception e) {
e.printStackTrace();
}
}
}

BarcodeFactory.java

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; public class BarcodeFactory {
// 图片宽度的一般
private static final int IMAGE_WIDTH = 80;
private static final int IMAGE_HEIGHT = 80;
private static final int IMAGE_HALF_WIDTH = IMAGE_WIDTH / 2;
private static final int FRAME_WIDTH = 2; // 二维码写码器
private static MultiFormatWriter mutiWriter = new MultiFormatWriter(); /**
* 将srcImagePath嵌入到destImagePath
*/
public static void encode(String content, int width, int height, String srcImagePath, String destImagePath) {
try {
ImageIO.write(genBarcode(content, width, height, srcImagePath), "jpg", new File(destImagePath));
} catch (IOException e) {
e.printStackTrace();
} catch (WriterException e) {
e.printStackTrace();
}
} private static BufferedImage genBarcode(String content, int width, int height, String srcImagePath)
throws WriterException, IOException {
// 读取源图像
BufferedImage scaleImage = scale(srcImagePath, IMAGE_WIDTH, IMAGE_HEIGHT, true);
int[][] srcPixels = new int[IMAGE_WIDTH][IMAGE_HEIGHT];
for (int i = 0; i < scaleImage.getWidth(); i++) {
for (int j = 0; j < scaleImage.getHeight(); j++) {
srcPixels[i][j] = scaleImage.getRGB(i, j);
}
} Map<EncodeHintType, Object> hint = new HashMap<EncodeHintType, Object>();
hint.put(EncodeHintType.CHARACTER_SET, "utf-8");
hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 生成二维码
BitMatrix matrix = mutiWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hint); // 二维矩阵转为一维像素数组
int halfW = matrix.getWidth() / 2;
int halfH = matrix.getHeight() / 2;
int[] pixels = new int[width * height]; for (int y = 0; y < matrix.getHeight(); y++) {
for (int x = 0; x < matrix.getWidth(); x++) {
// 读取图片
if (x > halfW - IMAGE_HALF_WIDTH && x < halfW + IMAGE_HALF_WIDTH && y > halfH - IMAGE_HALF_WIDTH
&& y < halfH + IMAGE_HALF_WIDTH) {
pixels[y * width + x] = srcPixels[x - halfW + IMAGE_HALF_WIDTH][y - halfH + IMAGE_HALF_WIDTH];
}
// 在图片四周形成边框
else if ((x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH && x < halfW - IMAGE_HALF_WIDTH + FRAME_WIDTH
&& y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH + IMAGE_HALF_WIDTH + FRAME_WIDTH)
|| (x > halfW + IMAGE_HALF_WIDTH - FRAME_WIDTH && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
&& y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH + IMAGE_HALF_WIDTH + FRAME_WIDTH)
|| (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
&& y > halfH - IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH - IMAGE_HALF_WIDTH + FRAME_WIDTH)
|| (x > halfW - IMAGE_HALF_WIDTH - FRAME_WIDTH && x < halfW + IMAGE_HALF_WIDTH + FRAME_WIDTH
&& y > halfH + IMAGE_HALF_WIDTH - FRAME_WIDTH && y < halfH + IMAGE_HALF_WIDTH + FRAME_WIDTH)) {
pixels[y * width + x] = 0xfffffff;
} else {
// 此处能够改动二维码的颜色,能够分别制定二维码和背景的颜色;
pixels[y * width + x] = matrix.get(x, y) ? 0xff000000 : 0xfffffff;
}
}
} BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
image.getRaster().setDataElements(0, 0, width, height, pixels); return image;
} /**
* 把传入的原始图像按高度和宽度进行缩放。生成符合要求的图标
*
* @param srcImageFile
* 源文件地址
* @param height
* 目标高度
* @param width
* 目标宽度
* @param hasFiller
* 比例不正确时是否须要补白:true为补白; false为不补白;
* @throws IOException
*/
private static BufferedImage scale(String srcImageFile, int height, int width, boolean hasFiller) throws IOException {
double ratio = 0.0; // 缩放比例
File file = new File(srcImageFile);
BufferedImage srcImage = ImageIO.read(file);
Image destImage = srcImage.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
// 计算比例
if ((srcImage.getHeight() > height) || (srcImage.getWidth() > width)) {
if (srcImage.getHeight() > srcImage.getWidth()) {
ratio = (new Integer(height)).doubleValue() / srcImage.getHeight();
} else {
ratio = (new Integer(width)).doubleValue() / srcImage.getWidth();
}
AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
destImage = op.filter(srcImage, null);
}
if (hasFiller) {// 补白
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphic = image.createGraphics();
graphic.setColor(Color.white);
graphic.fillRect(0, 0, width, height);
if (width == destImage.getWidth(null))
graphic.drawImage(destImage, 0, (height - destImage.getHeight(null)) / 2, destImage.getWidth(null), destImage
.getHeight(null), Color.white, null);
else
graphic.drawImage(destImage, (width - destImage.getWidth(null)) / 2, 0, destImage.getWidth(null), destImage
.getHeight(null), Color.white, null);
graphic.dispose();
destImage = image;
}
return (BufferedImage) destImage;
} public static void main(String[] args) {
//src.jpg为头像文件
BarcodeFactory.encode("http://www.baidu.com", 300, 300, "E:/qrtest/src.jpg","E:/qrtest/生成带头像的二维码.jpg");
}
}


Java实现二维码技术探讨。的更多相关文章

  1. 基于java生成二维码

                                                                                            二维码  二维码的概念 ...

  2. java生成二维码/java解析二维码

    二维码的优缺点 优点:1. 高密度编码,信息容量大:2.编码范围广:3.容错能力强:4.译码可靠性高:5.可引入加密措施:6.成本低,易制作,持久耐用. 缺点:1.二维码技术成为手机病毒.钓鱼网站传播 ...

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

    版权声明:本文为博主原创文章,未经博主credreamer 同意不得转载 违者追究法律责任. https://blog.csdn.net/lidew521/article/details/244418 ...

  4. 利用JAVA生成二维码

    本文章整理于慕课网的学习视频<JAVA生成二维码>,如果想看视频内容请移步慕课网. 维基百科上对于二维码的解释. 二维条码是指在一维条码的基础上扩展出另一维具有可读性的条码,使用黑白矩形图 ...

  5. java实现二维码

    说起二维码,微信好像最先启用,随后各类二维码就开始流行起来了.那什么是二维码呢. 1.什么是二维码?百度一下即可 http://baike.baidu.com/view/132241.htm?fr=a ...

  6. java 生成二维码、可带LOGO、可去白边

      1.准备工作 所需jar包: JDK 1.6: commons-codec-1.11.jar core-2.2.jar javase-2.2.jar JDK 1.7: commons-codec- ...

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

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

  8. java代码生成二维码

    java代码生成二维码一般步骤 常用的是Google的Zxing来生成二维码,生成的一般步骤如下: 一.下载zxing-core的jar包: 二.需要创建一个MatrixToImageWriter类, ...

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

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

随机推荐

  1. 关于render函数的总结

    一般情况下封装一个导航组件的写法 <!DOCTYPE html> <html lang="en"> <head> <meta charse ...

  2. HDU 1097.A hard puzzle-快速幂/取模

    快速幂: 代码: ll pow_mod(ll a,ll b){      ll ans=;      while(b){          ==){              ans=ans*a%mo ...

  3. 转:Awesome Vulnerability Research

    转:https://github.com/re-pronin/Awesome-Vulnerability-Research Awesome Vulnerability Research 

  4. go chapter 3 - defer

    https://www.cnblogs.com/bonelee/p/6861777.html 函数返回之前(或任意位置执行 return 语句之后)一刻才执行某个语句或函数.用法类似于面向对象编程语言 ...

  5. 单例(LintCode)

    单例 单例 是最为最常见的设计模式之一.对于任何时刻,如果某个类只存在且最多存在一个具体的实例,那么我们称这种设计模式为单例.例如,对于 class Mouse (不是动物的mouse哦),我们应将其 ...

  6. 洛谷——P2952 [USACO09OPEN]牛线Cow Line

    P2952 [USACO09OPEN]牛线Cow Line 题目描述 Farmer John's N cows (conveniently numbered 1..N) are forming a l ...

  7. 【Nginx】初试反向代理:反向代理的原理和用途

    Nginx是一个轻量级的服务器,是一个俄罗斯的开发者开发的开源软件.Nginx具有占内存小.并发能力高的特点,底层采用epoll(Linux2.6+)和kqueue(FREEBSD)网络I/O模型,相 ...

  8. 【BZOJ 1057】 1057: [ZJOI2007]棋盘制作

    1057: [ZJOI2007]棋盘制作 Description 国际象棋是世界上最古老的博弈游戏之一,和中国的围棋.象棋以及日本的将棋同享盛名.据说国际象棋起源 于易经的思想,棋盘是一个8*8大小的 ...

  9. 初见Python<2>:列表和元组

      1.在python中,最基本的数据结构是序列,序列中每一个元素被分配一个序号,即元素的位置,称为索引.索引从0开始,-1表示倒数第一个元素,-2表示倒数第二个元素,因此既可以是从前到后开始对元素进 ...

  10. 【欧拉回路】Play On Words(6-16)

    [UVA10129]Play On Words 算法入门经典第6章6-16(P169) 题目大意:有一些单词,问能不能将它们串成字符串(只有前缀和后缀相同才能连) 试题分析:很巧妙的一道题,将每个单词 ...