2012-04-30 99 views
27

我有一個PNG文件的透明度,加載並存儲在BufferedImage。我需要這個BufferedImageTYPE_INT_ARGB。但是,當我使用getType()時,返回值爲0(TYPE_CUSTOM)而不是2(TYPE_INT_ARGB)。從文件創建一個BufferedImage,並使其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 

我怎樣才能加載巴紐,保存在BufferedImage並使其TYPE_INT_ARGB

+3

更改'public BufferedImage buffImg = new BufferedImage(240,240,BufferedImage.TYPE_INT_ARGB);'將'public BufferedImage buffImg;'catch(IOException e){}'catch(IOException e){e.printStackTrace (); }'。報告新的輸出。 –

+5

'System.Out.Println' ***不能編譯。***爲了更好地提供幫助,請發佈[SSCCE](http://sscce.org/)。 –

回答

62
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(); 
+0

嘿,工作。謝謝! – user1319734

+15

@ user1319734,或許您想將此標記爲接受的答案? – iX3

+1

這是非常低效的,隨着圖像尺寸的增加,它變得越來越不可行。 – alexantd

6
try { 
    File img = new File("somefile.png"); 
    BufferedImage image = ImageIO.read(img); 
    System.out.println(image); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

實施例輸出爲我的圖像文件:

[email protected]: type = 5 ColorModel: #pixelBits = 24 
numComponents = 3 color 
space = [email protected] 
transparency = 1 
has alpha = false 
isAlphaPre = false 
ByteInterleavedRaster: 
width = 800 
height = 600 
#numDataElements 3 
dataOff[0] = 2 

可以運行的System.out.println(對象);關於任何對象並獲取關於它的一些信息。

0

由文件創建一個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,它在頂部紅色的條紋。

相關問題