0

This question is similar to…

Java BufferedImage saves with unwanted background color

…but regards .jpg and not .png.

I join two images together using the following Java code, and an orange background is mysteriously added. How can I get rid of it?

Note that I am trying to cover my bases using both setColor and setBackground, and both clearRect and fillRect.

Note that the source of the two images is a PDF, extracted using PDFBox

public static BufferedImage joinBufferedImage(BufferedImage img1, BufferedImage img2) {
    int offset = 0;
    int width = Math.max(img1.getWidth() , img2.getWidth()) + offset;
    int height = img1.getHeight() + img2.getHeight() + offset;

    BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = newImage.createGraphics();

    g2.setColor(Color.WHITE);
    g2.setBackground(Color.WHITE);
    g2.clearRect(0, 0, width, height);
    g2.fillRect(0, 0, width, height);

    g2.drawImage(img1, null, 0, 0);
    g2.drawImage(img2, null, 0, img1.getHeight() + offset);
    g2.dispose();

    return newImage;
}
BufferedImage joined = joinBufferedImage(bim, bim2);
ImageIO.write(joined, "jpg", imageFile);    
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
gordon613
  • 2,770
  • 12
  • 52
  • 81
  • 1
    Couldn't you use `BufferedImage.TYPE_INT_RGB` because the alpha transparency does not exist in JPEG images? – Mr. Polywhirl May 03 '18 at 16:08
  • That works! Please post as an answer and I will mark it correct! (And thanks for your editing...I will try and format better next time....) – gordon613 May 03 '18 at 16:12

0 Answers0