Java生成条形码功能,本地已经调试好,但是测试linux环境下总是显示不出来,解决方法,在linux下的tomcat下bin目录找到 catalina.sh 中加入
-Djava.awt.headless=true
以下是生成条形码代码:
package com.ect.util;
import com.google.zxing.*;
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.oned.Code128Writer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import javax.imageio.ImageIO;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
public class ZxingUtils {
/**
* 生成二维码
*
* @param contents
* @param width
* @param height
* @param imgPath
*/
public static void encodeQRCode(String contents, int width, int height, String imgPath) {
Map<EncodeHintType, Object> hints = new Hashtable<>();
// 指定纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
// 指定编码格式
hints.put(EncodeHintType.CHARACTER_SET, "GBK");
try { // QR_CODE结尾的为生成二维码 要注意高度宽度 信息量越大 二维码越密集
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToStream(bitMatrix, "png", new FileOutputStream(imgPath));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 生成带logo的二维码
*/
public static void addLogo_QRCode(File qrcodeFile, String logoPicPath) {
try {
File logoPic = new File(logoPicPath);
if (!logoPic.exists() || !logoPic.isFile()) {
System.out.print("logo file not find !");
return;
}
// 读取二维码图片,并构建绘图对象
BufferedImage image = ImageIO.read(qrcodeFile);
Graphics2D g = image.createGraphics();
// 读取Logo图片
BufferedImage logo = ImageIO.read(logoPic);
// 设置logo的大小,本人设置为二维码图片的1/6,因为过大会盖掉二维码
int widthLogo = logo.getWidth(null) > image.getWidth() * 1 / 6 ? (image.getWidth() * 1 / 6)
: logo.getWidth(null);
int heightLogo = logo.getHeight(null) > image.getHeight() * 1 / 6 ? (image.getHeight() * 1 / 6)
: logo.getHeight(null);
// 计算图片放置位置,/logo放在中心
int x = (image.getWidth() - widthLogo) / 2;
int y = (image.getHeight() - heightLogo) / 2;
// 开始绘制图片
g.drawImage(logo, x, y, widthLogo, heightLogo, null);
// g.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15);
// g.setStroke(new BasicStroke(0));
// g.drawRect(x, y, widthLogo, heightLogo);
g.dispose();
logo.flush();
image.flush();
ImageIO.write(image, "png", qrcodeFile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 解析二维码
*
* @param imgPath
* @return
*/
public static String decodeQRCode(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("the decode image may be not exit.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Map<DecodeHintType, Object> hints = new Hashtable<>();
hints.put(DecodeHintType.CHARACTER_SET, "GBK");
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 生成条形码(不带文字)
*
* @param contents
* @param width
* @param height
* @param imgPath
*/
// int width = 105, height = 50; 长度很容易报错:NotFoundException
public static boolean encodeBarCode(String contents, int width, int height, String imgPath) {
int codeWidth = 3 + // start guard
(7 * 6) + // left bars
5 + // middle guard
(7 * 6) + // right bars
3; // end guard
codeWidth = Math.max(codeWidth, width);
try { // 条形码貌似只能写入条形码固定规则的信息
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.CODE_128, codeWidth, height,
null);
MatrixToImageWriter.writeToStream(bitMatrix, "png", new FileOutputStream(imgPath));
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 解析条形码
*
* @param imgPath
* @return
*/
public static String decodeBarCode(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("the decode image may be not exit.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
/*
* Map<DecodeHintType, Object> hints = new Hashtable<>();
* hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
* hints.put(DecodeHintType.CHARACTER_SET, "utf-8"); result = new
* MultiFormatReader().decode(bitmap, hints);
*/
result = new MultiFormatReader().decode(bitmap, null);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/******************* 带文字条形码 **********************************/
/** 条形码宽度 */
private static final int WIDTH = 300;
/** 条形码高度 */
private static final int HEIGHT = 50;
/** 加文字 条形码 */
private static final int WORDHEIGHT = 75;
/**
* 设置 条形码参数
*/
private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
private static final long serialVersionUID = 1L;
{
// 设置编码方式
put(EncodeHintType.CHARACTER_SET, "utf-8");
}
};
/**
* 生成 图片缓冲
*
* @author fxbin
* @param vaNumber
* VA 码
* @return 返回BufferedImage
*/
public static BufferedImage getBarCode(String vaNumber) {
try {
Code128Writer writer = new Code128Writer();
// 编码内容, 编码类型, 宽度, 高度, 设置参数
BitMatrix bitMatrix = writer.encode(vaNumber, BarcodeFormat.CODE_128, WIDTH, HEIGHT, hints);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
/**
* 把带logo的二维码下面加上文字
*
* @author fxbin
* @param image
* 条形码图片
* @param words
* 文字
* @return 返回BufferedImage
*/
public static BufferedImage insertWords(BufferedImage image, String words) {
// 新的图片,把带logo的二维码下面加上文字
if (words != null) {
BufferedImage outImage = new BufferedImage(WIDTH, WORDHEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = outImage.createGraphics();
// 抗锯齿
setGraphics2D(g2d);
// 设置白色
setColorWhite(g2d);
// 画条形码到新的面板
g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
// 画文字到新的面板
Color color = new Color(0, 0, 0);
g2d.setColor(color);
// 字体、字型、字号
// g2d.setFont(new Font("微软雅黑", Font.PLAIN, 18));
// 文字长度
int strWidth = g2d.getFontMetrics().stringWidth(words);
// 总长度减去文字长度的一半 (居中显示)
int wordStartX = (WIDTH - strWidth) / 2;
// height + (outImage.getHeight() - height) / 2 + 12
int wordStartY = HEIGHT + 20;
// 画文字
g2d.drawString(words, wordStartX, wordStartY);
g2d.dispose();
outImage.flush();
return outImage;
}
return null;
}
/**
* 设置 Graphics2D 属性 (抗锯齿)
*
* @param g2d
* Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
*/
private static void setGraphics2D(Graphics2D g2d) {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
g2d.setStroke(s);
}
/**
* 设置背景为白色
*
* @param g2d
* Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
*/
private static void setColorWhite(Graphics2D g2d) {
g2d.setColor(Color.WHITE);
// 填充整个屏幕
g2d.fillRect(0, 0, 600, 600);
// 设置笔刷
g2d.setColor(Color.BLACK);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* String imgPath = "D:\\test.png"; // 益达无糖口香糖的条形码 String contents =
* "6923450657713"; int width = 105, height = 50; ZxingUtils handler =
* new ZxingUtils(); handler.encodeBarCode(contents, width, height,
* imgPath); String barcode = handler.decodeBarCode(imgPath);
* System.out.println(barcode); handler.encodeQRCode("abc123中文@#\\",
* 200, 200, imgPath); String qrcode = handler.decodeQRCode(imgPath);
* System.out.println(qrcode);
*/
BufferedImage image = insertWords(getBarCode("123456789"), "123456789");
try {
ImageIO.write(image, "jpg", new File("D://abc.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//controller调用
//从本地读取文件并返回到网页中 直接返回不保存到磁盘
@RequestMapping(value="getbarCode")
public void getbarCode(String keycode, HttpServletResponse response){
ServletOutputStream out = null;
try {
out=response.getOutputStream();
BufferedImage butimage=ZxingUtils.getBarCode(keycode);
BufferedImage image = ZxingUtils.insertWords(butimage,keycode);
ImageIO.write(image, "jpg", out);
/*BufferedImage butimage=ZxingUtils.getBarCode(keycode);
BufferedImage image = ZxingUtils.insertWords(butimage,keycode);*/
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}