39

我有一个透明的 PNG 文件,它被加载并存储在BufferedImage. 我需要BufferedImage这个TYPE_INT_ARGB。但是,当我使用getType()返回值是 0 ( TYPE_CUSTOM) 而不是 2 ( TYPE_INT_ARGB) 时。

这就是我加载的方式.png

public File img = new File("imagen.png");

public BufferedImage buffImg = 
    new BufferedImage(240, 240, BufferedImage.TYPE_INT_ARGB);

try { 
    buffImg = ImageIO.read(img ); 
} 
catch (IOException e) { }

System.out.Println(buffImg.getType()); //Prints 0 instead of 2

如何加载.png,保存BufferedImage并制作它TYPE_INT_ARGB

4

3 回答 3

83
BufferedImage in = ImageIO.read(img);

BufferedImage newImage = new BufferedImage(
    in.getWidth(), in.getHeight(), BufferedImage.TYPE_INT_ARGB);

Graphics2D g = newImage.createGraphics();
g.drawImage(in, 0, 0, null);
g.dispose();
于 2012-05-01T00:03:48.093 回答
10
try {
    File img = new File("somefile.png");
    BufferedImage image = ImageIO.read(img ); 
    System.out.println(image);
} catch (IOException e) { 
    e.printStackTrace(); 
}

我的图像文件的示例输出:

BufferedImage@5d391d: type = 5 ColorModel: #pixelBits = 24 
numComponents = 3 color 
space = java.awt.color.ICC_ColorSpace@50a649 
transparency = 1 
has alpha = false 
isAlphaPre = false 
ByteInterleavedRaster: 
width = 800 
height = 600 
#numDataElements 3 
dataOff[0] = 2

您可以运行 System.out.println(object); 在几乎任何对象上并获取有关它的一些信息。

于 2012-11-10T23:42:41.297 回答
2

从文件创建一个 BufferedImage 并将其设为 TYPE_INT_RGB

import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
    public static void main(String args[]){
        try{
            BufferedImage img = new BufferedImage( 
                500, 500, BufferedImage.TYPE_INT_RGB );
            File f = new File("MyFile.png");
            int r = 5;
            int g = 25; 
            int b = 255;
            int col = (r << 16) | (g << 8) | b;
            for(int x = 0; x < 500; x++){
                for(int y = 20; y < 300; y++){
                    img.setRGB(x, y, col);
                }
            }
            ImageIO.write(img, "PNG", f); 
        }
        catch(Exception e){ 
            e.printStackTrace();
        }
    }
}

这会在顶部画出一条大的蓝色条纹。

如果你想要它 ARGB,请这样做:

    try{
        BufferedImage img = new BufferedImage( 
            500, 500, BufferedImage.TYPE_INT_ARGB );
        File f = new File("MyFile.png");
        int r = 255;
        int g = 10;
        int b = 57;
        int alpha = 255;
        int col = (alpha << 24) | (r << 16) | (g << 8) | b;
        for(int x = 0; x < 500; x++){
            for(int y = 20; y < 30; y++){
                img.setRGB(x, y, col);
            }
        }
        ImageIO.write(img, "PNG", f);
    }
    catch(Exception e){
        e.printStackTrace();
    }

打开 MyFile.png,它的顶部有一条红色条纹。

于 2015-04-12T22:24:42.247 回答