简体   繁体   English

ImageIO.read()是否总是返回具有透明性的BufferedImage?

[英]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? 图像的类型将始终是BufferedImage.TYPE_INT_ARGB还是具有alpha通道的其他类型? (I am using Java 8 btw) (我正在使用Java 8 btw)

From my testing, it appears that the BufferedImage adapts to what image you have. 根据我的测试,看来BufferedImage可以适应您所拥有的图像。

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 6 = BufferedImage.TYPE_4BYTE_ABGR

5 = BufferedImage.TYPE_3BYTE_BGR 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. 更长的答案:如果读取的图像具有alpha通道,则ImageIO.read(...)仅应返回带有alpha的图像类型,但是正如@MadProgrammer在其评论中所说,这实际上是特定于插件的。 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. 据我所知,大多数ImageReader插件将为输入返回最“自然”的类型,即与输入文件的本机格式最接近的类型。

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 . 要做到这一点,你需要获得ImageReader你想要阅读的格式实例,并传递给类型或图像setDestination(...)setDestinationType(...)的方法ImageReadParam

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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