栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA生成二维码工具类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA生成二维码工具类

依赖





    com.google.zxing
    core
    2.2


    com.google.zxing
    javase
    2.2

代码


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 sun.font.FontDesignMetrics;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;



public class QRcreateUtile {


    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    private QRcreateUtile() {
    }

    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        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, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

    public static void writeToFile(BitMatrix matrix, String format, File file)
            throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format "
                    + format + " to " + file);
        }
    }

    public static void writeToFileBgTransparentAndAddFont(BitMatrix matrix, String format, File file, String addText)
            throws IOException {
        BufferedImage image = toBufferedImage(matrix);

        image = QRcreateUtile.transparentImage(image, 10);

        QRcreateUtile.addFontImage(image, addText);

        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format "
                    + format + " to " + file);
        }
    }

    public static void writeToStream(BitMatrix matrix, String format,
                                     OutputStream stream) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        }
    }

    
    public static File wirter2File(String cardNoName,String text,String vcode,String dirName) throws WriterException, IOException {

       //String text = "http://www.baidu.com"; // 二维码内容
       int width = 300; // 二维码图片宽度
       int height = 300; // 二维码图片高度
       String format = "png";// 二维码的图片格式

       Hashtable hints = new Hashtable();
       hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); // 内容所使用字符集编码

       BitMatrix bitMatrix = new MultiFormatWriter().encode(text,
               BarcodeFormat.QR_CODE, width, height, hints);
       File directory = new File("");// 参数为空
       String courseFile = directory.getCanonicalPath();
       //System.out.println(courseFile);

        String path = courseFile + File.separator + "dir" + File.separator + vcode + File.separator + dirName + File.separator;
        File file = new File(path);
        if(!file.exists()){//如果文件夹不存在
            file.mkdir();//创建文件夹
        }
        // 生成二维码
        File outputFile = new File(   path + File.separator + cardNoname + ".png");
        outputFile.mkdirs();
        outputFile.createNewFile();
        QRcreateUtile.writeToFileBgTransparentAndAddFont(bitMatrix, format, outputFile, cardNoName);
        return outputFile;
   }

    
    public static BufferedImage transparentImage(BufferedImage srcImage, int alpha) throws IOException {
        int imgHeight = srcImage.getHeight();//取得图片的长和宽
        int imgWidth = srcImage.getWidth();
        int c = srcImage.getRGB(3, 3);
        //防止越位
        if (alpha < 0) {
            alpha = 0;
        } else if (alpha > 10) {
            alpha = 10;
        }
        BufferedImage tmpImg = new BufferedImage(imgWidth + 10, imgHeight + 10, BufferedImage.TYPE_4BYTE_ABGR);//新建一个类型支持透明的BufferedImage
        for(int i = 0; i < imgWidth; ++i)//把原图片的内容复制到新的图片,同时把背景设为透明
        {
            for(int j = 0; j < imgHeight; ++j){
                //把背景设为透明
                if(srcImage.getRGB(i, j) == c){
                    tmpImg .setRGB(i, j, c & 0x00ffffff);
                }
                //设置透明度
                else{
                    int rgb = tmpImg .getRGB(i, j);
                    rgb = ((alpha * 255 / 10) << 24) | (rgb & 0x00ffffff);
                    tmpImg .setRGB(i, j, rgb);
                }
            }
        }

        return tmpImg ;
    }

    // 二维码尺寸
    private static final int QRCODE_SIZE = 300;
    // 字体大小
    private static final int FONT_SIZE = 18;

    
    private static void addFontImage(BufferedImage source, String declareText) throws IOException {
        BufferedImage textImage = strToImage(declareText, QRCODE_SIZE, 50);
        Graphics2D g2 = source.createGraphics();

        //开启文字抗锯齿
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        int width = textImage.getWidth(null);
        int height = textImage.getHeight(null);

        Image src = textImage;
        g2.drawImage(src, 0, QRCODE_SIZE - 40, width, height, null);
        g2.dispose();
    }

    private static BufferedImage strToImage(String str, int width, int height) throws IOException {
        BufferedImage textImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D)textImage.getGraphics();

        textImage = g2.getDeviceConfiguration()
                .createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g2.dispose();
        g2 = textImage.createGraphics();

        //开启文字抗锯齿
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.setBackground(Color.WHITE);
        g2.setPaint(Color.BLACK);
        FontRenderContext context = g2.getFontRenderContext();
        Font font = new Font("微软雅黑", Font.PLAIN, FONT_SIZE);
        g2.setFont(font);
        LineMetrics lineMetrics = font.getLineMetrics(str, context);
        FontMetrics fontMetrics = FontDesignMetrics.getMetrics(font);
        float offset = (width - fontMetrics.stringWidth(str)) / 2;
        float y = (height + lineMetrics.getAscent() - lineMetrics.getDescent() - lineMetrics.getLeading()) / 2;

        g2.drawString(str, (int)offset, (int)y);

        return textImage;
    }

    public static void main(String[] args) throws IOException, WriterException {
        wirter2File("test","test","xxx" , "2021-11-11");
    }
}




转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/770287.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号