首页 » IT技术 » 网络服务 » 正文

java zxing 生成彩色定位符二维码

这是用zxing 生成彩色定位符二维码的方法,zxing似乎没有提供这样的方法,自己写了一个,Java代码如下:

源代码   
package com.gogowan.util;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class QRcodeWithColor {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private static MultiFormatWriter mutiWriter = new MultiFormatWriter();
public static void encode(String content, int width, int height,
String destImagePath) {
try {
ImageIO.write(genBarcode(content, width, height),
"jpg", new File(destImagePath));
} catch (IOException e) {
e.printStackTrace();
} catch (WriterException e) {
e.printStackTrace();
}
}
private static int getFinderPatternWidth(BitMatrix matrix) {
int W = matrix.getWidth();
int H = matrix.getHeight();
int length = 0;
boolean flag = false;
for (int y = 0; y < H; y++) {
for (int x = 0; x < W; x++) {
if (matrix.get(x, y) == true) {
flag = true;
length++;
} else {
if (flag != false) {
return x;
}
}
}
}
return length;
}
public static BufferedImage genBarcode(String content, int width,
int height) throws WriterException,
IOException {
Map<EncodeHintType, Object> hint = new HashMap<EncodeHintType, Object>();
hint.put(EncodeHintType.CHARACTER_SET, "utf-8");
hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hint.put(EncodeHintType.MARGIN, 1);
BitMatrix matrix = mutiWriter.encode(content, BarcodeFormat.QR_CODE,
width, height, hint);
int H= matrix.getHeight();
int W= matrix.getWidth();
int L=getFinderPatternWidth(matrix)+3;
int[] pixels = new int[W * H];
Color redColor= new Color(182,0,5);
int redColorInt=redColor.getRGB();
Color greenColor= new Color(0,124,54);
int greenColorInt=greenColor.getRGB();
Color blueColor= new Color(0,64,152);
int blueColorInt=blueColor.getRGB();
for (int y = 0; y <H; y++) {
for (int x = 0; x < W; x++) {
if(x>0&&x<L&&y>0&&y<L){
pixels[y * W + x] = matrix.get(x, y) ? redColorInt: WHITE;
}else if (x>(W-L)&&x<H&&y>0&&y<L){
pixels[y * W + x] = matrix.get(x, y) ? blueColorInt: WHITE;
}else if (x>0&&x<L&&y>(H-L)&&y<H){
pixels[y * W + x] = matrix.get(x, y) ? greenColorInt: WHITE;
}else {
pixels[y * W + x] = matrix.get(x, y) ? BLACK: WHITE;
}
}
}
BufferedImage image = new BufferedImage(W, H,
BufferedImage.TYPE_INT_RGB);
image.getRaster().setDataElements(0, 0, W, H, pixels);
return image;
}
public static void main(String[] args) {
QRcodeWithColor.encode("http://www.frogchou.com/",256, 256, "F:\\frogchou.jpg");
}
}

 

生成效果

frogchou

本文共 2 个回复

  • 学习了 2016/04/19 09:29

    不错,学习下思路。

  • 王苗 2016/04/19 14:31

发表评论