All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.luues.util.qrcode.QRCodeUtil Maven / Gradle / Ivy

There is a newer version: 1.3.0.5.RELEASE
Show newest version
package com.luues.util.qrcode;

import com.luues.util.logs.LogUtil;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;

public class QRCodeUtil {

    /**
     * 绘制二维码
     *
     * @param contents 二维码内容
     * @return image 二维码图片
     */
    public static BufferedImage encodeImg(String contents) {
        BufferedImage image = null;
        try {
            BitMatrix matrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
            //1.1去白边
            int[] rec = matrix.getEnclosingRectangle();
            int resWidth = rec[2] + 1;
            int resHeight = rec[3] + 1;
            BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
            resMatrix.clear();
            for (int i = 0; i < resWidth; i++) {
                for (int j = 0; j < resHeight; j++) {
                    if (matrix.get(i + rec[0], j + rec[1])) {
                        resMatrix.set(i, j);
                    }
                }
            }
//2
            int width = resMatrix.getWidth();
            int height = resMatrix.getHeight();
            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, resMatrix.get(x, y) == true ?
                            Color.BLACK.getRGB() : Color.WHITE.getRGB());
                }
            }

			/*image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			int width = matrix.getWidth();
			int height = matrix.getHeight();
			for (int x = 0; x < width; x++) {
				for (int y = 0; y < height; y++) {
					image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
				}
			}*/
        } catch (Exception e) {
            LogUtil.error("生成二维码失败" + e.getMessage());
        }
        return image;
    }

    /**
     * 绘制二维码
     *
     * @param contents 二维码内容
     * @param logPath  log地址
     * @return image 二维码图片
     */
    public static BufferedImage encodeImgLogo(String contents, String logPath) {
        BufferedImage image = null;
        try {
            BitMatrix matrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
            //1.1去白边
            int[] rec = matrix.getEnclosingRectangle();
            int resWidth = rec[2] + 1;
            int resHeight = rec[3] + 1;
            BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
            resMatrix.clear();
            for (int i = 0; i < resWidth; i++) {
                for (int j = 0; j < resHeight; j++) {
                    if (matrix.get(i + rec[0], j + rec[1])) {
                        resMatrix.set(i, j);
                    }
                }
            }
            int width = resMatrix.getWidth();
            int height = resMatrix.getHeight();
            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, resMatrix.get(x, y) == true ?
                            Color.BLACK.getRGB() : Color.WHITE.getRGB());
                }
            }
            //获取画笔
            Graphics2D g = image.createGraphics();
            //读取logo图片
            BufferedImage logo = ImageIO.read(new File(logPath));
            //设置二维码大小,太大,会覆盖二维码,此处20%
            int logoWidth = logo.getWidth(null) > image.getWidth() * 2 / 10 ? (image.getWidth() * 2 / 10) : logo.getWidth(null);
            int logoHeight = logo.getHeight(null) > image.getHeight() * 2 / 10 ? (image.getHeight() * 2 / 10) : logo.getHeight(null);
            //设置logo图片放置位置
            //中心
            int x = (image.getWidth() - logoWidth) / 2;
            int y = (image.getHeight() - logoHeight) / 2;
            //右下角,15为调整值
