qr 生成二维码
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 生成二维码的更多相关文章
- php qr生成二维码
二维码就是用在平面上用特定的几何图形记录数据信息的,QR码是常见的一种二维码.推荐使用生成QR码的php类库PHP QR Code. 例子: <?php ini_set('display_e ...
- Javascript生成二维码(QR)
网络上已经有非常多的二维码编码和解码工具和代码,很多都是服务器端的,也就是说需要一台服务器才能提供二维码的生成.本着对服务器性能的考虑,这种小事情都让服务器去做,感觉对不住服务器,尤其是对于大流量的网 ...
- QR code 扩展生成二维码
include './phpqrcode/phpqrcode.php'; //引入QR库 QRcode::png("leo", 'qrcode.png', 'L', 10); ...
- C#通过第三方组件生成二维码(QR Code)和条形码(Bar Code)
用C#如何生成二维码,我们可以通过现有的第三方dll直接来实现,下面列出几种不同的生成方法: 1):通过QrCodeNet(Gma.QrCodeNet.Encoding.dll)来实现 1.1):首先 ...
- 使用PHP QR Code生成二维码
使用PHP QR Code生成二维码 HP QR Code是一个PHP二维码生成类库,利用它可以轻松生成二维码,官网提供了下载和多个演示demo,查看地址: http://phpqrcode.so ...
- 使用PHP二维码生成类库PHP QR Code生成二维码
<?php include 'phpqrcode.php'; $value = 'http://www.helloweba.com'; //二维码内容 $errorCorrectionLevel ...
- 利用PHP QR Code生成二维码(带logo)
转自:http://www.cnblogs.com/txw1958/p/phpqrcode.html HP QR Code是一个PHP二维码生成类库,利用它可以轻松生成二维码,官网提供了下载和多个演示 ...
- C#利用QrCode.Net生成二维码(Qr码
http://www.cnblogs.com/Soar1991/archive/2012/03/30/2426115.html 现在网上很多应用都是用二维码来分享网址或者其它的信息.尤其在移动领域,二 ...
- 前端生成二维码 - Javascript生成二维码(QR)
前段时间项目中需要动态的生成二维码,经过评估,前后端生成都可以.但后端生成会有两个问题: 没有找到正规发布出来的后端开源库. 二维码图片,会随着商品的增加而不断变多. 基于以上两个问题,决定在前端生成 ...
随机推荐
- 重工单001800020505在IN表IN_SFCHEADER被过滤 TEMP_REMOVED_ID_IN_DATA
select * from SAP_AFKO WHERE AUFNR='001800020505'; ---有数据SELECT * FROM IN_SFCHEADER WHERE MO_ID ='0 ...
- angularjs directive scope 与父scope双向绑定
参考 http://www.jb51.net/article/83051.htm angluar.module("aaa").directive("testDirecti ...
- python计算两个数的百分比
a和b是整数,计算a/b的百分比 a=3 b=7 a=float(a) b=float(b) 保留百分比后2位小数 print "%.2f%%" % (a/b*100) '42. ...
- 弹出序列(python)
题目描述 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序.假设压入栈的所有数字均不相等.例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压 ...
- attenuation
attenuation - 必应词典 美[əˌtenjʊ'eɪʃ(ə)n]英[əˌtenjʊ'eɪʃ(ə)n] n.减弱:稀释:[物]衰减:变细 网络衰减量:衰减作用:衰减值
- C语言之栈区、堆区
一 局部变量存放在栈区中,函数调用结束后释放内存空间. #include "stdio.h"; #include "stdlib.h"; int *getNum ...
- 伪异步IO
针对传统的BIO编程,当客户端数量一直增加的情况下,可能会导致服务器直接奔溃掉,进而出现了一种伪异步IO的线程方式. 先看一下代码: 看一下server端的代码: 其中使用了自定义的一个线程池Hand ...
- 微信小程序开发——打开另一个小程序
微信小程序打开另一个小程序,有两种方法:1.超链接:2.点击按钮. 全局配置: 跳转到其他小程序,需要在当前小程序全局配置中配置需要跳转的小程序列表,代码如下: App.json { ... &quo ...
- python的定时任务模块--schedule
首先先安装一下模块 下面我们简单的学习一下schedule模块 先简单的看个示例 import schedule def test(*args,**kwargs): print("hello ...
- go语言中常用的文件和文件夹操作函数
package main; import ( "os" "log" "time" "fmt" ) //一些常用的文件操作 ...