Android二維碼

出自: http://xiaoniudu.blog.51cto.com/7952142/1328937
 

package com.code;

import java.awt.Color;

import java.awt.Graphics2D;

import java.awt.Image;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import java.io.UnsupportedEncodingException;

import java.util.Hashtable;

import javax.imageio.ImageIO;

import javax.swing.ImageIcon;

import jp.sourceforge.qrcode.QRCodeDecoder;

import jp.sourceforge.qrcode.exception.DecodingFailedException;

import org.apache.log4j.Logger;

import com.google.zxing.BarcodeFormat;

import com.google.zxing.BinaryBitmap;

import com.google.zxing.DecodeHintType;

import com.google.zxing.EncodeHintType;

import com.google.zxing.LuminanceSource;

import com.google.zxing.MultiFormatReader;

import com.google.zxing.MultiFormatWriter;

import com.google.zxing.NotFoundException;

import com.google.zxing.Result;

import com.google.zxing.WriterException;

import com.google.zxing.client.j2se.BufferedImageLuminanceSource;

import com.google.zxing.client.j2se.MatrixToImageWriter;

import com.google.zxing.common.BitMatrix;

import com.google.zxing.common.HybridBinarizer;

import com.swetake.util.Qrcode;

public class TwoDimensionCode {

private static Logger log = Logger.getLogger(TwoDimensionCode.class);   //設置日誌

private static int QRCODE_IMAGE_SIZE = 140;     //二維碼尺寸

private static int ICON_SIZE = 40;              //ICON圖片尺寸

public TwoDimensionCode(){}

/**

* 方法描述:生成中間帶ICON圖片的二維碼,默認尺寸140*140,ICON爲40*40

*

* @author HUI

* @time 2013-11-18下午4:20:52

* @param content 要存儲的內容

* @param qrCodeImgPath 二維碼圖片存儲的路徑

* @param iconPath 中間ICON圖標的路徑

* @param imgType 二維碼圖片存儲類型

* @return true 生成成功    false 失敗

*/

public boolean createQrCode(String content, String qrCodeImgPath, String iconPath, String imgType){

if(!isImageType(qrCodeImgPath, imgType)){

log.info("存儲二維碼圖片格式錯誤");

}

Qrcode qrcodeHandler = new Qrcode();

qrcodeHandler.setQrcodeErrorCorrect('M');   //二維碼排錯率,可選L(7%)、M(15%)、Q(25%)、H(30%),排錯率越高可存儲的信息越少,但對二維碼清晰度的要求越小

qrcodeHandler.setQrcodeEncodeMode('B');     //二維碼編碼格式

qrcodeHandler.setQrcodeVersion(7);          //二維碼尺寸

try {

byte[] contentBytes = content.getBytes("utf-8");    //設置文本的格式

BufferedImage bufImg = new BufferedImage(QRCODE_IMAGE_SIZE, QRCODE_IMAGE_SIZE, BufferedImage.TYPE_INT_RGB);  //創建二維碼Image

Graphics2D gs = bufImg.createGraphics();

gs.setColor.WHITE);   //設置背景顏色

gs.clearRect(0, 0, QRCODE_IMAGE_SIZE, QRCODE_IMAGE_SIZE);   //全部填充

gs.setColor(Color.BLACK);       //設置圖像顏色

int pixoff = 2;     // 設置偏移量 不設置可能導致解析出錯

if (contentBytes.length > 0 && contentBytes.length < 800) {

boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);

for (int i = 0; i < codeOut.length; i++) {

for (int j = 0; j < codeOut.length; j++) {

if (codeOut[j][i]) {

gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);

}

}

}

} else {

log.info("QRCode content bytes length = " + contentBytes.length + " not in [ 0,800 ]. ");

return false;

}

ImageIcon img = new ImageIcon(iconPath);                                        //實例化ICON圖標

if(img.getIconWidth()>QRCODE_IMAGE_SIZE || img.getIconHeight()>QRCODE_IMAGE_SIZE){

log.info("ICON圖標尺寸太大");

return false;

}

img.setImage(img.getImage().getScaledInstance(ICON_SIZE, ICON_SIZE, Image.SCALE_DEFAULT));  //縮小圖標,這裏測試是40*40======================

Image imgimg = img.getImage();      //ImageIcon轉化爲Image

int bufImgWidth = bufImg.getWidth();

int bufImgHeight = bufImg.getHeight();

int imgWidth = img.getIconWidth();

int imgHeight = img.getIconHeight();

int x = (bufImgWidth - imgWidth)/2;

int y = (bufImgHeight - imgHeight)/2;

gs.drawImage(imgimg, x, y, null);

gs.dispose();

bufImg.flush();

File imgFile = new File(qrCodeImgPath);

