Search code examples
javaimageimagej

ImageJ - Convert image format without saving file


I'm using ImageJ API to convert some 24-bit TIFF images to 8-bit JPG. After the conversion I need to do other processing on these images. I made this:

ImagePlus img = IJ.openImage(f.getAbsolutePath()); // Open image
new ImageConverter(img).convertToGray8(); // Convert image to 8-bit grayscale
IJ.saveAs(img, "jpg", newPath); // Export image to jpg
// Read the same image again
// Process it

My problem is that the conversion must save the image to disk and I have to read it again immediately after, also I'm processing a large number of images. Is there a way to create the jpg image and put into an object without storing it on disk?

Specifically, my goal is to create an Hadoop SequenceFile with the byte content of the images so I don't need to store them at all.


Solution

  • You can get the raw buffered image from the ImagePlus class as such:

    BufferedImage rawImage = img.getBufferedImage();
    

    So theoretically you could use the API from there on to get the bytes instead of writing on the disk

    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    ImageIO.write(rawImage, "jpg", baos);
    byte[] imageInByte=baos.toByteArray();
    

    Hopefully, this would work