简体   繁体   中英

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.

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

I think your best way is to just grab the bufferedimage rather than save it:

Use ImagePlus myImage = IJ.getImage(); to return an ImagePlus object, then you can use myImage.getBufferedImage() to return a standard java.awt.image.BufferedImage and now you can continue to work with the buffered image without the need for the ImagePlus library.

ImagePlus img = IJ.openImage(f.getAbsolutePath()); // Open image
new ImageConverter(img).convertToGray8(); // Convert image to 8-bit grayscale
ImagePlus myImage = IJ.getImage();
BufferedImage bufferedImage = myImage.getBufferedImage();
// Process bufferedImage

From the ImagePlus method: https://imagej.nih.gov/ij/developer/api/ij/ImagePlus.html

public java.awt.image.BufferedImage getBufferedImage()

Returns a copy of this image as an 8-bit or RGB BufferedImage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM