Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting mime-type of a MySQL BLOB in Java

Yes I know that we shouldn't store images on a database, thanks.

That said, is there a way to detect in java the mime type of a BLOB stored in mysql?

It is only for images (.gif, .png, .jpeg, etc.) I don't need a common purpose tool.

Thanks a lot guys

Bonus points if the proposed solution does not involve 3rd party libs :)

like image 863
Pablo Fernandez Avatar asked May 10 '11 23:05

Pablo Fernandez


2 Answers

I imagine that you can take a look at the headers. You need to read the data into a byte array and then examine the bytes to see if they match up to the headers for the different file-types.

For example, for a GIF, the first three bytes are "GIF" (4716 4916 4616) followed by either "87a" (3816 3716 6116) or "89a" (3816 3916 6116).

So something like this should work (uses a FileInputStream for demonstration purposes, but you can get the binary data from a BLOB by using ResultSet#getBinaryStream(int) or ResultSet#getBinaryStream(String)):

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

public class IdentifyImage {
    public static void main(String[] args) throws IOException {
        FileInputStream in = null;

        try {
            in = new FileInputStream("sample.gif");

            //The following are in base 10
            byte[] gifHeader87a = {71, 73, 70, 56, 55, 97};
            byte[] gifHeader89a = {71, 73, 70, 56, 57, 97};

            byte[] bytes = new byte[6];
            in.read(bytes, 0, 6);

            if(Arrays.equals(gifHeader89a, bytes) || Arrays.equals(gifHeader87a, bytes)) {
               System.out.println("It's a GIF!");
            }

        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
}

You just need to look up the bytes in the header for other file types (like JPG, PNG, etc.). Not sure if this is the best way. Someone may have a better solution.

As far as 3rd-party libraries, jMimeMagic is pretty good. This is probably the easiest solution :).

EDIT

I found this article here that lists header information for different file types. There is some sample code, but it's written in another language (Clarion).

like image 90
Vivin Paliath Avatar answered Sep 24 '22 17:09

Vivin Paliath


Honestly, storing images in databases is a-ok if you remember that you can always employ caching strategies to avoid certain issues. And modern computers tend to be able to handle the load for most scenarios. Anyhow, a key thing to remember when storing the blob is to store the mimetype with it on the way in as it tends to be pretty easy to divine then.

like image 39
Wyatt Barnett Avatar answered Sep 24 '22 17:09

Wyatt Barnett