简体   繁体   中英

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)

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM