2

I am trying to create a 1920x1080 colored image with Java, but for some reason I can't change the color. All I get is black, whatever values I place in color RGB. Here is the code:

BufferedImage background = new BufferedImage(1920,1080,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = background.createGraphics();
g.setPaint ( new Color ( 100, 100, 250 ) );
g.fillRect ( 0, 0, background.getWidth(), background.getHeight() );
g.dispose();

try {
    ImageIO.write(background, "jpg", new File("output.jpg"));
} catch (IOException ex) {
    ex.printStackTrace();
}

What am I doing wrong?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
dirac
  • 309
  • 1
  • 9
  • 2
    Your code works fine for me and prints out a nice gray-green filled image. – Hovercraft Full Of Eels Jan 24 '16 at 03:41
  • Not to me as your code looks fine to me. Are you sure that you're looking at the right `output.jpg` file? – Hovercraft Full Of Eels Jan 24 '16 at 03:43
  • Yes, I check the right one – dirac Jan 24 '16 at 03:44
  • 1
    When I run this code on my MacBook, and I open with Preview, I see a black rectangle. When I open it with Chrome, it's green. – Erwin Bolwidt Jan 24 '16 at 04:01
  • 1
    And.. when I change the image type to TYPE_INT_RGB, the image is blue in both Preview and Chrome. Which makes sense because the color is `100,100,250` which is blue. A clear hint is the color space: when using type TYPE_INT_ARGB, the colorspace is in CMYK. When using TYPE_INT_RGB, the colorspace is RGB. CMYK color space is probably handled incorrectly by viewers. – Erwin Bolwidt Jan 24 '16 at 04:05
  • (The colorspace is the one I see in the MacOS finder - it shouldn't be CMYK but it is. Strange. Could be a bug in the Java 8 ImageIO class, or in the MacOS finder) – Erwin Bolwidt Jan 24 '16 at 04:14
  • @ErwinBolwidt Unfortunately, JPEG doesn't have a way of defining color space. Instead it's interpreted from multiple fields (typically JFIF, Exif and Adobe app markers + inspecting the component ids), by [convention](https://docs.oracle.com/javase/8/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html#color) (oh, and the algorithm described in that document is wrong... ;-) ). – Harald K Jan 27 '16 at 10:18

1 Answers1

2

I found the answer. I changed the:

BufferedImage.TYPE_INT_ARGB

to:

BufferedImage.TYPE_INT_RGB

and it worked. Weird though.

dirac
  • 309
  • 1
  • 9