ImageIO.read(...) (and the javax.imageio package as a whole) is intended for reading / writing images from / to file formats. You have an array containing raw pixels. ImageIO can determine the file format from this byte array. Because of this, it will return null .
Instead, you should create a BufferedImage from bytes directly. I do not know OpenCV very well, but I assume that the result of Imgproc.cvtColor(rgba, rgba, Imgproc.COLOR_RGB2GRAY, 0) will be a grayscale image (8 bits / sample, 1 sample / pixel). This is the same format as BufferedImage.TYPE_BYTE_GRAY . If this assumption is correct, you should be able to do:
// Read image to Mat as before Mat rgba = ...; Imgproc.cvtColor(rgba, rgba, Imgproc.COLOR_RGB2GRAY, 0); // Create an empty image in matching format BufferedImage gray = new BufferedImage(rgba.width(), rgba.height(), BufferedImage.TYPE_BYTE_GRAY); // Get the BufferedImage backing array and copy the pixels directly into it byte[] data = ((DataBufferByte) gray.getRaster().getDataBuffer()).getData(); rgba.get(0, 0, data);
By doing this this way, you save one allocation of a large byte array and one copy of the byte array as a bonus. :-)
source share