Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ImageOutputStream to byte[]

Tags:

java

image

jai

Have been trying to convert ImageOutputStream to byte[] for a while using JAI. Any inputs are appreciated. Thanks.

Sorry here is the code snippet, I am working on. I had to post it earlier. The problem I am facing is that, I am able to get ByteArrayOutputStream from ImageOutputStream. But it always gives me zero bytes. But if I use a FileOutputStream instead of a ByteArrayOuputStream, I can write into a file which has non zero bytes. :

File file = new File("C:/TIFFImages/tiff-image.tiff");
FileInputStream in = new FileInputStream(file);
long filelength = file.length();
byte[] bytes = new byte[(int)filelength]; 
int offset = 0; 
int numRead = 0; 

while (offset < bytes.length && (numRead=in.read(bytes, offset, bytes.length-offset)) >= 0) { 
    offset += numRead; 
} 
if (offset < bytes.length) { 
    throw new IOException("Could not completely read file "+file.getName()); 
} 

ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

RenderedImage src = JAI.create("stream", SeekableStream.wrapInputStream(bais, true));
RenderedOp renderedOp = MedianFilterDescriptor.create(src, MedianFilterDescriptor.MEDIAN_MASK_SQUARE , 1, null);
BufferedImage image = renderedOp.getAsBufferedImage();

ByteArrayOutputStream baos = new ByteArrayOutputStream();

ImageOutputStream  ios =  ImageIO.createImageOutputStream(baos);
//Instead of baos if I pass a FileOutputStream to the above function. It writes non zero
//bytes to the output file

TIFFImageWriterSpi tiffspi = new TIFFImageWriterSpi();
ImageWriter writer = tiffspi.createWriterInstance();
RenderedImage renderedImage = PlanarImage.wrapRenderedImage(src);
writer.setOutput(ios);
writer.write(image);
writer.write(null,new IIOImage(image, null, null), param);

System.out.println("After tiff ImageIO operations" + baos.toByteArray().length);

Thanks , Vinay

like image 681
vinaynag Avatar asked Aug 17 '10 23:08

vinaynag


1 Answers

I'm pretty sure it's because you're not calling ImageOutputStream.flush() at the end of the operation - if the IOS created is a MemoryCacheOutputStream, it seems to require an explicit flush on some ImageIO implementations.

like image 125
Nick Avatar answered Oct 16 '22 09:10

Nick