首页 > 其他分享 >生成带logo二维码+批量压缩导出

生成带logo二维码+批量压缩导出

时间:2024-07-12 10:52:34浏览次数:10  
标签:int image 导出 new 二维码 borderWidth import logo

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
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.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static java.util.Objects.nonNull;

public class QrCodeZXingUtils {
    private static final int QRCOLOR = 0xFF000000; // 默认是黑色
    private static final int BGWHITE = 0xFFFFFFFF; // 背景颜色

    private static final int WIDTH = 200; // 二维码宽
    private static final int HEIGHT = 200; // 二维码高

    // 用于设置QR二维码参数
    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        private static final long serialVersionUID = 1L;

        {
            put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别(H为最高级别)具体级别信息
            put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
            put(EncodeHintType.MARGIN, 0);
        }
    };


    // 生成带logo的二维码图片
    /***
     *@param logoFile  logo图地址
     * @param codeFile  二维码生成地址
     * @param qrUrl 扫描二维码方位地址
     * */
    public static void drawLogoQRCode(File logoFile, File codeFile, String qrUrl) {
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
            BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
            // 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色
            for (int x = 0; x < WIDTH; x++) {
                for (int y = 0; y < HEIGHT; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
                }
            }
            int width = image.getWidth();
            int height = image.getHeight();
            if (nonNull(logoFile) && logoFile.exists()) {
                // 构建绘图对象
                Graphics2D g = image.createGraphics();
                // 读取Logo图片
                BufferedImage logo = ImageIO.read(logoFile);
                // 开始绘制logo图片
                g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
                g.dispose();
                logo.flush();
            }
            image.flush();
            ImageIO.write(image, "png", codeFile);
            zip(image);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 添加边框,未成功,待测试
    private static BufferedImage addBorder(BufferedImage image) {
        int borderWidth = 10; // 边框宽度
        BufferedImage borderedImage = new BufferedImage(image.getWidth() + borderWidth * 2,
                image.getHeight() + borderWidth * 2,
                BufferedImage.TYPE_INT_RGB);
        // 使用白色填充边框区域
        for (int x = 0; x < borderedImage.getWidth(); x++) {
            for (int y = 0; y < borderedImage.getHeight(); y++) {
                if (x < borderWidth || x >= borderWidth + image.getWidth() ||
                        y < borderWidth || y >= borderWidth + image.getHeight()) {
                    borderedImage.setRGB(x, y, 0xFFFFFFFF); // 白色
                }
            }
        }
        // 将二维码图像复制到带有边框的图像上
        for (int x = borderWidth, y = borderWidth;
             x - borderWidth < image.getWidth() && y - borderWidth < image.getHeight(); x++, y++) {
            borderedImage.setRGB(x, y, image.getRGB(x - borderWidth, y - borderWidth));
        }
        return borderedImage;
    }
    public static void main(String[] args) throws  Exception {
        //头像logo
        File logoFile = new File("C:\\Users\\86181\\Desktop\\2.png");
        //生成二维码地址
        File QrCodeFile = new File("C:\\Users\\86181\\Desktop\\3.png");
        String url = "https://www.baidu.com/";
        drawLogoQRCode(logoFile, QrCodeFile, url);

        //mergeImage("C:\\Users\\86181\\Desktop\\66.png", "C:\\Users\\86181\\Desktop\\3.png", "C:\\Users\\86181\\Desktop\\test.png","30", "100");
    }



    /***
     * 二维码嵌套背景图的方法
     *@param bigPath 背景图 - 可传网络地址
     *@param smallPath 二维码地址 - 可传网络地址
     *@param newFilePath 生成新图片的地址
     * @param  x 二维码x坐标
     *  @param  y 二维码y坐标
     * */
    public static void mergeImage(String bigPath, String smallPath, String newFilePath,String x, String y) throws IOException {

        try {
            BufferedImage small;
            BufferedImage big;
            if (bigPath.contains("http://") || bigPath.contains("https://")) {
                URL url = new URL(bigPath);
                big = ImageIO.read(url);
            } else {
                big = ImageIO.read(new File(bigPath));
            }


            if (smallPath.contains("http://") || smallPath.contains("https://")) {

                URL url = new URL(smallPath);
                small = ImageIO.read(url);
            } else {
                small = ImageIO.read(new File(smallPath));
            }

            Graphics2D g = big.createGraphics();

            float fx = Float.parseFloat(x);
            float fy = Float.parseFloat(y);
            int x_i = (int) fx;
            int y_i = (int) fy;
            g.drawImage(small, x_i, y_i, small.getWidth(), small.getHeight(), null);
            Font font = new Font("SimSun", Font.BOLD, 36); // 使用宋体字体,设置字体大小为36
            g.setFont(font);
            g.setColor(Color.BLACK); // 设置文字颜色为红色
            String text = "你好,世界!"; // 要添加的文字内容
            g.drawString(text, 300, 400); // 在指定位置绘制文字
            g.dispose();
            ImageIO.write(big, "png", new File(newFilePath));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void zip(BufferedImage image) {
        try {
            File outputFile = new File("output.png");
            ImageIO.write(image, "png", outputFile);

            FileOutputStream fos = new FileOutputStream("imageFolder.zip");
            ZipOutputStream zos = new ZipOutputStream(fos);
            ZipEntry zipEntry = new ZipEntry("output.png");
            zos.putNextEntry(zipEntry);

            FileInputStream fis = new FileInputStream(outputFile);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, length);
            }

            fis.close();
            zos.closeEntry();
            zos.close();

            // Delete the original file
            outputFile.delete();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  

标签:int,image,导出,new,二维码,borderWidth,import,logo
From: https://www.cnblogs.com/foreverstudy/p/18297848

相关文章

  • pandas导出excel
    工具类cvsutil.py#!/usr/bin/envpython#-*-coding:utf-8-*-importcsvimportcodecsimportioclassUTF8Recoder:"""IteratorthatreadsanencodedstreamandreencodestheinputtoUTF-8"""def__init_......
  • 浅析文件如何生成二维码,以及文件二维码的广泛应用
    随着智能手机的普及和移动互联网的飞速发展,二维码已经深入到人们生活的各个领域,为人们的生活带来了极大的便利。文件二维码具有信息容量大、编码范围广、容错能力强、译码可靠性高、可引入加密措施、成本低、易制作、持久耐用等优点。因此,文件二维码在各行各业得到非常广泛......
  • POI导出案例
    /** *POI方式导出 *@paramlist数据 *@paramexportFields绑定列数组,0:表头,1:数据key *@paramresponse */ publicstaticvoidexportExcel(Listlist,String[]exportFields,HttpServletResponseresponse){ Workbookwb=newXSSFWorkbook(); /......
  • java导出PDF文件
    我们需要将生成的PDF文件直接导出到浏览器而不是保存到本地,需要对HttpServletResponse进行配置,将PDF写入到响应流中。以下是可以将PDF导出到浏览器进行下载:我们首先先编写PDF工具类:packagecom.scenic.util;importcom.itextpdf.text.*;importcom.itextpdf.text.pdf.*;im......
  • AI绘画comfyui工作流,商业海报设计、Logo设计,一个comfyui工作流就能搞定!
    前言创新设计工作流:轻松打造LOGO和海报本文涉及的工作流和插件,需要的朋友请扫描免费获取哦—HAPPYNEWYEAR—大家好!今天我要分享的是一个高效且创新的设计工作流,这一工具由国外的网友无私分享,适用于LOGO设计和海报创作。这不仅是对开源精神的致敬,也为我们的设计工......
  • 在 PowerShell 中,你可以使用一些命令来管理打印机驱动的导入和导出操作。通过这些 Pow
    更高级的PowerShell自动化打印机迁移,可以考虑以下步骤和技术:自动化打印机迁移流程批量导出和导入打印机配置使用PowerShell脚本批量导出和导入多个打印机的配置。可以结合循环和数组来处理多个打印机。powershellCopyCode#批量导出打印机配置$printers=Get-Printe......
  • 【20240709】海量图片导出需求,shell脚本
     [root@localhostimages]#catjunshuv3.sh#!/bin/bash#确保脚本在~/images目录下运行if["$(pwd)"!="$HOME/images"];thencd~/imagesfi#创建目标目录junshu,如果不存在则创建mkdir-pjunshu#获取CSV文件中的总行数,用于进度条total_lines=$(wc-l......
  • Oracle数据库使用expdp/impdp导出导入数据
    背景:正式环境数据同步到测试环境,数据库名:MYDB,正式、用户:MYUSER(必须拥有SYS权限)。1、正式环境备份数据库(1)正式服务器上,cmd输入sqlplus,使用MYUSER账户登录(2)创建一个自定义的目录,用于存放导出的数据createdirectoryDATA_OUT_FILEas'E:\app\Administrator\admin\MYDB\my_dir\'......
  • oracle数据库导出数据时密码中存在特殊符号的情况处理
    oracle数据库导出指定的表数据,直接在windows的cmd命令行执行如下命令:expwz9199/""“wzz@123"”"@172.17.34.40:1521/orclfile=E:\temp\exp.dmptables=(T_User)命令详细说明:exp代表我们要进行导出操作;wz9199是用户名;wzz@123是密码;在密码两边拼接的三个双引号是为了适配密码中有......
  • Laravel Excel导出功能:高效实现数据导出
    Laravel是一个功能丰富的PHPWeb开发框架,它提供了许多内置功能来简化开发过程。其中,LaravelExcel导出功能是处理数据导出任务的强大工具。通过使用Maatwebsite的LaravelExcel包,开发者可以轻松地将数据集导出为Excel文件,这对于报告生成、数据备份和用户数据下载等场景非常......