Question: I have an SQL query that returns a list of results. The sql is :

```
SELECT fcategory,sum(fquantity*fprice) AS qty FROM items GROUP BY fcategory

```

The output is something like

```
----------------
category|qty
----------------
   a    | 10
   b    | 100
   c    | 554

```

Based on the result of the sql statement above, how do I retrieve the row with maximum quantity? (in this case I want the query to return just "c" )

Answer: 
`ImageIO.read(...)` (and the `javax.imageio` package in general) is for reading/writing images from/to file formats. What you have is an array containing "raw" pixels. It's impossible for `ImageIO` to determine file format from this byte array. Because of this, it will return `null`.

Instead, you should create a `BufferedImage` from the bytes directly. I don't know OpenCV that well, but I'm assuming that the result of `Imgproc.cvtColor(rgba, rgba, Imgproc.COLOR_RGB2GRAY, 0)` will be an image in grayscale (8 bits/sample, 1 sample/pixel). This is the same format as [`BufferedImage.TYPE_BYTE_GRAY`](https://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferedImage.html#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's backing array and copy the pixels directly into it
byte[] data = ((DataBufferByte) gray.getRaster().getDataBuffer()).getData();
rgba.get(0, 0, data);

```

Doing it this way, saves you one large byte array allocation and one byte array copy as a bonus. :-)
I used this kind of code to convert Mat object to Buffered Image. 

```
static BufferedImage Mat2BufferedImage(Mat matrix)throws Exception {        
    MatOfByte mob=new MatOfByte();
    Imgcodecs.imencode(".jpg", matrix, mob);
    byte ba[]=mob.toArray();

    BufferedImage bi=ImageIO.read(new ByteArrayInputStream(ba));
    return bi;
}

```