⑴ 如何用java生成二維碼
packagecommon;
importjava.awt.Color;
importjava.awt.Graphics2D;
importjava.awt.Image;
importjava.awt.image.BufferedImage;
importjava.io.File;
importjava.io.IOException;
importjava.util.HashMap;
importjava.util.Map;
importjavax.imageio.ImageIO;
importjp.sourceforge.qrcode.QRCodeDecoder;
importjp.sourceforge.qrcode.exception.DecodingFailedException;
importcom.google.zxing.BarcodeFormat;
importcom.google.zxing.Binarizer;
importcom.google.zxing.BinaryBitmap;
importcom.google.zxing.EncodeHintType;
importcom.google.zxing.LuminanceSource;
importcom.google.zxing.MultiFormatReader;
importcom.google.zxing.MultiFormatWriter;
importcom.google.zxing.NotFoundException;
importcom.google.zxing.WriterException;
importcom.google.zxing.common.BitMatrix;
importcom.google.zxing.common.HybridBinarizer;
importcom.swetake.util.Qrcode;
/**
*二維碼生成工具類
*@authorCloud
*@data2016-12-15
*QRCode
*/
publicclassQRCodeUtil{
//二維碼顏色
privatestaticfinalintBLACK=0xFF000000;
//二維碼顏色
privatestaticfinalintWHITE=0xFFFFFFFF;
/**
*<spanstyle="font-size:18px;font-weight:blod;">ZXing方式生成二維碼</span>
*@paramtext<ahref="javascript:void();">二維碼內容</a>
*@paramwidth二維碼寬
*@paramheight二維碼高
*@paramoutPutPath二維碼生成保存路徑
*@paramimageType二維碼生成格式
*/
(Stringtext,intwidth,intheight,StringoutPutPath,StringimageType){
Map<EncodeHintType,String>his=newHashMap<EncodeHintType,String>();
//設置編碼字元集
his.put(EncodeHintType.CHARACTER_SET,"utf-8");
try{
//1、生成二維碼
BitMatrixencode=newMultiFormatWriter().encode(text,BarcodeFormat.QR_CODE,width,height,his);
//2、獲取二維碼寬高
intcodeWidth=encode.getWidth();
intcodeHeight=encode.getHeight();
//3、將二維碼放入緩沖流
BufferedImageimage=newBufferedImage(codeWidth,codeHeight,BufferedImage.TYPE_INT_RGB);
for(inti=0;i<codeWidth;i++){
for(intj=0;j<codeHeight;j++){
//4、循環將二維碼內容定入圖片
image.setRGB(i,j,encode.get(i,j)?BLACK:WHITE);
}
}
FileoutPutImage=newFile(outPutPath);
//如果圖片不存在創建圖片
if(!outPutImage.exists())
outPutImage.createNewFile();
//5、將二維碼寫入圖片
ImageIO.write(image,imageType,outPutImage);
}catch(WriterExceptione){
e.printStackTrace();
System.out.println("二維碼生成失敗");
}catch(IOExceptione){
e.printStackTrace();
System.out.println("生成二維碼圖片失敗");
}
}
/**
*<spanstyle="font-size:18px;font-weight:blod;">二維碼解析</span>
*@paramanalyzePath二維碼路徑
*@return
*@throwsIOException
*/
@SuppressWarnings({"rawtypes","unchecked"})
(StringanalyzePath)throwsException{
MultiFormatReaderformatReader=newMultiFormatReader();
Objectresult=null;
try{
Filefile=newFile(analyzePath);
if(!file.exists())
{
return"二維碼不存在";
}
BufferedImageimage=ImageIO.read(file);
LuminanceSourcesource=newLuminanceSourceUtil(image);
Binarizerbinarizer=newHybridBinarizer(source);
BinaryBitmapbinaryBitmap=newBinaryBitmap(binarizer);
Maphints=newHashMap();
hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
result=formatReader.decode(binaryBitmap,hints);
}catch(NotFoundExceptione){
e.printStackTrace();
}
returnresult;
}
/**
*<spanstyle="font-size:18px;font-weight:blod;">QRCode方式生成二維碼</span>
*@paramcontent二維碼內容
*@paramimgPath二維碼生成路徑
*@paramversion二維碼版本
*@paramisFlag是否生成Logo圖片為NULL不生成
*/
publicstaticvoidQRCodeCreate(Stringcontent,StringimgPath,intversion,StringlogoPath){
try{
QrcodeqrcodeHandler=newQrcode();
//設置二維碼排錯率,可選L(7%)M(15%)Q(25%)H(30%),排錯率越高可存儲的信息越少,但對二維碼清晰度的要求越小
qrcodeHandler.setQrcodeErrorCorrect('M');
//N代表數字,A代表字元a-Z,B代表其他字元
qrcodeHandler.setQrcodeEncodeMode('B');
//版本1為21*21矩陣,版本每增1,二維碼的兩個邊長都增4;所以版本7為45*45的矩陣;最高版本為是40,是177*177的矩陣
qrcodeHandler.setQrcodeVersion(version);
//根據版本計算尺寸
intimgSize=67+12*(version-1);
byte[]contentBytes=content.getBytes("gb2312");
BufferedImagebufImg=newBufferedImage(imgSize,imgSize,BufferedImage.TYPE_INT_RGB);
Graphics2Dgs=bufImg.createGraphics();
gs.setBackground(Color.WHITE);
gs.clearRect(0,0,imgSize,imgSize);
//設定圖像顏色>BLACK
gs.setColor(Color.BLACK);
//設置偏移量不設置可能導致解析出錯
intpixoff=2;
//輸出內容>二維碼
if(contentBytes.length>0&&contentBytes.length<130){
boolean[][]codeOut=qrcodeHandler.calQrcode(contentBytes);
for(inti=0;i<codeOut.length;i++){
for(intj=0;j<codeOut.length;j++){
if(codeOut[j][i]){
gs.fillRect(j*3+pixoff,i*3+pixoff,3,3);
}
}
}
}else{
System.err.println("QRCodecontentbyteslength="+contentBytes.length+"notin[0,130].");
}
/*判斷是否需要添加logo圖片*/
if(logoPath!=null){
Fileicon=newFile(logoPath);
if(icon.exists()){
intwidth_4=imgSize/4;
intwidth_8=width_4/2;
intheight_4=imgSize/4;
intheight_8=height_4/2;
Imageimg=ImageIO.read(icon);
gs.drawImage(img,width_4+width_8,height_4+height_8,width_4,height_4,null);
gs.dispose();
bufImg.flush();
}else{
System.out.println("Error:login圖片還在在!");
}
}
gs.dispose();
bufImg.flush();
//創建二維碼文件
FileimgFile=newFile(imgPath);
if(!imgFile.exists())
imgFile.createNewFile();
//根據生成圖片獲取圖片
StringimgType=imgPath.substring(imgPath.lastIndexOf(".")+1,imgPath.length());
//生成二維碼QRCode圖片
ImageIO.write(bufImg,imgType,imgFile);
}catch(Exceptione){
e.printStackTrace();
}
}
/**
*<spanstyle="font-size:18px;font-weight:blod;">QRCode二維碼解析</span>
*@paramcodePath二維碼路徑
*@return解析結果
*/
(StringcodePath){
FileimageFile=newFile(codePath);
BufferedImagebufImg=null;
StringdecodedData=null;
try{
if(!imageFile.exists())
return"二維碼不存在";
bufImg=ImageIO.read(imageFile);
QRCodeDecoderdecoder=newQRCodeDecoder();
decodedData=newString(decoder.decode(newImageUtil(bufImg)),"gb2312");
}catch(IOExceptione){
System.out.println("Error:"+e.getMessage());
e.printStackTrace();
}catch(DecodingFailedExceptiondfe){
System.out.println("Error:"+dfe.getMessage());
dfe.printStackTrace();
}
returndecodedData;
}
}
3、最後貼測試代碼:
packagetest;
importjava.awt.image.BufferedImage;
importjava.io.InputStream;
importjava.net.URL;
importjavax.imageio.ImageIO;
importcommon.ImageUtil;
importcommon.QRCodeUtil;
importjp.sourceforge.qrcode.QRCodeDecoder;
/**
*二維碼生成測試類
*@authorCloud
*@data2016-11-21
*QRCodeTest
*/
publicclassQRCodeTest{
publicstaticvoidmain(String[]args)throwsException{
/**
*QRcode二維碼生成測試
*QRCodeUtil.QRCodeCreate("http://blog.csdn.net/u014266877","E://qrcode.jpg",15,"E://icon.png");
*/
/**
*QRcode二維碼解析測試
*StringqrcodeAnalyze=QRCodeUtil.QRCodeAnalyze("E://qrcode.jpg");
*/
/**
*ZXingCode二維碼生成測試
*QRCodeUtil.zxingCodeCreate("http://blog.csdn.net/u014266877",300,300,"E://zxingcode.jpg","jpg");
*/
/**
*ZxingCode二維碼解析
*StringzxingAnalyze=QRCodeUtil.zxingCodeAnalyze("E://zxingcode.jpg").toString();
*/
System.out.println("success");
}
}
⑵ 怎麼使用java生成DataMatrix格式的二維碼
參考:
import com.spire.barcode.BarCodeGenerator;
import com.spire.barcode.BarCodeType;
import com.spire.barcode.BarcodeSettings;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
public class CreateDataMatrix {
public static void main(String[] args) throws Exception {
//生成BarcodeSettings實例
BarcodeSettings settings = new BarcodeSettings();
//設置條形碼類型為DataMatrix
settings.setType(BarCodeType.Data_Matrix);
//設置條形碼模型寬度
settings.setX(1.5f);
//設置數據和顯示文本
settings.setData("ABC 123456789ABC 123456789ABC 123456789");
settings.setData2D("ABC 123456789ABC 123456789ABC 123456789");
//創建BarCodeGenerator實例
BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);
//根據settings生成圖像數據,保存至BufferedImage實例
BufferedImage bufferedImage = barCodeGenerator.generateImage();
//保存為PNG圖片
ImageIO.write(bufferedImage, "png", new File("DataMatrix.png"));
System.out.println("Complete!");
}
}
用到了spire.barcode for java庫
⑶ java 如何完成二維碼的製作
參考以下代碼:
//創建BarcodeSettings實例
BarcodeSettingssettings=newBarcodeSettings();
//設置條碼類型為QR二維碼
settings.setType(BarCodeType.QR_Code);
//設置二維碼數據
settings.setData("Hello123456789");
//設置二維碼顯示數據
settings.setData2D("Hello123456789");
//設置數據類型
settings.setQRCodeDataMode(QRCodeDataMode.Alpha_Number);
//設置二維碼模型寬度
settings.setX(1.0f);
//設置二維碼糾錯級別
settings.setQRCodeECL(QRCodeECL.H);
//創建BarCodeGenerator實例
=newBarCodeGenerator(settings);
//根據settings生成圖像數據,保存至BufferedImage實例
BufferedImagebufferedImage=barCodeGenerator.generateImage();
//保存為PNG圖片
ImageIO.write(bufferedImage,"png",newFile("QRCode.png"));
System.out.println("Complete!");
需要引用Spire.Barcode for java
原文:Java 生成二維碼
⑷ 如何使用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://jinshan.iteye.com/blog/1004554
3:zxing
zxing 這個是google的
下載地址
http://code.google.com/p/zxing/downloads/list
Java代碼:
import java.io.File;
import java.util.Hashtable;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
public class QRCodeEvents {
public static void main(String []args)throws Exception{
String text = "你好";
int width = 100;
int height = 100;
String format = "png";
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("new.png");
MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
}
}
4:google chart api就有實現二維碼的方法
利用這個api,使用google appengine進行實現。
5:JS生成二維碼
使用jQuery-qrcode生成二維碼
先簡單說一下jquery-qrcode,這個開源的三方庫(可以從https://github.com/jeromeetienne/jquery-qrcode 獲取),
qrcode.js 是實現二維碼數據計算的核心類,
jquery.qrcode.js 是把它用jquery方式封裝起來的,用它來實現圖形渲染,其實就是畫圖(支持canvas和table兩種方式)
支持的功能主要有:
Js代碼:
text : "https://github.com/jeromeetienne/jquery-qrcode" //設置二維碼內容
Js代碼:
render : "canvas",//設置渲染方式
width : 256, //設置寬度
height : 256, //設置高度
typeNumber : -1, //計算模式
correctLevel : QRErrorCorrectLevel.H,//糾錯等級
background : "#ffffff",//背景顏色
foreground : "#000000" //前景顏色
使用方式非常簡單
Js代碼:
jQuery('#output').qrcode({width:200,height:200,correctLevel:0,text:content});
經過簡單實踐,
使用canvas方式渲染性能還是非常不錯的,但是如果用table方式,性能不太理想,特別是IE9以下的瀏覽器,所以需要自行優化一下渲染table的方式,這里就不細述了。
其實上面的js有一個小小的缺點,就是默認不支持中文。
這跟js的機制有關系,jquery-qrcode這個庫是採用 charCodeAt() 這個方式進行編碼轉換的,
而這個方法默認會獲取它的 Unicode 編碼,一般的解碼器都是採用UTF-8, ISO-8859-1等方式,
英文是沒有問題,如果是中文,一般情況下Unicode是UTF-16實現,長度2位,而UTF-8編碼是3位,這樣二維碼的編解碼就不匹配了。
解決方式當然是,在二維碼編碼前把字元串轉換成UTF-8,具體代碼如下:
function utf16to8(str) {
var out, i, len, c;
out = "";
len = str.length;
for(i = 0; i < len; i++) {
c = str.charCodeAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
out += str.charAt(i);
} else if (c > 0x07FF) {
out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
} else {
out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
}
}
return out;
}
⑸ java中怎樣用代碼生成二維碼
參考代碼
import java.io.*;
import java.util.Date;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
public class QRCodeEncoderTest
{
/** Creates a new instance of QRCodeEncoderTest */
public QRCodeEncoderTest()
{
}
public static void create_image(String sms_info)throws Exception{
try{
qrcode testQrcode =new qrcode();
testQrcode.setQrcodeErrorCorrect('M');
testQrcode.setQrcodeEncodeMode('B');
testQrcode.setQrcodeVersion(7);
String testString = sms_info;
byte[] d = testString.getBytes("gbk");
System.out.println(d.length);
//BufferedImage bi = new BufferedImage(98, 98, BufferedImage.TYPE_INT_RGB);
BufferedImage bi = new BufferedImage(98, 98, BufferedImage.TYPE_BYTE_BINARY);
Graphics2D g = bi.createGraphics();
g.setBackground(Color.WHITE);
g.clearRect(0, 0, 98, 98);
g.setColor(Color.BLACK);
// 限制最大位元組數為120
if (d.length>0 && d.length <120){
boolean[][] s = testQrcode.calQrcode(d);
for (int i=0;i<s.length;i++){
for (int j=0;j<s.length;j++){
if (s[j][i]) {
g.fillRect(j*2+3,i*2+3,2,2);
}
}
}
}
g.dispose();
bi.flush();
File f = new File("D:\\QRCodeTest\\"+sms_info+".jpg");
if(!f.exists()){
f.createNewFile();
}
//創建圖片
ImageIO.write(bi, "jpg", f);
} // end try
catch (Exception e) {
e.printStackTrace();
} // end catch
}
public static void main(String[] args) throws Exception {
System.out.println(new Date());
for(int i =1; i < 100000; i ++){
QRCodeEncoderTest.create_image(i+"");
}
System.out.println(new Date());
} // end main
}