生成二维码,条形码,带数字,输出到文件

生成二维码和条形码

依赖

  <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.4.1</version>
        </dependency>

代码



package com.zyj.common.utils;

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.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import sun.font.FontDesignMetrics;


import javax.imageio.ImageIO;
import javax.print.*;
import javax.print.attribute.HashPrintJobAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSize;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;
import java.util.HashMap;

import static com.google.zxing.client.j2se.MatrixToImageWriter.toBufferedImage;

public class CreateCodeUtils {

    private static int qrHeight=520;
    private static  int qrWidth=520;

    private static int numberWidth=400;
    private static int numberHeight=30;

    private static int digitSpace=21;



    /**
     * 生成条形码
     * @param content
     * @return
     */
    public static String generateBarcode(String content){
        BufferedImage barcodeImage =generateBarcodeImage(content);

        //转换为base64
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(barcodeImage, "png", baos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        byte[] imageBytes = baos.toByteArray();
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);
        return base64Image;


    }
    public static BufferedImage generateBarcodeImage(String content){
        int width=300;
        int height=100;
//        生成二维码
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.CODE_128, width, height);
        } catch (WriterException e) {
            throw new RuntimeException(e);
        }

        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for(int x=0;x<width;x++){
            for(int y=0;y<height;y++){
                bufferedImage.setRGB(x,y,bitMatrix.get(x,y)?0xFF000000:0xFFFFFFFF);
            }
        }
        return  bufferedImage;
    }

    /**
     * 生成二维码
     */
    public static String generateQRCodeBase64(String text,int width,int height){
        HashMap<EncodeHintType, Object> hits = new HashMap<>();
        hits.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

        hits.put(EncodeHintType.ERROR_CORRECTION.MARGIN,1);
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix =null;
        try {
            bitMatrix=qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height,hits);
        } catch (WriterException e) {
            throw new RuntimeException(e);
        }
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for(int x=0;x<width;x++){
            for(int y=0;y<height;y++){
                image.setRGB(x,y,bitMatrix.get(x,y)?0xFF000000:0xFFFFFFFF);
            }
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(image,"png",baos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        byte[] imageBytes = baos.toByteArray();
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);
        return base64Image;


    }



    public static BufferedImage  generateCodeQRToBuffImage(String text,String number){

        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = multiFormatWriter.encode(text, BarcodeFormat.QR_CODE, qrWidth, qrHeight);
        } catch (WriterException e) {
            throw new RuntimeException(e);
        }

        BufferedImage qrImage = toBufferedImage(bitMatrix);

        //给二维码下面添加编号
        addFontImage(qrImage,number);
        // 在二维码下方添加编号
//        Graphics2D g2 = qrImage.createGraphics();
//        g2.setColor(Color.RED);
//        g2.setFont(new Font("Arial", Font.PLAIN, 10));
//
//
        获取自提度量信息
//        FontMetrics fontMetrics = g2.getFontMetrics();
//        int textWidth = fontMetrics.stringWidth(number);
//        int textHeight=fontMetrics.getAscent();
//
//        g2.drawString(number, (width - textWidth) / 2, height + margin + textHeight);
        g2.drawString("12344", 0, 0);
//
//
//        g2.dispose();
      return  qrImage;

    }

    /**
     * 在图片下面加字符串
     * @param
     * @return
     */
    private static void addFontImage(BufferedImage source, String number) {
        //生成image  编号的Image
        int defineWidth = numberWidth;
        int defineHeight = numberHeight;
        BufferedImage textImage = new BufferedImage(defineWidth, defineHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) textImage.getGraphics();
        //开启文字抗锯齿
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,   RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.setBackground(Color.WHITE);
        g2.clearRect(0, 0, defineWidth, defineHeight);
        g2.setPaint(Color.BLACK);
        FontRenderContext context = g2.getFontRenderContext();
        //部署linux需要注意 linux无此字体会显示方块
        Font font = new Font("Arial", Font.BOLD, 30);

        g2.setFont(font);
        LineMetrics lineMetrics = font.getLineMetrics(number, context);
        FontMetrics fontMetrics = FontDesignMetrics.getMetrics(font);
//        float offset = (defineWidth - fontMetrics.stringWidth(number)) / 2;
        float offset=0;
        float y = (defineHeight + lineMetrics.getAscent() - lineMetrics.getDescent() - lineMetrics.getLeading()) / 2;
        for(int i=0;i<number.length();i++){
            char digit=number.charAt(i);
            g2.drawString(String.valueOf(digit),(int)offset,(int)y);
            offset+=digitSpace;
        }
//        g2.drawString(number, (int) offset, (int) y);

        Graphics2D graph = source.createGraphics();
        //开启文字抗锯齿
        graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,   RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        //添加image
        int width = textImage.getWidth(null);
        int height = textImage.getHeight(null);

        graph.drawImage(textImage, (qrWidth-width)/8*5, qrHeight-height*2, width, height, Color.WHITE, null);
        graph.dispose();
    }


    private static BufferedImage myToBufferedImage(BitMatrix bitMatrix) {
        int width=bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
        for(int x=0;x<width;x++){
            for(int y=0;y<height;y++){
                image.setRGB(x,y,bitMatrix.get(x,y)?Color.BLACK.getRGB():Color.WHITE.getRGB());
            }
        }
        return image;

    }

    /**
     * 打印bufferImage  图片
     * @param image
     */
    public static void printImage(BufferedImage image) throws PrintException, IOException {
        // 获取默认打印机
        PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();

        //创建打印机作业
        DocPrintJob printJob = defaultPrintService.createPrintJob();

        //将图像转化为打印文档
        DocFlavor.INPUT_STREAM flavor = DocFlavor.INPUT_STREAM.PNG;
        SimpleDoc doc = new SimpleDoc(imageToInputStream(image), flavor, null);

        //设置纸张大小
        HashPrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
        MediaSize mediaSize = MediaSize.ISO.A7;
        attributes.add(mediaSize.getMediaSizeName());
        //打印
            printJob.print(doc,attributes);

    }

    public static InputStream imageToInputStream(BufferedImage image) throws IOException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();

            ImageIO.write(image,"png",os);

        return  new ByteArrayInputStream(os.toByteArray());
    }

    /**
     * 保存到文件
     */
    public   static void  saveImageToFile(BufferedImage image,String outputName) throws IOException {
        File outputFile = new File(outputName);
        ImageIO.write(image,"png",outputFile);
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值