ImageIO.write(bufImg, imgType, imgFile);// 生成二維碼QRCode圖片

} catch (UnsupportedEncodingException e) {

log.info("存儲內容轉化UTF-8失敗");

e.printStackTrace();

return false;

} catch (IOException e) {

log.info("生成二維碼失敗");

e.printStackTrace();

return false;

}

return true;

}

/**

* 方法描述:生成中間帶ICON圖片的二維碼,指定尺寸

*

* @author HUI

* @time 2013-11-18下午4:31:29

* @param content 要存儲的內容

* @param qrCodeImgPath 二維碼圖片存儲的路徑

* @param iconPath 中間ICON圖標的路徑

* @param qrCodeImgSize 指定二維碼尺寸[ 0,40 ],尺寸越大,存儲容量越大

* @param imgType 二維碼圖片存儲類型

* @return true 生成成功    false 失敗

*/

public boolean createQrCode(String content, String qrCodeImgPath, String iconPath, int qrCodeImgSize, String imgType){

if(!isImageType(qrCodeImgPath, imgType)){

log.info("存儲二維碼圖片格式錯誤");

}

Qrcode qrcodeHandler = new Qrcode();

qrcodeHandler.setQrcodeErrorCorrect('M');   //二維碼排錯率,可選L(7%)、M(15%)、Q(25%)、H(30%),排錯率越高可存儲的信息越少,但對二維碼清晰度的要求越小

qrcodeHandler.setQrcodeEncodeMode('B');     //二維碼編碼格式

qrcodeHandler.setQrcodeVersion(qrCodeImgSize);          //二維碼尺寸

try {

byte[] contentBytes = content.getBytes("utf-8");    //設置文本的格式

int imgSize = 67 + 12 * (qrCodeImgSize - 1);

BufferedImage bufImg = new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_INT_RGB);  //創建二維碼Image

Graphics2D gs = bufImg.createGraphics();

gs.setColor.WHITE);   //設置背景顏色

gs.clearRect(0, 0, imgSize, imgSize);   //全部填充

gs.setColor(Color.BLACK);       //設置圖像顏色

int pixoff = 2;     // 設置偏移量 不設置可能導致解析出錯

if (contentBytes.length > 0 && contentBytes.length < 800) {

boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);

for (int i = 0; i < codeOut.length; i++) {

for (int j = 0; j < codeOut.length; j++) {

if (codeOut[j][i]) {

gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);

}

}

}

} else {

log.info("QRCode content bytes length = " + contentBytes.length + " not in [ 0,800 ]. ");

return false;

}

ImageIcon img = new ImageIcon(iconPath);                                        //實例化ICON圖標

if(img.getIconWidth()>imgSize || img.getIconHeight()>imgSize){

log.info("ICON圖標尺寸太大");

return false;

}

img.setImage(img.getImage().getScaledInstance(40, 40, Image.SCALE_DEFAULT));    //縮小圖標,這裏測試是40*40======================

Image imgimg = img.getImage();      //ImageIcon轉化爲Image

int bufImgWidth = bufImg.getWidth();

int bufImgHeight = bufImg.getHeight();

int imgWidth = img.getIconWidth();

int imgHeight = img.getIconHeight();

int x = (bufImgWidth - imgWidth)/2;

int y = (bufImgHeight - imgHeight)/2;

gs.drawImage(imgimg, x, y, null);

gs.dispose();

bufImg.flush();

File imgFile = new File(qrCodeImgPath);

ImageIO.write(bufImg, imgType, imgFile);// 生成二維碼QRCode圖片

} catch (UnsupportedEncodingException e) {

log.info("存儲內容轉化UTF-8失敗");

e.printStackTrace();

return false;

} catch (IOException e) {

log.info("生成二維碼失敗");

e.printStackTrace();

return false;

}

return true;

}

/**

* 方法描述:生成一般的二維碼

*

* @author HUI

* @time 2013-11-18下午4:49:28

* @param content 存儲內容

* @param qrCodeImgPath 二維碼存儲路徑

* @param imgType 二維碼圖片存儲類型

* @return

*/

