import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.Hashtable;
import javax.imageio.ImageIO;
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.ReaderException;
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.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* 二维码
* @author QY
*/
public class BuildED {
private static Logger logger = Logger.getLogger(BuildED.class);
/**
* 生成包含字符串信息的二维码图片
* @param outputStream 文件输出流路径
* @param content 二维码携带信息
* @param qrCodeSize 二维码图片大小
* @param imageFormat 二维码的格式
* @throws WriterException
* @throws IOException
*/
public static boolean createQrCode1(OutputStream outputStream, String content, int qrCodeSize, String imageFormat) throws WriterException, IOException{
//设置二维码纠错级别MAP
Hashtable<EncodeHintType, ErrorCorrectionLevel> hints = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); // 矫错级别
QRCodeWriter qrCodeWriter = new QRCodeWriter();
//创建比特矩阵(位矩阵)的QR码编码的字符串
BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hints);
// 使BufferedImage勾画QRCode (matrixWidth 是行二维码像素点)
int matrixWidth = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(matrixWidth-200, matrixWidth-200, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixWidth);
// 使用比特矩阵画并保存图像
graphics.setColor(Color.BLACK);
for (int i = 0; i < matrixWidth; i++){
for (int j = 0; j < matrixWidth; j++){
if (byteMatrix.get(i, j)){
graphics.fillRect(i-100, j-100, 1, 1);
}
}
}
return ImageIO.write(image, imageFormat, outputStream);
}
/**
* 读二维码并输出携带的信息
*/
public static void readQrCode1(InputStream inputStream) throws IOException{
//从输入流中获取字符串信息
BufferedImage image = ImageIO.read(inputStream);
//将图像转换为二进制位图源
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
Result result = null ;
try {
result = reader.decode(bitmap);
} catch (ReaderException e) {
e.printStackTrace();
}
logger.debug(result.getText());
}
/**
* 测试代码
* @throws WriterException
*/
public static void main(String[] args) throws IOException, WriterException {
FileOutputStream fileOutputStream = new FileOutputStream(new File("d:\\二维码1.jpg"));
String detail1 = "https://www.baidu.com";
int size = 800; // 过小会异常
String imageFormat = "JPEG";
String filePath = "d:\\二维码2.jpg";
String detail2 = "";
int high = 150;
int wide = 150;
//生成二维码 (大小问题)
createQrCode1(fileOutputStream,detail1,size,imageFormat);
readQrCode1(new FileInputStream(new File("d:\\二维码1.jpg")));
//生成二维码
for (int i = 0; i < 635; i++) {
detail2 += "1";
}
//此方法生成二维码需根据内容大小调试二维码大小
createQrCode2(detail1, filePath, high, wide);
readQrCode2(filePath);
}
// 创建二维码 方法二
static void createQrCode2(String conent, String filePath,int h,int w) {
Charset charset = Charset.forName("UTF-8");
CharsetEncoder encoder = charset.newEncoder();
byte[] b = null;
try { // Convert a string to ISO-8859-1 bytes in a ByteBuffer
logger.debug("-------->" + conent.length());
ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(conent));
b = bbuf.array();
} catch (CharacterCodingException e) {
logger.debug(e.getMessage());
}
String data = "";
try {
data = new String(b, "iso8859-1");
} catch (UnsupportedEncodingException e) {
logger.debug(e.getMessage());
} // get a byte matrix for the data
BitMatrix matrix = null;
com.google.zxing.Writer writer = new QRCodeWriter();
try {
matrix = writer.encode(data,
com.google.zxing.BarcodeFormat.QR_CODE, w, h);
} catch (com.google.zxing.WriterException e) {
logger.debug(e.getMessage());
}
File file = new File(filePath);
try {
MatrixToImageWriter.writeToFile(matrix, "PNG", file);
logger.debug("printing to " + file.getAbsolutePath());
} catch (IOException e) {
logger.debug(e.getMessage());
}
}
// qrcode 解码
static void readQrCode2(String file) {
try {
Result result = null;
BufferedImage image = null;
image = ImageIO.read(new File(file));
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
result = new MultiFormatReader().decode(bitmap, hints);
String rtn = result.getText();
logger.debug(rtn);
logger.debug(rtn.length());
} catch (Exception ex) {
logger.debug(ex.toString());
}
}
}