How to decide which BufferedImage image type to use?

user3437460 picture user3437460 · Sep 5, 2015 · Viewed 17.1k times · Source

Java BufferedImage class has a long list of class variables known as the image type which can be used as an argument for the BufferedImage constructor.

However, Java docs did a minimal explanation what these image types are used for and how would it affect the BufferedImage to be created.

My question is:

  1. How would an image type affect the BufferedImage to be created? Does it control the number of bits used to store various colors (Red,Green,Blue) and its transparency?

  2. Which image type should we use if we just want to create

    • an opaque image
    • a transparent image
    • a translucent image

I read the description in the Java Doc many times, but just couldn't figure out how should we use it. For example, this one:

TYPE_INT_BGR

Represents an image with 8-bit RGB color components, corresponding to a Windows- or Solaris- style BGR color model, with the colors Blue, Green, and Red packed into integer pixels. There is no alpha. The image has a DirectColorModel. When data with non-opaque alpha is stored in an image of this type, the color data must be adjusted to a non-premultiplied form and the alpha discarded, as described in the AlphaComposite documentation.

Answer

Jack picture Jack · Sep 5, 2015

Unless you have specific requirements (for example saving memory or saving computations or a specific native pixel format) just go with the default TYPE_INT_ARGB which has 8 bits per channel, 3 channels + alpha.

Skipping the alpha channel when working with 8 bits per channel won't affect the total memory occupied by the image since every pixel will be packed in an int in any case so 8 bits will be discarded.

Basically you have:

  • TYPE_INT_ARGB, 4 bytes per pixel with alpha channel
  • TYPE_INT_ARGB_PRE, 4 bytes per pixel, same as before but colors are already multiplied by the alpha of the pixel to save computations
  • TYPE_INT_RGB, 4 bytes per pixel without alpha channel
  • TYPE_USHORT_555_RGB and TYPE_USHORT_565_RGB, 2 bytes per pixel, much less colors, don't need to use it unless you have memory constraints

Then there are all the same kind of formats with swapped channels (eg. BGR instead that RGB). You should choose the one native of your platform so that less conversion should be done.