java合并两张图片

2024-01-08 22:01:28

?测试照片: 一个场景拍两张视角轻微偏移的照片, 比如书上的文字

用途: 判断摄像机是否偏移视角等等


import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

public class MergeTwoImgUtil {

    public static void main(String[] args) throws Exception {
        BufferedImage img1 = getImageByPath("E:\\t1.jpg");
        BufferedImage img2 = getImageByPath("E:\\t2.jpg");
        merge2File(img1, img2, "E:\\t1_t2.png");
    }


    public static ByteArrayOutputStream merge2Stream(BufferedImage image1, BufferedImage image2) {
        return merge(image1, image2);
    }

    public static void merge2File(BufferedImage image1, BufferedImage image2, String savePath) {
        try (FileOutputStream fileOutputStream = new FileOutputStream(savePath);) {
            ByteArrayOutputStream merge = merge(image1, image2);
            merge.writeTo(fileOutputStream);
            fileOutputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static ByteArrayOutputStream merge(BufferedImage image1, BufferedImage image2) {
        try {
            // 加载第二个图片
            // 替换为第二个图片的路径
            // 创建一个与图片大小相同的透明图片
            BufferedImage blendedImage = new BufferedImage(896, 476, BufferedImage.TYPE_INT_ARGB);
            // 创建Graphics2D对象并绘制第一个图片
            Graphics2D g2d = blendedImage.createGraphics();
            g2d.drawImage(image1, 0, 0, null);
            // 设置透明度为50%
            AlphaComposite transparency = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
            g2d.setComposite(transparency);
            // 绘制第二个图片
            g2d.drawImage(image2, 0, 0, null);
            // 保存合并后的图片
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageIO.write(blendedImage, "png", byteArrayOutputStream);  // 保存路径和文件名
            // 清除Graphics2D对象
            g2d.dispose();
            return byteArrayOutputStream;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static BufferedImage getImageByPath(String filePath) throws Exception {
        InputStream imageStream = new FileInputStream(filePath);
        return ImageIO.read(imageStream);
    }

    public static BufferedImage getImageByUrl(String imgUrl) throws Exception {
        InputStream imageStream = null;
        URL url = new URL(imgUrl);
        imageStream = url.openStream();
        return ImageIO.read(imageStream);
    }
}

文章来源:https://blog.csdn.net/Lxinccode/article/details/135412634
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。