package com.common;

import com.swetake.util.Qrcode;
import jp.sourceforge.qrcode.QRCodeDecoder;
import com.swetake.util.Qrcode; import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; /**
* Created by lxl on 2016-09-10.
*/
public class QRCodeUtils { /**
* 生成二维码
* @param qrContent 存入的内容
* @param w 二维码 宽度
* @param h 二维码 高度
* @param filePath 二维码 存储路径
* @param fileName 二维码 名称
* @return 返回文件名称
*/
public static String encoderQRCode(String qrContent, int w, int h, String filePath, String fileName) {
Lock lock = new ReentrantLock();
lock.lock();
String FilePath = "";
try {
Qrcode qrcode = new Qrcode();
qrcode.setQrcodeErrorCorrect('M');
qrcode.setQrcodeEncodeMode('B');
qrcode.setQrcodeVersion();
//如果给定的路径不存在创建
File fp = new File(filePath);
if (!fp.exists()) {
fp.mkdirs();
}
byte[] d = new byte[];
try {
d = qrContent.getBytes("GBK");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
BufferedImage bi = new BufferedImage(, , BufferedImage.TYPE_INT_RGB);
// createGraphics
Graphics2D g = bi.createGraphics();
// set background
g.setBackground(Color.WHITE);
g.clearRect(, , w, h);
g.setColor(Color.BLACK); if (d.length > && d.length < ) {
boolean[][] b = qrcode.calQrcode(d);
for (int ii = ; ii < b.length; ii++) {
for (int j = ; j < b.length; j++) {
if (b[j][ii]) {
g.fillRect(j * + , ii * + , , );
}
}
}
}
g.dispose();
bi.flush(); FilePath = filePath + fileName;
File f = new File(FilePath); try {
ImageIO.write(bi, "png", f);
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
} finally {
lock.unlock();
}
System.out.println("doned!");
return fileName;
} /**
* 读取二维码内容
* @param imageFile
* @return
*/
public static String decoderQRCode(File imageFile) {
Lock lock = new ReentrantLock();
lock.lock();
String decodedData = null;
try {
QRCodeDecoder decoder = new QRCodeDecoder();
BufferedImage image = null;
try {
image = ImageIO.read(imageFile);
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} try {
decodedData = new String(decoder.decode(new J2SEImage(image)), "GBK");
System.out.println("Output Decoded Data is:" + decodedData);
} catch (Exception dfe) {
System.out.println("Error: " + dfe.getMessage());
}
} catch (Exception e) {
} finally {
lock.unlock();
}
return decodedData;
}
}

------------------------------------------------------------end--------------------------------------------------------------------------

下面部分是扩展部分

二维中不仅可以存储字符,还可以存储图片,需要将要存储的图片转换成字节流,注意图片最大只可以存储2kb左右,对你没有听错,就是2kb

/**
* 将指定的图片转换为字节
* @param path
* @return
*/
public static byte[] image2byte(String path){
byte[] data = null;
FileImageInputStream input = null;
try {
input = new FileImageInputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buf = new byte[];
int numBytesRead = ;
while ((numBytesRead = input.read(buf)) != -) {
output.write(buf, , numBytesRead);
}
data = output.toByteArray();
output.close();
input.close();
}
catch (FileNotFoundException ex1) {
ex1.printStackTrace();
}
catch (IOException ex1) {
ex1.printStackTrace();
}
return data;
}
将二维码中读取出的字节转换成图片
    /**
* 将二维码中读取出的字节转换成图片
* @param data
* @param path
*/
public static void byte2image(byte[] data,String path){
if(data.length<||path.equals("")) return;
try{
FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
imageOutput.write(data, , data.length);
imageOutput.close();
} catch(Exception ex) {
System.out.println("Exception: " + ex);
ex.printStackTrace();
}
}

完成代码

package hbxt;

import com.swetake.util.Qrcode;
import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.exception.DecodingFailedException;
import org.apache.commons.codec.binary.Base64; import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*; /**
* Hello world!
*
*/
public class App
{
static int size=;
// 图片尺寸
static int imgSize = + * (size - );
public static byte[] createQRCode(String imgPath) {
byte[] result = null;
try {
Qrcode qrcodeHandler = new Qrcode();
qrcodeHandler.setQrcodeErrorCorrect('M');
qrcodeHandler.setQrcodeEncodeMode('B');
qrcodeHandler.setQrcodeVersion(size); byte[] contentBytes =image2byte(imgPath);
BufferedImage bufferImgage = new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = bufferImgage.createGraphics();
graphics2D.setBackground(Color.WHITE);
graphics2D.clearRect(, , imgSize, imgSize);
graphics2D.setColor(Color.BLACK);
int pixoff = ;
if (contentBytes.length > && contentBytes.length < ) {
boolean[][] matrix = qrcodeHandler.calQrcode(contentBytes);
for (int i = ; i < matrix.length; i++) {
for (int j = ; j < matrix.length; j++) {
if (matrix[j][i]) {
graphics2D.fillRect(j * + pixoff, i * + pixoff, , );
}
}
}
} else {
}
graphics2D.dispose();
bufferImgage.flush();
ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageIO.write(bufferImgage, "png", output);
result = output.toByteArray();
output.close(); } catch (Exception e) {
e.printStackTrace();
}
return result;
} public static void saveImage(byte[] data, String fileName,String type) {
BufferedImage image = new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_BYTE_BINARY);
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, byteOutputStream);
// byte[] date = byteOutputStream.toByteArray();
byte[] bytes = data;
System.out.println("path:" + fileName);
RandomAccessFile file = new RandomAccessFile(fileName, "rw");
file.write(bytes);
file.close();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* 将二维码中读取出的字节转换成图片
* @param data
* @param path
*/
public static void byte2image(byte[] data,String path){
if(data.length<||path.equals("")) return;
try{
FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
imageOutput.write(data, , data.length);
imageOutput.close();
} catch(Exception ex) {
System.out.println("Exception: " + ex);
ex.printStackTrace();
}
} /**
* 解析二维码(QRCode)
* @param imgPath 图片路径
* @return
*/
public static String decoderQRCode(String imgPath) {
// QRCode 二维码图片的文件
File imageFile = new File(imgPath);
BufferedImage bufImg = null;
String content = null;
try {
bufImg = ImageIO.read(imageFile);
QRCodeDecoder decoder = new QRCodeDecoder();
content = new String(decoder.decode(new TwoDimensionCodeImage(bufImg)), "utf-8");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
} catch (DecodingFailedException dfe) {
System.out.println("Error: " + dfe.getMessage());
dfe.printStackTrace();
}
return content;
} /**
* 将指定的图片转换为字节
* @param path
* @return
*/
public static byte[] image2byte(String path){
byte[] data = null;
FileImageInputStream input = null;
try {
input = new FileImageInputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buf = new byte[];
int numBytesRead = ;
while ((numBytesRead = input.read(buf)) != -) {
output.write(buf, , numBytesRead);
}
data = output.toByteArray();
output.close();
input.close();
}
catch (FileNotFoundException ex1) {
ex1.printStackTrace();
}
catch (IOException ex1) {
ex1.printStackTrace();
}
return data;
} public static void main(String[] args) {
byte[] imgs=App.createQRCode("d:/2.gif");
App.saveImage(imgs, "D:/1.png", "png");
System.out.println(imgs);
try {
Thread.sleep();
} catch (InterruptedException e) {
e.printStackTrace();
}
decoderQRCode("D:/1.png"); }
}

扩展类:

package hbxt;

import jp.sourceforge.qrcode.data.QRCodeImage;

import java.awt.image.BufferedImage;

/**
* Created by Administrator on 2016-10-20.
*/
public class TwoDimensionCodeImage implements QRCodeImage {
BufferedImage bufImg; public TwoDimensionCodeImage(BufferedImage bufImg) {
this.bufImg = bufImg;
} @Override
public int getHeight() {
return bufImg.getHeight();
} @Override
public int getPixel(int x, int y) {
return bufImg.getRGB(x, y);
} @Override
public int getWidth() {
return bufImg.getWidth();
} }

maven:

<dependency>
<groupId>com.xiongyingqi</groupId>
<artifactId>qrcode</artifactId>
<version>0.1.</version>
</dependency>

qr 生成二维码的更多相关文章

