关闭

Java Image合并

标签: image合并
299人阅读 评论(0) 收藏 举报
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");
	}
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:149665次
    • 积分:1362
    • 等级:
    • 排名:千里之外
    • 原创:35篇
    • 转载:2篇
    • 译文:0篇
    • 评论:12条
    文章分类
    最新评论