2014-12-02 83 views
0

我想將一個8位灰度圖像字節數組轉換爲java中的jpg圖像格式。8位灰度圖像字節數組到JPG格式

static byte[] bytes = new byte[]{126, 126, 127, -128}; 

public static void main(String[] args) throws IOException { 
    ByteArrayInputStream bis = new ByteArrayInputStream(bytes); 
    Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg"); 
    ImageReader reader = (ImageReader) readers.next(); 
    Object source = bis; 
    ImageInputStream iis = ImageIO.createImageInputStream(source); 
    reader.setInput(iis, true); 
    ImageReadParam param = reader.getDefaultReadParam(); 
    Image image = reader.read(0, param); 
    BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_BYTE_GRAY); 
    Graphics2D g2 = bufferedImage.createGraphics(); 
    g2.drawImage(image, null, null); 
    File imageFile = new File("C:\\newrose3.jpg"); 
    ImageIO.write(bufferedImage, "jpg", imageFile); 
    System.out.println(imageFile.getPath()); 
} 

我有字節有圖像數據,我想在java中將其轉換爲可讀的圖像格式。

+0

什麼是你的問題? – Holger 2014-12-02 12:24:56

+0

我的問題是如何將圖像字節數組{126,126,127,-128}轉換爲任何可讀的圖像格式? – Raman 2014-12-02 12:29:35

+0

'{126,126,127,-128}'應該是什麼格式?對於完整的JPEG數據流來說有點短。那是像素值嗎? – haraldK 2014-12-02 12:39:44

回答

2

假設bytes應該是像素數據,您應該從這些字節創建一個圖像,然後將其寫成JPEG格式。

喜歡的東西:

// Create an image type grayscale 
BufferedImage image = new BufferedImage(2, 2, BufferedImage.TYPE_BYTE_GRAY); 

// Get the backing pixels, and copy into it 
byte[] data = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); 
System.arraycopy(bytes, 0, data, 0, bytes.length); 

// Write it out: 
ImageIO.write(image, "jpg", new File("yourPathHere");