Jerfov2
Jerfov2

Reputation: 5504

Does ImageIO.read() always return BufferedImage with transparency?

The title explains it all. Lets say i have the following code:

BufferedImage image;
try {
    image = ImageIO.read(new File(path));
}
catch (Exception e) {
    e.printStackTrace();
}

Would image's type always be BufferedImage.TYPE_INT_ARGB or other type with an alpha channel? (I am using Java 8 btw)

Upvotes: 1

Views: 3885

Answers (2)

Harald K
Harald K

Reputation: 27084

Short answer: No. Not always. It can be any type.

Longer answer: ImageIO.read(...) should only return an image type with alpha, if the image read has an alpha channel, but as @MadProgrammer says in his comment, this is really plugin-specific. Most ImageReader plugins that I know of, will return the most "natural" type for the input, that is the one that is closest to the native format of the input file.

It is however possible to specify the type of image you want, or even specify the target image to load into. To do this, you need to obtain an ImageReader instance for the format you want to read, and pass the type or image to the setDestination(...) or setDestinationType(...) methods on the ImageReadParam.

Upvotes: 0

Constant
Constant

Reputation: 830

From my testing, it appears that the BufferedImage adapts to what image you have.

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.net.URL;

public class BufferedImageTest {

    public static void main(String[] args) {
        try {
            BufferedImage transparent = ImageIO.read(new URL("http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png"));
            System.out.println(transparent.getType());
            BufferedImage solid = ImageIO.read(new URL("http://blacklabelsociety.com/home/wp-content/uploads/2014/01/spacer.jpg"));
            System.out.println(solid.getType());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Output

6
5

6 = BufferedImage.TYPE_4BYTE_ABGR

5 = BufferedImage.TYPE_3BYTE_BGR

The first image had transparency, whereas the second one did not.

Upvotes: 3

Related Questions