Search code examples
javaspringimagejpa

Compress Image as Byte Array


After a while and after a stresstest of my database and it's REST Api the following Problem occurred.

We save images as byte array in an Mysql Database via JPA/Hibernate annotated like this:

@Column(columnDefinition = "MEDIUMBLOB")
private byte[] photo;

Works as it should except when there are much high quality images and I want to retrieve all of them. Then the Response takes too long and event Postman gets stuck.

So I am searching for a solution to make those byte Arrays smaller. Is there a way to compress the image as byte array? Or would another approach be better, maybe paging (Not my the best approach in my opinion for the task we have to solve)?

Thanks in advance.


Solution

  • I assume that the problem you face is that you read many images in the same query and that they take too much memory, leading to garbage collection and other problems. Compressing the images would not help as you will want to decompress them again before returning them to the client, plus most image formats are already compressed.

    You could look into streaming instead, where you don't read all the matching images from the database into memory, but process them one at a time. Make sure that you stream the data you send to the client as well. If you get it right you can keep the memory usage down and you can send the first image to the client before you have read the others, reducing the time to first byte and making the response appear quick.

    Alternatively do as one of the comments suggested and read the meta data first, then read the full image data for one image at a time.