public boolean createQrCode(String content, String qrCodeImgPath, String imgType){

if(!isImageType(qrCodeImgPath, imgType)){

log.info("存儲二維碼圖片格式錯誤");

}

Qrcode qrcodeHandler = new Qrcode();

qrcodeHandler.setQrcodeErrorCorrect('M');   //二維碼排錯率,可選L(7%)、M(15%)、Q(25%)、H(30%),排錯率越高可存儲的信息越少,但對二維碼清晰度的要求越小

qrcodeHandler.setQrcodeEncodeMode('B');     //二維碼編碼格式

qrcodeHandler.setQrcodeVersion(7);          //二維碼尺寸

try {

byte[] contentBytes = content.getBytes("utf-8");    //設置文本的格式

BufferedImage bufImg = new BufferedImage(QRCODE_IMAGE_SIZE, QRCODE_IMAGE_SIZE, BufferedImage.TYPE_INT_RGB);  //創建二維碼Image

Graphics2D gs = bufImg.createGraphics();

gs.setColor.WHITE);   //設置背景顏色

gs.clearRect(0, 0, QRCODE_IMAGE_SIZE, QRCODE_IMAGE_SIZE);   //全部填充

gs.setColor(Color.BLACK);       //設置圖像顏色

int pixoff = 2;     // 設置偏移量 不設置可能導致解析出錯

if (contentBytes.length > 0 && contentBytes.length < 800) {

boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);

for (int i = 0; i < codeOut.length; i++) {

for (int j = 0; j < codeOut.length; j++) {

if (codeOut[j][i]) {

gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);

}

}

}

} else {

log.info("QRCode content bytes length = " + contentBytes.length + " not in [ 0,800 ]. ");

return false;

}

gs.dispose();

bufImg.flush();

File imgFile = new File(qrCodeImgPath);

ImageIO.write(bufImg, imgType, imgFile);// 生成二維碼QRCode圖片

} catch (UnsupportedEncodingException e) {

log.info("存儲內容轉化UTF-8失敗");

e.printStackTrace();

return false;

} catch (IOException e) {

log.info("生成二維碼失敗");

e.printStackTrace();

return false;

}

return true;

}

/**

* 方法描述:google API生成二維碼

*

* @author HUI

* @time 2013-11-19下午12:45:52

* @param content 存儲內容

* @param qrCodeImgPath 二維碼存儲路徑

* @param qrCodeSize 二維碼生成大小(例如200*200)

* @param imgType 二維碼圖片存儲類型

* @return true 成功 false 失敗

*/

/*public boolean createQrCode(String content, String qrCodeImgPath, int qrCodeSize, String imgType){

if(!isImageType(qrCodeImgPath, imgType)){

log.info("存儲二維碼圖片格式錯誤");

return false;

}

QRCodeWriter writer = new QRCodeWriter();

try {

String contentStr = new String(content.getBytes("GBK"), "UTF-8");

BitMatrix matrix = writer.encode(contentStr, BarcodeFormat.QR_CODE,qrCodeSize, qrCodeSize);

File file = new File(qrCodeImgPath);

MatrixToImageWriter.writeToFile(matrix, imgType, file);

} catch (WriterException e) {

log.info("創建二維碼失敗");

e.printStackTrace();

return false;

} catch (IOException e) {

log.info("創建二維碼失敗");

e.printStackTrace();

return false;

}

return true;

}*/

public boolean createQrCode(String content, String qrCodeImgPath, int qrCodeSize, String imgType){

if(!isImageType(qrCodeImgPath, imgType)){

log.info("存儲二維碼圖片格式錯誤");

return false;

}

Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();

hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

BitMatrix bitMatrix;

try {

bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hints);

MatrixToImageWriter.writeToFile(bitMatrix, imgType, new File(qrCodeImgPath));

} catch (WriterException e) {

log.info("創建二維碼失敗");

e.printStackTrace();

return false;

} catch (IOException e) {

log.info("創建二維碼失敗");

e.printStackTrace();

return false;

}

return true;

}

/**

* 方法描述:解析不包含logo的二維碼,得到二維碼存儲信息

*

* @author HUI

* @time 2013-11-19上午9:26:51

* @param qrCodeImgPath 二維碼存儲路徑

* @return 二維碼的存儲信息

*/

public String decoderQRCode(String qrCodeImgPath){

File qrCodeImgFile = new File(qrCodeImgPath);

BufferedImage bufImg = null;

String content = null;

try {

bufImg = ImageIO.read(qrCodeImgFile);

QRCodeDecoder decoder = new QRCodeDecoder();

content = new String(decoder.decode(new TwoDimensionCodeImg(bufImg)), "UTF-8");

} catch (IOException e) {

log.info("解析出錯: " + e.getMessage());

e.printStackTrace();

} catch (DecodingFailedException dfe) {

log.info("解析出錯: " + dfe.getMessage());

dfe.printStackTrace();

}

return content;

}

/**

* 方法描述:解析不包含logo的二維碼,得到二維碼存儲信息

*

* @author HUI

* @time 2013-11-19上午9:29:01

* @param qrCodeImgFile 二維碼圖片文件

* @return 二維碼存儲信息

*/

public String decoderQRCode(File qrCodeImgFile){

BufferedImage bufImg = null;

String content = null;

try {

bufImg = ImageIO.read(qrCodeImgFile);

QRCodeDecoder decoder = new QRCodeDecoder();

content = new String(decoder.decode(new TwoDimensionCodeImg(bufImg)), "UTF-8");

} catch (IOException e) {

log.info("解析出錯: " + e.getMessage());

e.printStackTrace();

} catch (DecodingFailedException dfe) {

log.info("解析出錯: " + dfe.getMessage());

dfe.printStackTrace();

}

return content;

}

