Java实现将两张图片合成一张图片,并且实现批量下载

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;

public class ImageMerging {
    private Font font = new Font("微软雅黑", Font.PLAIN, 46); // 添加字体的属性设置

    private Graphics2D g = null;

    private int fontsize = 0;

    private int x = 0;

    private int y = 0;

    /**
     * 导入本地图片到缓冲区
     */
    public BufferedImage loadImageLocal(String imgName) {
        try {
            return ImageIO.read(new File(imgName));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * 导入网络图片到缓冲区
     */
    public BufferedImage loadImageUrl(String imgName) {
        try {
            URL url = new URL(imgName);
            return ImageIO.read(url);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * 生成新图片到本地
     */
    public void writeImageLocal(String newImage, BufferedImage img) {
        if (newImage != null && img != null) {
            try {
                File outputfile = new File(newImage);
                ImageIO.write(img, "jpg", outputfile);
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }

    /**
     * 设定文字的字体等
     */
    public void setFont(String fontStyle, int fontSize) {
        this.fontsize = fontSize;
        this.font = new Font(fontStyle, Font.PLAIN, fontSize);
    }

    /**
     * 修改图片,返回修改后的图片缓冲区(只输出一行文本)
     */
    public BufferedImage modifyImage(BufferedImage img, Object content, int x, int y) {

        try {
            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();
            g.setBackground(new Color(255, 255, 255, 0));
            g.setColor(Color.WHITE);//设置字体颜色
            g.setFont(new Font("微软雅黑", Font.PLAIN, 46));
            if (this.font != null)
                g.setFont(this.font);
            // 验证输出位置的纵坐标和横坐标  
            if (x >= h || y >= w) {
                this.x = h - this.fontsize + 2;
                this.y = w;
            } else {
                this.x = x;
                this.y = y;
            }
            if (content != null) {
                g.drawString(content.toString(), this.x, this.y);
            }
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return img;
    }

    /**
     * 修改图片,返回修改后的图片缓冲区(输出多个文本段) xory:true表示将内容在一行中输出;false表示将内容多行输出
     */
    public BufferedImage modifyImage(BufferedImage img, Object[] contentArr, int x, int y,
                                     boolean xory) {
        try {
            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();
            g.setBackground(Color.WHITE);
            g.setColor(Color.RED);
            if (this.font != null)
                g.setFont(this.font);
            // 验证输出位置的纵坐标和横坐标  
            if (x >= h || y >= w) {
                this.x = h - this.fontsize + 2;
                this.y = w;
            } else {
                this.x = x;
                this.y = y;
            }
            if (contentArr != null) {
                int arrlen = contentArr.length;
                if (xory) {
                    for (int i = 0; i < arrlen; i++) {
                        g.drawString(contentArr[i].toString(), this.x, this.y);
                        this.x += contentArr[i].toString().length() * this.fontsize / 2 + 5;// 重新计算文本输出位置  
                    }
                } else {
                    for (int i = 0; i < arrlen; i++) {
                        g.drawString(contentArr[i].toString(), this.x, this.y);
                        this.y += this.fontsize + 2;// 重新计算文本输出位置  
                    }
                }
            }
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return img;
    }

    /**
     * 修改图片,返回修改后的图片缓冲区(只输出一行文本)
     * <p>
     * @param img
     * @return
     */
    public BufferedImage modifyImageYe(BufferedImage img) {

        try {
            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();
            g.setBackground(Color.WHITE);
            g.setColor(Color.blue);//设置字体颜色  
            if (this.font != null)
                g.setFont(this.font);
            //g.drawString("www.hi.baidu.com?xia_mingjian", w - 85, h - 5);
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return img;
    }

    public BufferedImage modifyImagetogeter(BufferedImage b, BufferedImage d, int width, int height) {
        try {
            int w = b.getWidth();
            int h = b.getHeight();
            g = d.createGraphics();
            g.drawImage(b, width, height, w, h, null);
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return d;
    }



    public static void main(String[] args) {
        ImageMerging tt = new ImageMerging();
        BufferedImage b = tt.loadImageLocal("E:\\image\\33.png");
        BufferedImage d = tt.loadImageLocal("E:\\image\\44.png");
        //往图片上写文件
        BufferedImage aaaaaaaa = tt.modifyImage(b, "勇衣小吃店", 578, 999);
        tt.writeImageLocal("E:\\image\\cc.jpg", tt.modifyImagetogeter(d, aaaaaaaa, 342, 218));

        //将多张图片合在一起  
        System.out.println("success");
    }

}

如果想要复用一张背景图片,并且想要每次给背景图片上面添加不同内容,那就需要将复用的背景图片进行拷贝,然后对副本进行拷贝,可以减少IO操作,提高效率。

/**
     * BufferedImage拷贝
     * @param source
     * @return
     */
    public BufferedImage copyImage(BufferedImage source) {
        BufferedImage copyBufferedImage = new BufferedImage(source.getWidth(), source.getHeight(), source.getType());
        Graphics g = copyBufferedImage.getGraphics();
        g.drawImage(source, 0, 0, null);
        g.dispose();
        return copyBufferedImage;
    }
    /**
     * 批量生成照片时,如果背景图片是一个时,对其进行拷贝在修改。
     * @param pic ImageMerging  对象
     * @param unitName  需要添加的文字,
     * @param qRCode  需要合并的图片 这里是二维码
     * @param backgroundImage  背景图片
     * @return
     */
    public BufferedImage qRCodeGeneration(ImageMerging pic, String unitName, BufferedImage qRCode, BufferedImage backgroundImage, FontMetrics fontMetrics) {
    //FontMetrics fontMetrics= new JLabel().getFontMetrics(new Font("微软雅黑", Font.PLAIN, 46));
    	//计算文字的像素宽度  unitName是添加的字体
        int strWidth = fontMetrics.stringWidth(unitName);
		//拷贝背景图片
        BufferedImage copyBufferedImage = copyImage(backgroundImage);
		//往拷贝的背景图片上面添加文字,进行居中处理
		//1400 是背景图片宽度
		//1050 是设计字体距离背景图片顶部的距离
        BufferedImage backgroundAndName = pic.modifyImage(copyBufferedImage, unitName, (1400 - strWidth) / 2, 1050);
		//将背景图片和二维码合并
        BufferedImage bufferedImage = pic.modifyImagetogeter(qRCode, backgroundAndName, 342, 218);

        return bufferedImage;
    }

实现批量下载,和照片批量生成

public void generateQRCode(@RequestParam(required = false) Long unitId, HttpServletResponse response) throws Exception {
        long start = System.currentTimeMillis();
        List<DrugUnitInfo> drugUnitList = new ArrayList<>();
        if (unitId == null) {
            drugUnitList = drugUnitInfoService.list();
        } else {
            DrugUnitInfo drugUnitInfo = drugUnitInfoService.getById(unitId);
            drugUnitList.add(drugUnitInfo);
        }

        String downloadFilename = "药品二维码";
        downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");
        ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment; filename=" + downloadFilename + ".zip");
        AtomicReference<BufferedImage> encode = new AtomicReference<>();


        ImageMerging pic = new ImageMerging();
        FontMetrics metrics = new JLabel().getFontMetrics(new Font("微软雅黑", Font.PLAIN, 46));
        BufferedImage backgroundImage = pic.loadImageLocal("E:\\image\\33.png");
        drugUnitList.forEach(i -> {
            if (!StringUtils.isEmpty(i.getUnitNo())) {
                try {
                    encode.set(QRCodeUtil.encode(host + ":" + port + urlPrefix + i.getId(), null, true));
                    BufferedImage bufferedImage = pic.qRCodeGeneration(pic, i.getUnitName(), encode.get(), backgroundImage, metrics);
                    zos.putNextEntry(new ZipEntry(i.getUnitName() + ".png"));
                    ImageIO.write(bufferedImage, "png", zos);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        zos.flush();
        zos.close();
        long end = System.currentTimeMillis();
        System.out.println("执行完时间:" + (end - start));
    }
完整版ImageMerging
package com.swkj.smart.market.regulation.sysmanage.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;

public class ImageMerging {
    private Font font = new Font("微软雅黑", Font.PLAIN, 46); // 添加字体的属性设置

    private Graphics2D g = null;

    private int fontsize = 0;

    private int x = 0;

    private int y = 0;

    /**
     * 导入本地图片到缓冲区
     */
    public BufferedImage loadImageLocal(String imgName) {
        try {
            return ImageIO.read(new File(imgName));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * 导入网络图片到缓冲区
     */
    public BufferedImage loadImageUrl(String imgName) {
        try {
            URL url = new URL(imgName);
            return ImageIO.read(url);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * 生成新图片到本地
     */
    public void writeImageLocal(String newImage, BufferedImage img) {
        if (newImage != null && img != null) {
            try {
                File outputfile = new File(newImage);
                ImageIO.write(img, "jpg", outputfile);
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }

    /**
     * 设定文字的字体等
     */
    public void setFont(String fontStyle, int fontSize) {
        this.fontsize = fontSize;
        this.font = new Font(fontStyle, Font.PLAIN, fontSize);
    }

    /**
     * 修改图片,返回修改后的图片缓冲区(只输出一行文本)
     */
    public BufferedImage modifyImage(BufferedImage img, Object content, int x, int y) {

        try {
            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();
            g.setBackground(new Color(255, 255, 255, 0));
            g.setColor(Color.WHITE);//设置字体颜色
            g.setFont(new Font("微软雅黑", Font.PLAIN, 46));
            if (this.font != null)
                g.setFont(this.font);
            // 验证输出位置的纵坐标和横坐标  
            if (x >= h || y >= w) {
                this.x = h - this.fontsize + 2;
                this.y = w;
            } else {
                this.x = x;
                this.y = y;
            }
            if (content != null) {
                g.drawString(content.toString(), this.x, this.y);
            }
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return img;
    }

    /**
     * 修改图片,返回修改后的图片缓冲区(输出多个文本段) xory:true表示将内容在一行中输出;false表示将内容多行输出
     */
    public BufferedImage modifyImage(BufferedImage img, Object[] contentArr, int x, int y,
                                     boolean xory) {
        try {
            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();
            g.setBackground(Color.WHITE);
            g.setColor(Color.RED);
            if (this.font != null)
                g.setFont(this.font);
            // 验证输出位置的纵坐标和横坐标  
            if (x >= h || y >= w) {
                this.x = h - this.fontsize + 2;
                this.y = w;
            } else {
                this.x = x;
                this.y = y;
            }
            if (contentArr != null) {
                int arrlen = contentArr.length;
                if (xory) {
                    for (int i = 0; i < arrlen; i++) {
                        g.drawString(contentArr[i].toString(), this.x, this.y);
                        this.x += contentArr[i].toString().length() * this.fontsize / 2 + 5;// 重新计算文本输出位置  
                    }
                } else {
                    for (int i = 0; i < arrlen; i++) {
                        g.drawString(contentArr[i].toString(), this.x, this.y);
                        this.y += this.fontsize + 2;// 重新计算文本输出位置  
                    }
                }
            }
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return img;
    }

    /**
     * 修改图片,返回修改后的图片缓冲区(只输出一行文本)
     * @param img
     * @return
     */
    public BufferedImage modifyImageYe(BufferedImage img) {

        try {
            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();
            g.setBackground(Color.WHITE);
            g.setColor(Color.blue);//设置字体颜色  
            if (this.font != null)
                g.setFont(this.font);
            //g.drawString("www.hi.baidu.com?xia_mingjian", w - 85, h - 5);
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        return img;
    }

    public BufferedImage modifyImagetogeter(BufferedImage b, BufferedImage d, int width, int height) {
        try {
            int w = b.getWidth();
            int h = b.getHeight();
            g = d.createGraphics();
            g.drawImage(b, width, height, w, h, null);
            g.dispose();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return d;
    }

    /**
     * BufferedImage拷贝
     * @param source
     * @return
     */
    public BufferedImage copyImage(BufferedImage source) {
        BufferedImage copyBufferedImage = new BufferedImage(source.getWidth(), source.getHeight(), source.getType());
        Graphics g = copyBufferedImage.getGraphics();
        g.drawImage(source, 0, 0, null);
        g.dispose();
        return copyBufferedImage;
    }

    /**
     * 批量生成照片时,如果背景图片是一个时,对其进行拷贝在修改。
     * @param pic
     * @param unitName
     * @param qRCode
     * @param backgroundImage
     * @param fontMetrics
     * @return
     */
    public BufferedImage qRCodeGeneration(ImageMerging pic, String unitName, BufferedImage qRCode, BufferedImage backgroundImage, FontMetrics fontMetrics) {
        int strWidth = fontMetrics.stringWidth(unitName);

        BufferedImage copyBufferedImage = copyImage(backgroundImage);

        BufferedImage backgroundAndName = pic.modifyImage(copyBufferedImage, unitName, (1400 - strWidth) / 2, 1050);


        BufferedImage bufferedImage = pic.modifyImagetogeter(qRCode, backgroundAndName, 342, 218);

        return bufferedImage;
    }


    public static void main(String[] args) {
        ImageMerging tt = new ImageMerging();
        BufferedImage b = tt.loadImageLocal("E:\\image\\33.png");
        BufferedImage d = tt.loadImageLocal("E:\\image\\44.png");
        //往图片上写文件
        BufferedImage aaaaaaaa = tt.modifyImage(b, "勇衣小吃店", 578, 999);
        tt.writeImageLocal("E:\\image\\cc.jpg", tt.modifyImagetogeter(d, aaaaaaaa, 342, 218));

        //将多张图片合在一起  
        System.out.println("success");
    }

}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值