gpt4 book ai didi

java - 将两个 BufferedImage 并排复制到一张图像中

转载 作者:行者123 更新时间:2023-12-01 19:07:26 24 4
gpt4 key购买 nike

我有两个图像,我想将这两个图像复制到一个新图像,其中第二个图像位于第一个图像的旁边,而不是在它的上面。

BufferedImage imgb1 = img1;
BufferedImage imgb2 = img2;
BufferedImage imgResult = new BufferedImage(...);

其中 imgResult 包含彼此相邻的第一张图像和第二张图像。

最佳答案

我为您创建了一个演示以及一个单元测试,希望它有效!

代码:

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* This code try to join two BufferedImage
* @author wangdq
* 2013-12-29
*/
public class JoinImage {
public static void main(String args[])
{
String filename = System.getProperty("user.home")+File.separator;
try {
BufferedImage img1 = ImageIO.read(new File(filename+"1.png"));
BufferedImage img2=ImageIO.read(new File(filename+"2.png"));
BufferedImage joinedImg = joinBufferedImage(img1,img2);
boolean success = ImageIO.write(joinedImg, "png", new File(filename+"joined.png"));
System.out.println("saved success? "+success);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* join two BufferedImage
* you can add a orientation parameter to control direction
* you can use a array to join more BufferedImage
*/

public static BufferedImage joinBufferedImage(BufferedImage img1,BufferedImage img2) {

//do some calculate first
int offset = 5;
int wid = img1.getWidth()+img2.getWidth()+offset;
int height = Math.max(img1.getHeight(),img2.getHeight())+offset;
//create a new buffer and draw two image into the new image
BufferedImage newImage = new BufferedImage(wid,height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = newImage.createGraphics();
Color oldColor = g2.getColor();
//fill background
g2.setPaint(Color.WHITE);
g2.fillRect(0, 0, wid, height);
//draw image
g2.setColor(oldColor);
g2.drawImage(img1, null, 0, 0);
g2.drawImage(img2, null, img1.getWidth()+offset, 0);
g2.dispose();
return newImage;
}
}

关于java - 将两个 BufferedImage 并排复制到一张图像中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59524492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com