Java使用BufferedImage修改图片内容

Posted shijl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java使用BufferedImage修改图片内容相关的知识,希望对你有一定的参考价值。

1.修改图片的架包

  

      <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
      </dependency>

1.1   修i该图片工具类

package com.mz.usps.common.util;

import com.mz.usps.common.domain.LableMessage;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author sjl
 * @date 2019-04-23 17:58
 */
public class PngAlterUtil {
    /**
     * 添加字体的属性设置
     */
    private Font font = new Font("微软雅黑", Font.BOLD, 18);
    private Graphics2D g = null;
    private int fontsize = 0;
    private int x = 0;
    private int y = 0;
    private static int z = 0;

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

    /**
     * 生成图片到本地
     */
    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) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
        }
    }

    /**
     * 修改图片,返回修改后的图片缓冲区
     */
    public BufferedImage modifyImage(BufferedImage img, BufferedImage imgs1, BufferedImage imgs2, BufferedImage imgs3, Object content, int x, int y, int j) {
        try {

            if (j >= z) {
                font = new Font("微软雅黑", Font.BOLD, 22);
            }


            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();

            //遮盖原本模板
            if (imgs1 != null) {
                ImageObserver observer = new Checkbox();
                g.drawImage(imgs1, 5, 270, observer);
            }
            if (imgs2 != null) {
                ImageObserver observer = new Checkbox();
                g.drawImage(imgs2, 5, 470, observer);
            }
            if (imgs3 != null) {
                ImageObserver observer = new Checkbox();
                g.drawImage(imgs3, 205, 1010, observer);
            }

            //设置背景颜色
            g.setBackground(Color.WHITE);
            //设置字体颜色
            g.setColor(Color.BLACK);
            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) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return img;
    }

    /**
     *
     * @param path 原图路径
     * @param message 封装了向原图中插入的信息
     */
    public static void panAlter(String path, LableMessage message) {
        //获取单号条形码
        BufferedImage barCodeImage = BarCodesUtil.generateFile(message.getLabelNo());

        //遮盖层存放路径
        String coverPath1 = "/usr/local/tomcatusps/apache-tomcat-8.5.15/Root/overspread/coverLayer1.png";
        String coverPath2 = "/usr/local/tomcatusps/apache-tomcat-8.5.15/Root/overspread/coverLayer2.png";
        PngAlterUtil pngAlterUtil = new PngAlterUtil();
        //导入本地图片到缓冲区
        BufferedImage img1 = pngAlterUtil.loadImageLocal(path);
        BufferedImage img2 = pngAlterUtil.loadImageLocal(coverPath1);
        BufferedImage img3 = pngAlterUtil.loadImageLocal(coverPath2);
        //修改图片,返回修改后的图片缓冲区
        BufferedImage image = pngAlterUtil.modifyImage(img1, img2, img3, barCodeImage, "", 0, 0, 0);


        ArrayList<String> list = new ArrayList();
        list.add("From:" + message.getSendName());
        //发件地址1判断
        if (message.getSendAddress1().length() > 30) {
            String sb1 = message.getSendAddress1().substring(0, 30);
            int i1 = sb1.lastIndexOf(" ");
            list.add(message.getSendAddress1().substring(0, i1));
            list.add(message.getSendAddress1().substring(i1 + 1));
        } else {
            list.add(message.getReceiveAddress1());
        }
        //发件地址2判断
        if (message.getSendAddress2() != null) {
            if (message.getSendAddress2().length() > 30) {
                String sb2 = message.getSendAddress2().substring(0, 30);
                int i2 = sb2.lastIndexOf(" ");
                list.add(message.getSendAddress2().substring(0, i2));
                list.add(message.getSendAddress2().substring(i2 + 1));
            } else {
                list.add(message.getSendAddress2());
            }
        }
        list.add(message.getSendCity() + "  " + message.getSendProvCode() + "  " + message.getSendPostcode());
        list.add(message.getSendMobile());

        //添加收货人信息
        list.add("Ship To:" + message.getReceiveName());
        //判断收货人地址1
        if (message.getReceiveAddress1().length() > 30) {
            String sb3 = message.getReceiveAddress1().substring(0, 30);
            int i3 = sb3.lastIndexOf(" ");
            list.add(message.getReceiveAddress1().substring(0, i3));
            list.add(message.getReceiveAddress1().substring(i3 + 1));
        } else {
            list.add(message.getReceiveAddress1());
        }
        //判断收获人地址2
        if (message.getReceiveAddress2() != null) {
            if (message.getReceiveAddress2().length() > 30) {
                String sb4 = message.getReceiveAddress2().substring(0, 30);
                int i4 = sb4.lastIndexOf(" ");
                list.add(message.getReceiveAddress2().substring(0, i4));
                list.add(message.getReceiveAddress2().substring(i4 + 1));
            } else {
                list.add(message.getReceiveAddress2());
            }
        }
        list.add(message.getReceiveCity() + "  " + message.getReceivePrvoCode() + "  " + message.getSendPostcode());
        list.add(message.getReceiveMobile());

        int y = 340;

        for (int j = 0; j < list.size(); j++) {
            if (j == 0) {
                image = pngAlterUtil.modifyImage(image, null, null, null, list.get(j), 45, y, j);
            } else if (list.get(j).contains("Ship To:")) {
                z = j;
                y = y + 40;
                image = pngAlterUtil.modifyImage(image, null, null, null, list.get(j), 5, y, j);
            } else {
                image = pngAlterUtil.modifyImage(image, null, null, null, list.get(j), 96, y, j);
            }
            y = y + 20;
        }
        //将生成的新lable保存到本地
        pngAlterUtil.writeImageLocal(path, image);
    }
}

