Java Image合并

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.junit.Test;

public class MergeImageUtils {
	
	/**
	 * 将两张图片合并为一张图片
	 * @param oneSrc
	 * @param twoSrc
	 * @param mergeSrc 合并后的图片路径
	 */
	public void mergeImage(String oneSrc, String twoSrc, String mergeSrc) {
		String postFix = mergeSrc.substring(mergeSrc.lastIndexOf(".") + 1, mergeSrc.length());
		try {
			File fileOne = new File(oneSrc);//读取第一张图片
			Image src = ImageIO.read(fileOne);  
			int width = src.getWidth(null);
			int height = src.getHeight(null);
			if(width > 900 || height > 900) {
				int num = (int) Math.ceil((double)width/900);
				int num2 = (int) Math.ceil((double)height/900);
				num = num > num2 ? num : num2;
				width = width/num;
				height = height/num;
			}
	        BufferedImage bufferedImageOne = null;
			if ("png".equalsIgnoreCase(postFix.toLowerCase())) {
				bufferedImageOne = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
			} else {
				bufferedImageOne = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			}
			bufferedImageOne.getGraphics().drawImage(src.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0,  null);
			int[] imageArrayOne = new int[width * height];// 从图片中读取RGB
			imageArrayOne = bufferedImageOne.getRGB(0, 0, width, height, imageArrayOne, 0, width);
			
			File fileTwo = new File(twoSrc);//读取第二张图片
			src = ImageIO.read(fileTwo);  
			BufferedImage bufferedImageTwo = null;
			if ("png".equalsIgnoreCase(postFix.toLowerCase())) {
				bufferedImageTwo = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
			} else {
				bufferedImageTwo = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			}
			bufferedImageTwo.getGraphics().drawImage(src.getScaledInstance(width, height,  Image.SCALE_SMOOTH), 0, 0,  null);
			int[] imageArrayTwo = new int[width * height];// 从图片中读取RGB
			imageArrayTwo = bufferedImageTwo.getRGB(0, 0, width, height, imageArrayTwo, 0, width);
			
			//生成新图片
			BufferedImage imageNew = new BufferedImage(width*2, height, BufferedImage.TYPE_INT_RGB);
			imageNew.setRGB(0 , 0, width, height, imageArrayOne, 0, width);		//设置左半部分的RGB
			imageNew.setRGB(width, 0, width, height, imageArrayTwo, 0, width);	//设置右半部分的RGB
			File outFile = new File(mergeSrc);
			//写图片
			ImageIO.write(imageNew, postFix, outFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
    
	@Test
    public void testMergeImage(){
    	mergeImage("D:/source/image/1.jpg", "D:/source/image/2.png", "D:/source/image/3.png");
	}
}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tanksyg/article/details/49928095
文章标签: image 合并
上一篇通过System.getProperties()获取系统参数
下一篇Java中的getGenericSuperclass方法的基本用法
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