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 :)
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).
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.
I think it is not a good idea to store binary in databases because if this grow up, it can be very slow.
Even though you want to do this, I think it is better to store the mime type when you are storing the binary.
精彩评论