2.根据单号生成条形码工具类架包

    <!--条形码工具-->
        <dependency>
            <groupId>net.sf.barcode4j</groupId>
            <artifactId>barcode4j-light</artifactId>
            <version>2.0</version>
    </dependency>

2.1   根据单号生成条形码工具类

package com.mz.usps.common.util;

import org.apache.commons.lang3.StringUtils;
import org.krysalis.barcode4j.BarcodeDimension;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * 生成条形码工具
 *
 * @author sjl
 * @date 2019-04-25 10:44
 */
public class BarCodesUtil {

    /**
     * 生成文件
     *
     * @param msg
     * @param
     * @return
     */
    public static BufferedImage generateFile(String msg) {
//        String path = "C:\\usr\\local\\tomcatusps\\apache-tomcat-8.5.15\\Root\\label\\barCode.png";
        String path = "/usr/local/tomcatusps/apache-tomcat-8.5.15/Root/overspread/barCode.png";

        BufferedImage read = null;
        File file = new File(path);
        try {
            //将条形码存入本地
            generate(msg, new FileOutputStream(file));
            read = ImageIO.read(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return read;
    }

    /**
     * 生成字节
     *
     * @param msg
     * @return
     */
    public static byte[] generate(String msg) {
        ByteArrayOutputStream ous = new ByteArrayOutputStream();
        generate(msg, ous);
        return ous.toByteArray();
    }

    /**
     * 生成到流
     *
     * @param msg
     * @param ous
     */
    public static void generate(String msg, OutputStream ous) {
        if (StringUtils.isEmpty(msg) || ous == null) {
            return;
        }

//        Code39Bean bean = new Code39Bean();
        Code128Bean bean = new Code128Bean();

        // 精细度
        final int dpi = 30;
        // module宽度
        final double moduleWidth = UnitConv.in2mm(0.5f / dpi);

        // 配置对象
        bean.setModuleWidth(3);
//        bean.setWideFactor(5);
        bean.setBarHeight(20);
        bean.setFontSize(20);
        bean.doQuietZone(false);


        String format = "image/png";


        BarcodeDimension barcodeDimension = bean.calcDimensions(msg);

        try {

            // 输出到流
            BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format, dpi,
                    BufferedImage.TYPE_BYTE_BINARY, false, 0);

            // 生成条形码
            bean.generateBarcode(canvas, msg);

            // 结束绘制
            canvas.finish();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

  

以上是关于Java使用BufferedImage修改图片内容的主要内容,如果未能解决你的问题,请参考以下文章

java修改图片大小

Java小游戏DanceWithStars:修改本地文档中的图片(图片宽高和图片类型)以及将图片设置为JButton的图像

BufferedImage操作图片笔记(转)

BufferedImage类实现图片的切分

Java中BufferedImage的用法,如何读取保存一个图片

Java读取并修改图片的像素值