I'm trying to read in an image file, convert it into a bytes array, process the individual bytes, and then convert it back into an image file and export it.
I've tried working on it, but it seems that ImageIO.read
can't read the ByteInputArrayStream
- it returns null.
Here's what I've tried so far (and the line that throws the error)
public static void RGBToGrayManual2(BufferedImage original) {
byte[] pixels = ((DataBufferByte) original.getRaster().getDataBuffer()).getData();
/*
* Code to process pixels
*/
ByteArrayInputStream grayscaleByteInputStream = new ByteArrayInputStream(pixels);
BufferedImage convertedGrayscale = null;
try {
// below line throws the error
convertedGrayscale = ImageIO.read(grayscaleByteInputStream);
ImageIO.write(convertedGrayscale, "jpg", new File("converted-grayscale-002.jpg"));
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
And the error message
Exception in thread "main" java.lang.IllegalArgumentException: image == null! at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925) at javax.imageio.ImageIO.getWriter(ImageIO.java:1591) at javax.imageio.ImageIO.write(ImageIO.java:1520) at project2.ImageProcessing.RGBToGrayManual2(ImageProcessing.java:252) at project2.ImageProcessing.main(ImageProcessing.java:284)
I've also looked at a similar post - Null returned from ImageIO.read(new ByteArrayInputStream(bs)); - and the accepted answer seems to suggest it's a problem with the encoding.
I've looked at this other post - Which Java library provides base64 encoding/decoding? - to decode the bytes array, but I don't think I'm doing it right.
Here's what I tried:
String encodedPixelsString = DatatypeConverter.printBase64Binary(pixels);
byte[] decodedPixelsString = DatatypeConverter.parseBase64Binary(encodedPixelsString);
ByteArrayInputStream pixelsStreamInputStream = new ByteArrayInputStream(decodedPixelsString);
And passed in the decoded array's ByteArrayInputStream as an argument
convertedGrayscale = ImageIO.read(pixelStreamInputStream);
However it yielded the exact same error message.
My thoughts on two possible directions to solve this problem - but I'm not sure about the details:
- Find out the problem with
ImageIO.read
method - Try exposing the bytes array of the image file in a different way
This is an assignment we have to do, but I've never worked with image processing before and as such, I'm a bit lost as to what to do. I would really appreciate any pointers