  1. php qr生成二维码

    二维码就是用在平面上用特定的几何图形记录数据信息的,QR码是常见的一种二维码.推荐使用生成QR码的php类库PHP QR Code. 例子: <?php   ini_set('display_e ...

  2. Javascript生成二维码(QR)

    网络上已经有非常多的二维码编码和解码工具和代码,很多都是服务器端的,也就是说需要一台服务器才能提供二维码的生成.本着对服务器性能的考虑,这种小事情都让服务器去做,感觉对不住服务器,尤其是对于大流量的网 ...

  3. QR code 扩展生成二维码

    include './phpqrcode/phpqrcode.php';  //引入QR库 QRcode::png("leo", 'qrcode.png', 'L', 10);  ...

  4. C#通过第三方组件生成二维码(QR Code)和条形码(Bar Code)

    用C#如何生成二维码,我们可以通过现有的第三方dll直接来实现,下面列出几种不同的生成方法: 1):通过QrCodeNet(Gma.QrCodeNet.Encoding.dll)来实现 1.1):首先 ...

  5. 使用PHP QR Code生成二维码

    使用PHP QR Code生成二维码   HP QR Code是一个PHP二维码生成类库,利用它可以轻松生成二维码,官网提供了下载和多个演示demo,查看地址: http://phpqrcode.so ...

  6. 使用PHP二维码生成类库PHP QR Code生成二维码

    <?php include 'phpqrcode.php'; $value = 'http://www.helloweba.com'; //二维码内容 $errorCorrectionLevel ...

  7. 利用PHP QR Code生成二维码(带logo)

    转自:http://www.cnblogs.com/txw1958/p/phpqrcode.html HP QR Code是一个PHP二维码生成类库,利用它可以轻松生成二维码,官网提供了下载和多个演示 ...

  8. C#利用QrCode.Net生成二维码(Qr码

    http://www.cnblogs.com/Soar1991/archive/2012/03/30/2426115.html 现在网上很多应用都是用二维码来分享网址或者其它的信息.尤其在移动领域,二 ...

  9. 前端生成二维码 - Javascript生成二维码(QR)

    前段时间项目中需要动态的生成二维码,经过评估,前后端生成都可以.但后端生成会有两个问题: 没有找到正规发布出来的后端开源库. 二维码图片,会随着商品的增加而不断变多. 基于以上两个问题,决定在前端生成 ...

随机推荐

  1. cdnbest如何查看站点操作日志(同步日志)

     1. 在区域列表点同步日志 2. 点击进入后,可以查看对哪个站点进行了操作,操作时间,ip,id都有记录 3. 想知道详细操作了什么内容把鼠标指向操作类型,就会弹出操作的信息

  2. python学习day6 for循环 字符串的内置方法

    1.for循环 和while相比 l=[1,2,3] i=0 while i <len(l) print(l[i]) i+=1 l=['a','b','c'] for item in l: pr ...

  3. unity项目开发必备插件Asset Hunter 2(资源猎人2)

    unity必备插件 Asset Hunter 2 2.4 , 工程项目过大,垃圾太多之后的清洁利器,能识别 ,移除你用不到的资源 扫码时备注或说明中留下邮箱 付款后如未回复请至https://shop ...

  4. Codeforces Beta Round #70 (Div. 2)

    Codeforces Beta Round #70 (Div. 2) http://codeforces.com/contest/78 A #include<bits/stdc++.h> ...

  5. ES6之导入模块时的内存共享

    项目结构 主页面 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> &l ...

  6. day 06 列表去重, 数据类型的补充,编码,深浅copy

    因为重要,所以放前面 列表去重 l1 = [1, 2, 3, 4, 5] l2 = [3, 4, 5, 6, 7] set = list(set(l1 + l2)) # set自动去重,然后变成lis ...

  7. php解析优酷网上的视频资源去广告

    1.过程原理解析: 一.准备工作 所谓工欲善其事必先利其器,做好破解的准备工作会令你事半功倍. 1.首先准备一个Http抓包工具,PC上推荐Fiddler或者Postman,iOS上推荐Surge 2 ...

  8. jquery字符串相等判断

    在jquery中字符串相等判断一直失败 原来是空格! string1, string2 若其中有一个为返回值或类似 $.trim(string1) == $.trim(string2) ------- ...

  9. Await Async和Thread.waitAll想法?未完待续

    [管理员]四九-李冰-修行者(2216529884) 2017/7/3 17:15:12 看着就可以了,这种东西是有使用场景的.并不是你用了就一定有提升的 [管理员]上海-xx科技(lovepoint ...

  10. Win7 64位VC6调试无法退出

    错误信息:LINK: fatal error LNK1168: cannot open Debug/test1.exe for writing 根据网络上查询,找到最终原因,DM.dll,TLLOC. ...