图片拼接:横向、纵向、多张等

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.*;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MergeImageUtil {
    public static void main(String[] args) throws IOException {
        // 两张图拼接:既可以横向拼接也可以纵相拼接
        String filePath = "D:\\download\\";
//        String path1 = filePath + "DJI_20220826142048_0021_W.JPG";
//        String path2 = filePath + "DJI_20220826142051_0022_W.JPG";
//        mergeImage(path1, path2,  1, filePath+"c_2.jpg");


//        // 多张图片拼接
//        List<String> filePaths=new ArrayList<>();
//        filePaths.add(filePath + "DJI_20220826142048_0021_W.JPG");
//        filePaths.add(filePath + "DJI_20220826142051_0022_W.JPG");
//        filePaths.add(filePath + "DJI_20220826142221_0061_W.JPG");
//        filePaths.add(filePath + "DJI_20220826142228_0064_W.JPG");
//        for (int i = 0; i < filePaths.size(); i++) {
//            System.out.println("i*******"+i);
//            if(i==0){
//                // 0,1->c0 横
//                mergeImage(filePaths.get(i), filePaths.get(i+1),  1, filePath+"c_"+i+".jpg");
//                i=i+1;
//            }
//
//            // 2,c_0.jpg->c_2.jpg 纵
//            if(i==2){
//                mergeImage(filePath+"c_"+(i-2)+".jpg", filePaths.get(i),  2, filePath+"c_"+i+".jpg");
//            }
//            // 3,c_2.jpg->c_3 横
//            // 4,c_3.jpg->c_4 纵
//            if(i>2 && i%2==0){
//                mergeImage(filePath+"c_"+(i-1)+".jpg", filePaths.get(i),  2, filePath+"c_"+i+".jpg");
//            }else{
//                mergeImage(filePath+"c_"+(i-1)+".jpg", filePaths.get(i),  1, filePath+"c_"+i+".jpg");
//            }
//
//
//            System.out.println("i====="+i);
//        }


        // 原图按照固定的宽、高缩放
        // 图片裁剪按照固定尺寸裁剪 宽640*高512
        // 原图: 宽5184*高3888
        String filePath2 = "D:\\download\\suofang\\";
        File srcImg=new File(filePath2.concat("DJI_20220826142003_0001_Z.JPG"));
        File destImg=new File(filePath2.concat("DJI_20220826142003_0001_destImg.JPG"));
        imgThumbnail(srcImg, destImg, 640, 512, false);

    }

    /**
     * 图片拼接
     * @param path1     图片1路径
     * @param path2     图片2路径
     * @param type      1 横向拼接, 2 纵向拼接
     * (注意:必须两张图片长宽一致)
     */
    public static void mergeImage( String path1, String path2, int type, String targetFile) throws IOException {
        File file1 = new File(path1);
        File file2 = new File(path2);
        //两张图片的拼接
        int len = 2;
        BufferedImage[] images = new BufferedImage[len];
        images[0] = ImageIO.read(file1);
        images[1] = ImageIO.read(file2);
        int[][] ImageArrays = new int[len][];

        for (int i = 0; i < len; i++) {
            int width = images[i].getWidth();
            int height = images[i].getHeight();
            ImageArrays[i] = new int[width * height];
            ImageArrays[i] = images[i].getRGB(0, 0, width, height, ImageArrays[i], 0, width);
        }
        int newHeight = 0;
        int newWidth = 0;
        for (int i = 0; i < images.length; i++) {
            // 横向
            if (type == 1) {
                newHeight = newHeight > images[i].getHeight() ? newHeight : images[i].getHeight();
                newWidth += images[i].getWidth();
            } else if (type == 2) {// 纵向
                newWidth = newWidth > images[i].getWidth() ? newWidth : images[i].getWidth();
                newHeight += images[i].getHeight();
            }
        }
        if (type == 1 && newWidth < 1) {
            return;
        }
        if (type == 2 && newHeight < 1) {
            return;
        }
        // 生成新图片
        try {
            BufferedImage ImageNew = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            int height_i = 0;
            int width_i = 0;
            for (int i = 0; i < images.length; i++) {
                if (type == 1) {
                    ImageNew.setRGB(width_i, 0, images[i].getWidth(), newHeight, ImageArrays[i], 0,
                            images[i].getWidth());
                    width_i += images[i].getWidth();
                } else if (type == 2) {
                    ImageNew.setRGB(0, height_i, newWidth, images[i].getHeight(), ImageArrays[i], 0, newWidth);
                    height_i += images[i].getHeight();
                }
            }
            //输出想要的图片
            ImageIO.write(ImageNew, targetFile.split("\\.")[1], new File(targetFile));
            System.out.println("拼接图片成功!");

        } catch (Exception e) {
            System.err.println("拼接图片失败:{}"+ e);
        }
    }

    /**
     * 原图等比例缩略图
     *
     * @param srcImg     原图片
     * @param destImg    目标位置
     * @param width      期望宽
     * @param height     期望高
     * @param equalScale 是否等比例缩放
     */
    public static void imgThumbnail(File srcImg, File destImg, int width, int height, boolean equalScale) {
        String type = getImageType(srcImg);
        if (type == null) {
            return;
        }
        if (width < 0 || height < 0) {
            return;
        }

        BufferedImage srcImage = null;
        try {
            srcImage = ImageIO.read(srcImg);
            System.out.println("srcImg size=" + srcImage.getWidth() + "X" + srcImage.getHeight());
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        if (srcImage != null) {
            // targetW,targetH分别表示目标长和宽
            BufferedImage target = null;
            double sx = (double) width / srcImage.getWidth();
            double sy = (double) height / srcImage.getHeight();
            // 等比缩放
            if (equalScale) {
                if (sx > sy) {
                    sx = sy;
                    width = (int) (sx * srcImage.getWidth());
                } else {
                    sy = sx;
                    height = (int) (sy * srcImage.getHeight());
                }
            }
            System.out.println("destImg size=" + width + "X" + height);
            ColorModel cm = srcImage.getColorModel();
            WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
            boolean alphaPremultiplied = cm.isAlphaPremultiplied();

            target = new BufferedImage(cm, raster, alphaPremultiplied, null);
            Graphics2D g = target.createGraphics();
            // smoother than exlax:
            g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g.drawRenderedImage(srcImage, AffineTransform.getScaleInstance(sx, sy));
            g.dispose();
            // 将转换后的图片保存
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(target, type, baos);
                FileOutputStream fos = new FileOutputStream(destImg);
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取文件后缀不带.
     *
     * @param file 文件后缀名
     * @return 图片类型
     */
    private static String getImageType(File file) {
        if (file != null && file.exists() && file.isFile()) {
            String fileName = file.getName();
            int index = fileName.lastIndexOf(".");
            if (index != -1 && index < fileName.length() - 1) {
                return fileName.substring(index + 1);
            }
        }
        return null;
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值