//	          int x = twodimensioncode.getWidth()  - logoWidth-15;
//	          int y = twodimensioncode.getHeight() - logoHeight-15;
            //开始合并绘制图片
            g.drawImage(logo, x, y, logoWidth, logoHeight, null);
            g.drawRoundRect(x, y, logoWidth, logoHeight, 15, 15);
            //logo边框大小
            g.setStroke(new BasicStroke(2));
            //logo边框颜色
            g.setColor(Color.WHITE);
            g.drawRect(x, y, logoWidth, logoHeight);
            g.dispose();
            logo.flush();
            image.flush();
        } catch (Exception e) {
            LogUtil.error("生成二维码失败" + e.getMessage());
        }
        return image;
    }

    /**
     * 二维码绘制logo
     *
     * @param twodimensioncodeImg 二维码图片文件
     * @param logoImg             logo图片文件
     */
    public static BufferedImage encodeImgLogo(File twodimensioncodeImg, File logoImg) {
        BufferedImage twodimensioncode = null;
        try {
            if (!twodimensioncodeImg.isFile() || !logoImg.isFile()) {
                LogUtil.error("输入非图片");
                return null;
            }
            //读取二维码图片
            twodimensioncode = ImageIO.read(twodimensioncodeImg);
            //获取画笔
            Graphics2D g = twodimensioncode.createGraphics();
            //读取logo图片
            BufferedImage logo = ImageIO.read(logoImg);
            //设置二维码大小,太大,会覆盖二维码,此处20%
            int logoWidth = logo.getWidth(null) > twodimensioncode.getWidth() * 2 / 10 ? (twodimensioncode.getWidth() * 2 / 10) : logo.getWidth(null);
            int logoHeight = logo.getHeight(null) > twodimensioncode.getHeight() * 2 / 10 ? (twodimensioncode.getHeight() * 2 / 10) : logo.getHeight(null);
            //设置logo图片放置位置
            //中心
            int x = (twodimensioncode.getWidth() - logoWidth) / 2;
            int y = (twodimensioncode.getHeight() - logoHeight) / 2;
            //右下角,15为调整值
//	          int x = twodimensioncode.getWidth()  - logoWidth-15;
//	          int y = twodimensioncode.getHeight() - logoHeight-15;
            //开始合并绘制图片
            g.drawImage(logo, x, y, logoWidth, logoHeight, null);
            g.drawRoundRect(x, y, logoWidth, logoHeight, 15, 15);
            //logo边框大小
            g.setStroke(new BasicStroke(2));
            //logo边框颜色
            g.setColor(Color.WHITE);
            g.drawRect(x, y, logoWidth, logoHeight);
            g.dispose();
            logo.flush();
            twodimensioncode.flush();
        } catch (Exception e) {
            LogUtil.error("二维码绘制logo失败");
        }
        return twodimensioncode;
    }


    /**
     * 图片绘制其他图片
     *
     * @param twodimensioncodeImg 主图片文件
     * @param Img                 另一个图片文件
     */
    public static BufferedImage encodeOtherImg(File twodimensioncodeImg, File Img, int yy) {
        BufferedImage twodimensioncode = null;
        try {
            if (!twodimensioncodeImg.isFile() || !Img.isFile()) {
                LogUtil.error("输入非图片");
                return null;
            }
            //读取二维码图片
            twodimensioncode = ImageIO.read(twodimensioncodeImg);
            //获取画笔
            Graphics2D g = twodimensioncode.createGraphics();
            //读取logo图片
            BufferedImage logo = ImageIO.read(Img);
            //设置二维码大小,太大,会覆盖二维码,此处20%
            int logoWidth = 300;//logo.getWidth(null) > twodimensioncode.getWidth()*2 /10 ? (twodimensioncode.getWidth()*2 /10) : logo.getWidth(null);
            int logoHeight = 300;//logo.getHeight(null) > twodimensioncode.getHeight()*2 /10 ? (twodimensioncode.getHeight()*2 /10) : logo.getHeight(null);
            //设置logo图片放置位置
            //中心
            int x = (twodimensioncode.getWidth() - logoWidth) / 2;
            int y = (twodimensioncode.getHeight() - logoHeight) / 2;
            //右下角,15为调整值
//	          int x = twodimensioncode.getWidth()  - logoWidth-15;
//	          int y = twodimensioncode.getHeight() - logoHeight-15;
            //开始合并绘制图片
            g.drawImage(logo, x, y + yy, logoWidth, logoHeight, null);
            g.drawRoundRect(x, y + yy, logoWidth, logoHeight, 15, 15);
            //logo边框大小
            g.setStroke(new BasicStroke(2));
            //logo边框颜色
            g.setColor(Color.WHITE);
            g.drawRect(x, y + yy, logoWidth, logoHeight);
            g.dispose();
            logo.flush();
            twodimensioncode.flush();
        } catch (Exception e) {
            LogUtil.error("二维码绘制logo失败");
        }
        return twodimensioncode;
    }


    public static String Decode(File file) {
        BufferedImage image;
        try {
            image = ImageIO.read(file);
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map hints = new HashMap();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
            return result.getText();
        } catch (IOException e) {
        } catch (NotFoundException e) {
        }
        return null;
    }

    private static int width = 400;
    private static int height = 400;
    // 二维码颜色
    private static final int BLACK = 0xFF000000;// 0xFFFF0000,红色
    // 二维码背景色
    private static final int WHITE = 0xFFFFFFFF;// 0xFF0000FF,蓝色
    // 注:二维码颜色色差大,扫描快,但如果"BLACK'设置为黑色外其他颜色,可能无法扫描

    // 二维码格式参数
    private static final EnumMap hints = new EnumMap(EncodeHintType.class);

    static {
        /*
         * 二维码的纠错级别(排错率),4个级别: L (7%)、 M (15%)、 Q (25%)、 H (30%)(最高H)
         * 纠错信息同样存储在二维码中,纠错级别越高,纠错信息占用的空间越多,那么能存储的有用讯息就越少;共有四级; 选择M,扫描速度快。
         */
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 二维码边界空白大小 1,2,3,4 (4为默认,最大)
        hints.put(EncodeHintType.MARGIN, 0);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MAX_SIZE, 350);
        hints.put(EncodeHintType.MIN_SIZE, 150);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy