您的位置:首页 > 编程语言 > Java开发

java实现 二维码生成 并 添加 附加信息

2018-02-24 13:46 302 查看
需求说明

在一些场景中,需要在二维码底部添加一些相关的信息,例如二维码表示一个设备时,下方显示该设备的位置信息



实现方式

首先,根据需求的长和宽生成一个BufferedImage

/**
* 描述:建立布景并设置背景色
* @author renpengfei
* @since JDK 1.8
*/
BufferedImage outputImage = new BufferedImage(DEVICE_QRCODE_WIDTH,DEVICE_IMG_HEIGHT,BufferedImage.TYPE_INT_RGB);
Graphics g = outputImage.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0,0, DEVICE_QRCODE_WIDTH, DEVICE_IMG_HEIGHT);
g.dispose();


随后,将二维码本身表达的信息使用 google的zxing生成

/**
* 生成二维码
*/
ErrorCorrectionLevel level = ErrorCorrectionLevel.H;
HashMap<EncodeHintType,Object> hints = new HashMap<EncodeHintType,Object>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, level);
hints.put(EncodeHintType.MARGIN, 0);
BitMatrix m = new MultiFormatWriter().encode(deviceQrcode, BarcodeFormat.QR_CODE, DEVICE_QRCODE_WIDTH, DEVICE_QRCODE_HEIGHT,hints);
/**
* 二维码写入到bufferedImage
**/

4000
BufferedImage imageNew = new BufferedImage(DEVICE_QRCODE_WIDTH, DEVICE_QRCODE_HEIGHT,BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < DEVICE_QRCODE_WIDTH; x++) {
for (int y = 0; y < DEVICE_QRCODE_HEIGHT; y++) {
imageNew.setRGB(x, y, m.get(x, y) ? DEVICE_QRCODE_BLACK : DEVICE_QRCODE_WHITE);
}
}


然后将二维码写入BufferedImage中:

/**
* 描述:添加二维码
*/
int[] imageNewArray = new int[DEVICE_QRCODE_WIDTH*DEVICE_QRCODE_HEIGHT];
imageNewArray = imageNew.getRGB(0,0,DEVICE_QRCODE_WIDTH,DEVICE_QRCODE_HEIGHT,imageNewArray,0,DEVICE_QRCODE_WIDTH);
outputImage.setRGB(0,0,DEVICE_QRCODE_WIDTH,DEVICE_QRCODE_HEIGHT,imageNewArray,0,DEVICE_QRCODE_WIDTH);


将所需要的信息写入BufferedImage,这样就得到我们所需要的图片供后续操作,可以下载或者直接显示到页面中。

Graphics gText = outputImage.createGraphics();
gText.setColor(Color.black);
gText.setFont(new Font("普通", Font.PLAIN, DEVICE_INFO_FONT_SIZE));

gText.drawString(deviceInfo, 0, DEVICE_QRCODE_HEIGHT+DEVICE_INFO_FONT_SIZE);
gText.dispose();
return outputImage;


工具类:

http://download.csdn.net/download/qingfengilp/10256996
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二维码 java zxing