Detecting MySQL BLOB mime type in Java

Yes, I know that we should not store images in a database , thanks.

However, is there a way to detect in java the mime blob type stored in mysql?

This is only for images (.gif, .png, .jpeg, etc.). I do not need a tool for a common goal.

Many thanks guys

Bonus points if the proposed solution is not related to third-party libs :)

+5
source share
3 answers

I guess you can take a look at the headlines. You need to read the data into an array of bytes, and then examine the bytes to see if they match the headers for different types of files.

, GIF "GIF" (47 16 49 16 46 16), "87a" (38 16 37 16 61 16)) "89a" (38 16 39 16 61 16).

, - ( FileInputStream, BLOB ResultSet#getBinaryStream(int) 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 a GIF!");
            }

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

(, JPG, PNG ..). , . - .

, jMimeMagic . , , :).

, . , (Clarion).

+2

, - , , , . , , . , , blob, - mimetype , , , .

+2

, , , .

Even if you want to do this, I think it's better to store the mime type while saving the binary.

0
source

All Articles