/**

* 方法描述:解析不包含logo的二維碼,得到二維碼存儲信息

*

* @author HUI

* @time 2013-11-19上午9:31:28

* @param input 二維碼文件輸入流

* @return 二維碼存儲信息

*/

public String decoderQRCode(InputStream input){

BufferedImage bufImg = null;

String content = null;

try {

bufImg = ImageIO.read(input);

QRCodeDecoder decoder = new QRCodeDecoder();

content = new String(decoder.decode(new TwoDimensionCodeImg(bufImg)), "UTF-8");

} catch (IOException e) {

log.info("解析出錯: " + e.getMessage());

e.printStackTrace();

} catch (DecodingFailedException dfe) {

log.info("解析出錯: " + dfe.getMessage());

dfe.printStackTrace();

}

return content;

}

/**

* 方法描述:利用google API解析二維碼

*

* @author HUI

* @time 2013-11-19下午12:47:52

* @param qrCodeImgPath 二維碼路徑

* @return

*/

public String decoderGoogleQRCode(String qrCodeImgPath){

Result result = null;

BufferedImage image = null;

String rtn = null;

try {

image = ImageIO.read(new File(qrCodeImgPath));

LuminanceSource source = new BufferedImageLuminanceSource(image);

BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();

hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");

result = new MultiFormatReader().decode(bitmap, hints);

rtn = result.getText();

} catch (IOException e) {

log.info("解析二維碼出現錯誤" + e.getMessage());

e.printStackTrace();

rtn = "";

} catch (NotFoundException e) {

log.info("解析二維碼出現錯誤" + e.getMessage());

e.printStackTrace();

rtn = "";

}

return rtn;

}

/**

* 方法描述:利用google API解析二維碼

*

* @author HUI

* @time 2013-11-19下午12:54:26

* @param qrCodeImgFile 二維碼文件

* @return 存儲信息

*/

public String decoderGoogleQRCode(File qrCodeImgFile){

Result result = null;

BufferedImage image = null;

String rtn = null;

try {

image = ImageIO.read(qrCodeImgFile);

LuminanceSource source = new BufferedImageLuminanceSource(image);

BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();

hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");

result = new MultiFormatReader().decode(bitmap, hints);

rtn = result.getText();

} catch (IOException e) {

log.info("解析二維碼出現錯誤" + e.getMessage());

e.printStackTrace();

rtn = "";

} catch (NotFoundException e) {

log.info("解析二維碼出現錯誤" + e.getMessage());

e.printStackTrace();

rtn = "";

}

return rtn;

}

/**

* 方法描述:利用google API解析二維碼

*

* @author HUI

* @time 2013-11-19下午12:56:34

* @param input 輸入流

* @return 存儲信息

*/

public String decoderGoogleQRCode(InputStream input){

Result result = null;

BufferedImage image = null;

String rtn = null;

try {

image = ImageIO.read(input);

LuminanceSource source = new BufferedImageLuminanceSource(image);

BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();

hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");

result = new MultiFormatReader().decode(bitmap, hints);

rtn = result.getText();

} catch (IOException e) {

log.info("解析二維碼出現錯誤" + e.getMessage());

e.printStackTrace();

rtn = "";

} catch (NotFoundException e) {

log.info("解析二維碼出現錯誤" + e.getMessage());

e.printStackTrace();

rtn = "";

}

return rtn;

}

private boolean isImageType(String qrCodeImgPath, String imgType){

int index = qrCodeImgPath.lastIndexOf(".");

if(index < 0){

return false;

}

String QrCodeimgType = qrCodeImgPath.substring(index).toLowerCase();

boolean imgPathTypeBool = QrCodeimgType.equals(".jpg") || QrCodeimgType.equals(".png") || QrCodeimgType.equals(".gif") || QrCodeimgType.equals(".bmp") || QrCodeimgType.equals(".jpeg");

boolean imgTypeBool = imgType.equals("jpg") || imgType.equals("png") || imgType.equals("gif") || imgType.equals("bmp") || imgType.equals("jpeg");

boolean Type2Equal = QrCodeimgType.substring(1).equals(imgType);

if(imgPathTypeBool && imgTypeBool && Type2Equal ){

return true;

}

return false;

}

}

這利用QRCode.jar解析時還用到TwoDimensionCodeImg類,它實現了QRCodeImage接口

package com.code;

import java.awt.image.BufferedImage;

import jp.sourceforge.qrcode.data.QRCodeImage;

public class TwoDimensionCodeImg implements QRCodeImage{

BufferedImage bufImg = null;

public TwoDimensionCodeImg(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();

}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章