I am trying to merge two images in Java. The two photos must be positioned horizontally (the first to the left of the second). I think I have problems in the write method of the ImageIO class.
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.*;
public class Merge {
public static void main(String[] args) throws IOException {
String p = "../../Desktop/temp/";
BufferedImage left = ImageIO.read(new File(p+"006.jpg"));
BufferedImage right = ImageIO.read(new File(p+"007.jpg"));
BufferedImage imgClone = new BufferedImage(left.getWidth()+right.getWidth(), left.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D cloneG = imgClone.createGraphics();
cloneG.drawImage(right, 0, 0, null);
cloneG.drawImage(left, left.getWidth(), 0, null);
System.out.println(ImageIO.write(imgClone, "jpg", new File(p+"001.jpg"))); //always false
cloneG.dispose();
}
}
ImageIO.write(imgClone, "jpg", new File(p+"001.jpg"))
always returns false, I think there is something wrong here but I can't figure out what.
If I go into debugging I can see the merged photo, but then it won't be saved in the folder.
I think it's because JPEG doesn't support transparency, and you used ARGB as the image buffer type. Removing the "A" worked for me.
class Merge {
public static void main(String[] args) throws IOException {
BufferedImage imgClone = new BufferedImage( 50, 50, BufferedImage.TYPE_INT_RGB);
// returns "true"
System.out.println(ImageIO.write(imgClone, "jpg", File.createTempFile( "Test-", "jpg")));
}
}