2013-06-19 34 views
7

我的Java代碼中有一個格式爲byte[]數組的圖像。我想從該數組中提取以下信息。我如何儘可能快地做到這一點。從字節數組中提取圖像的寬度,高度,顏色和類型

  • 寬度
  • 身高
  • 顏色(黑白色&,顏色或透明的嗎?如果顏色,什麼是主色調?)
  • 類型(是圖像PNG,GIF,JPEG等。 )
+1

在字節數組上使用按位操作來提取這種信息是一項艱鉅的任務。我會爲此使用一些庫。 – Simon

+0

創建某種圖像(可能使用'ImageIO')並提取圖像屬性 – MadProgrammer

+0

@Simon我沒有使用庫的問題。 –

回答

9

使用ImageIO讀取緩存的圖像,然後獲取您想要的相關內容。請參閱java doc http://docs.oracle.com/javase/6/docs/api/javax/imageio/ImageIO.html

import java.awt.image.BufferedImage; 
import java.io.ByteArrayInputStream; 
import java.io.IOException; 
import java.io.InputStream; 

import javax.imageio.ImageIO; 


public class Test { 

    /** 
    * @param args 
    * @throws IOException 
    */ 
    public static void main(String[] args) throws IOException { 
     // assuming that picture is your byte array 
     byte[] picture = new byte[30]; 

     InputStream in = new ByteArrayInputStream(picture); 

     BufferedImage buf = ImageIO.read(in); 
     ColorModel model = buf.getColorModel(); 
     int height = buf.getHeight(); 

    } 

} 
+0

你能給我一個代碼片段嗎?我真的很感激它。 –

+0

特別針對顏色部分。 –

+0

感謝您的編輯。顏色信息如何? 「BufferedImage」可能嗎?謝謝。 –

5

要獲得從字節數組的圖像類型,你可以這樣做:

byte[] picture = new byte[30]; 
ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(picture)); 

Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); 
while (readers.hasNext()) { 
    ImageReader read = readers.next(); 
    System.out.println("format name = " + read.getFormatName()); 
} 

這裏是輸出我有不同的文件:

format name = png 
format name = JPEG 
format name = gif 

它靈感來源於:

Convert Byte Array to image in Java - without knowing the type

+0

工作fr我... thnks :) –

+0

很酷。 ..謝謝 !! –

相關問題