条形码生成

来源:互联网 发布:pokemon go unity源码 编辑:程序博客网 时间:2024/04/30 19:15
public class ZxingHandler {
private static final String CODE = "utf-8";  
    private static final int BLACK = 0xff000000;  
    private static final int WHITE = 0xFFFFFFFF;  
    /**
     * 条形码编码
     * 
     * @param contents
     * @param width
     * @param height
     * @param imgPath
     */
    public BufferedImage encode(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 {
        // 文字编码  
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();  
            hints.put(EncodeHintType.CHARACTER_SET, CODE);  
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
                    BarcodeFormat.CODE_128, codeWidth, height, hints);
            return toBufferedImage(bitMatrix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }



 
    /** 
     * 转换成图片 
     * 
     * @param matrix 
     * @return 
     */  
    private static BufferedImage toBufferedImage(BitMatrix matrix) {  
        int width = matrix.getWidth();  
        int height = matrix.getHeight();  
        BufferedImage image = new BufferedImage(width, height,  
                BufferedImage.TYPE_INT_ARGB);  
        for (int x = 0; x < width; x++) {  
            for (int y = 0; y < height; y++) {  
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);  
            }  
        }  
        return image;  
    }  

}


@RequestMapping(value = "/getBarCode", method = RequestMethod.GET)
public void getBarCode(HttpServletRequest request, HttpServletResponse response) {
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");

String contents = request.getParameter("barCode");
        int width = 250, height = 30;  
        ZxingHandler handler = new ZxingHandler();  
BufferedImage image = handler.encode(contents, width, height, "");
try {
ImageIO.write(image, "png", response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();

}

原创粉丝点击