Java生成二维码并贴到新的图片上

一、简述
1、Java生成二维码以来一些第三方库,本地的api会有一些bug,比如生成图片会造成红色蒙版,还有当二维码中字数过多,会造成二维码大小出现问题,要不就是二维码很大,要不就是二维码白边很大。
解决办法:一般二维码扫描是链接,但是有的会带着id或者uuid或者营销员的信息,为了使链接变短,使二维码正常,将链接过长的部门进行参数hash,将链接变短,使二维码正常

maven
		<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>core</artifactId>
			<version>3.4.1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>javase</artifactId>
			<version>3.4.1</version>
		</dependency>
		<dependency>
			<groupId>cn.hutool</groupId>
			<artifactId>hutool-extra</artifactId>
			<version>5.4.3</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>simpleimage</artifactId>
			<version>1.2.3</version>
		</dependency>
		<dependency>
			<groupId>com.sun.media</groupId>
			<artifactId>jai-codec</artifactId>
			<version>1.1.3</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
		<dependency>
			<groupId>net.coobird</groupId>
			<artifactId>thumbnailator</artifactId>
			<version>0.4.14</version>
		</dependency>
		<dependency>
			<groupId>com.twelvemonkeys.imageio</groupId>
			<artifactId>imageio-jpeg</artifactId>
			<version>3.3.2</version>
		</dependency>

附代码:

@Component
public class MyQrCodeUtils {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private QrCodeService qrCodeService;

    /***
     * 在一张背景图上添加二维码
     */
    public String drawString(String content, QRCodeCoordinates qRCodeCoordinates,String instNo) throws Exception {
        BufferedImage image = this.addWaters(content,qRCodeCoordinates,instNo);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        Thumbnails.of(image).scale(1f).outputFormat("jpeg").toOutputStream(output);
        Base64.Encoder encoder = Base64.getEncoder(); // 实例化一个对byte[]型数据进行64位编码的对象
        String blob = encoder.encodeToString(output.toByteArray());
        String returnInfo = "data:image/jpeg;base64," + blob; // 前台直接把returnInfo放入img标签的src中
        logger.warn("图长度为:"+returnInfo.length());
        output.close();
        return returnInfo;
    }

    public  BufferedImage addWaters(String content,QRCodeCoordinates qRCodeCoordinates,String instNo)
            throws Exception {
        // 获取底图
        String path = qRCodeCoordinates.getPath();
        InputStream inputStream = getInputStream(path);
        BufferedImage buffImg = Thumbnails.of(inputStream).scale(1.0)
                .asBufferedImage();
        // 获取层图
        Integer qrw = qRCodeCoordinates.getQrw();
        logger.warn("层图qrw:"+qrw);
        //中间log的地址
        String middlePic = "logoUrl";
        logger.warn("logoUrl:===="+middlePic);
        BufferedImage waterImg =
                qrCodeService.createQrCodeWithLogoAndNodeCorner(content, qrw, getInputStream(middlePic), instNo);
        // 创建Graphics2D对象,用在底图对象上绘图
        Graphics2D g2d = buffImg.createGraphics();
        int waterImgWidth = waterImg.getWidth();// 获取层图的宽度
        int waterImgHeight = waterImg.getHeight();// 获取层图的高度
        // 在图形和图像中实现混合和透明效果
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1f));
        // 绘制
        g2d.drawImage(waterImg, qRCodeCoordinates.getOffsetx(), qRCodeCoordinates.getOffsety(), waterImgWidth, waterImgHeight, null);
        g2d.dispose();// 释放图形上下文使用的系统资源
        return buffImg;

    }
    private static final String CHARSET = "utf-8";

    private  BufferedImage createQrCode2(String content, int width, int height,String middlePic) throws Exception {
        QrConfig config = new QrConfig(width, height);
        if(!StringUtils.isEmpty(middlePic)){
            Image image = ImageIO.read(getInputStream(middlePic));
            config.setImg(image);
        }
        config.setErrorCorrection(ErrorCorrectionLevel.L);
        config.setMargin(1);
        BitMatrix bitMatrix = QrCodeUtil.encode(content,
                config);
        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) ? BLACK
                        : WHITE );
            }
        }
        return image;
    }


    private static BufferedImage createQrCode(String content, int width, int height,String middlePic) throws IOException {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = new MultiFormatWriter().encode(content,
                    BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        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) ? BLACK
                        : WHITE);
            }
        }
        return image;
    }

    public static InputStream resourceLoader(String fileFullPath) throws IOException {
        InputStream fileInputStream = new FileInputStream(new File(fileFullPath));
        return fileInputStream;
    }

    public  InputStream getInputStream(String urls)throws Exception {
        return getHttpString(urls);
    }

    public InputStream getHttpString(String path) {
        // 网络请求所需变量
        InputStream in = null;
        try {
            URL url = new URL(path);
            // 根据Url打开地址,以utf-8编码的形式返回输入流
            in = url.openStream();
            return in;
        } catch ( Exception e) {
            
        }  
        return null;
    }

}
以下是Java生成二维码并保存图片的示例代码: ```java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; public class QRCodeGenerator { public static void main(String[] args) { String text = "https://www.csdn.net"; int width = 500; int height = 500; String format = "jpg"; String filePath = "d://test//out.jpg"; String logoPath = "E:\\test.jpg"; try { QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height); 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); } } File qrFile = new File(filePath); ImageIO.write(bufferedImage, format, qrFile); if (logoPath != null && !"".equals(logoPath.trim())) { QRCodeUtil.addLogo(qrFile, new File(logoPath), new LogoConfig()); } } catch (WriterException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 其中,QRCodeUtil是一个工具类,用于在二维码中添加Logo。你可以在这里找到QRCodeUtil的完整代码:https://github.com/liuyueyi/quick-media/blob/master/quick-media/src/main/java/com/github/hui/quick/plugin/qrcode/util/QRCodeUtil.java
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会改bug的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值