2014-03-13 2 views
7

나는 몇 가지 코드 소스를 봐 왔지만, 이해가 안 자바 7JAVA : 바이트 [.]에서 .PNG 이미지를 만드는 방법? <p></p> 내가 사용 ...

하시기 바랍니다하는 RGB (빨강, 녹색, 파랑) 바이트 배열로 변환하는 방법 (또는 이와 비슷한 것) 을 .PNG 파일 형식? 의 "RGB 픽셀"을 나타낼 수있는 배열에서

예 :

byte[] aByteArray={0xa,0x2,0xf}; 

중요한 양상 :

I 만 [] "하지 바이트에서 .PNG 파일을 생성 할 이전 기존 파일 "

기존 API로 가능합니까? ;) 여기

내 첫 번째 코드 :

byte[] aByteArray={0xa,0x2,0xf}; 
ByteArrayInputStream bais = new ByteArrayInputStream(aByteArray); 
File outputfile = new File("image.png"); 
ImageIO.write(bais, "png", outputfile); 

.... 오류 : 여기에 다른 버전

제레미에서 수정되었지만 유사 찾을 수 없음 적절한 방법 :

byte[] aByteArray={0xa,0x2,0xf}; 
ByteArrayInputStream bais = new ByteArrayInputStream(aByteArray); 
final BufferedImage bufferedImage = ImageIO.read(newByteArrayInputStream(aByteArray)); 
ImageIO.write(bufferedImage, "png", new File("image.png")); 

.... 복수 오류 : image == null! ...... 그래? 참고 : 소스 파일을 사용하여 검색하지 않습니다.

+0

이해가되지 않는 코드를 게시 해 주시면 도와 드리겠습니다. – wattostudios

답변

10

이미지 I/O API는 이미지를 처리하기 때문에 먼저 바이트 배열의 이미지를 작성해야합니다.

byte[] aByteArray = {0xa,0x2,0xf,(byte)0xff,(byte)0xff,(byte)0xff}; 
int width = 1; 
int height = 2; 

DataBuffer buffer = new DataBufferByte(aByteArray, aByteArray.length); 

//3 bytes per pixel: red, green, blue 
WritableRaster raster = Raster.createInterleavedRaster(buffer, width, height, 3 * width, 3, new int[] {0, 1, 2}, (Point)null); 
ColorModel cm = new ComponentColorModel(ColorModel.getRGBdefault().getColorSpace(), false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); 
BufferedImage image = new BufferedImage(cm, raster, true, null); 

ImageIO.write(image, "png", new File("image.png")); 

바이트 배열에 픽셀 당 3 바이트 (빨강, 초록, 파랑)가 있고 값의 범위가 0-255 인 것으로 가정합니다.

+0

모든 도움을 주셔서 감사합니다.) 예 코드가 좋고 잘 수행 할 수 있습니다.^_^ – MadMonkey

+0

각 행의 의미와 이유를 설명하는 것이 좋습니다. – ianaz

관련 문제