Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;

public class Main {
    public static final byte[] img_jpeg = { (byte) 0xFF, (byte) 0xD8 };
    public static final byte[] img_png = { (byte) 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };
    public static final byte[] img_gif = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 };
    public static final byte[] img_bmp = { 0x42, 0x4D };

    public static boolean isImage(Blob blob) throws Exception {
        InputStream in = null;
        byte[] bytes = new byte[8];
        try {
            in = blob.getBinaryStream();

            in.read(bytes);
            return isImage(bytes);
        } catch (Exception ex) {
            throw new Exception(ex.toString());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ex) {
                    throw new Exception(ex.toString());
                }
            }
            bytes = null;
        }
    }

    private static boolean isImage(byte[] byt) {
        if (byt == null || byt.length < 8) {
            return false;
        }

        if (byt[0] == img_jpeg[0] && byt[1] == img_jpeg[1]) {
            return true;
        } else if (byt[0] == img_png[0] && byt[1] == img_png[1] && byt[2] == img_png[2] && byt[3] == img_png[3]
                && byt[4] == img_png[4] && byt[5] == img_png[5] && byt[6] == img_png[6] && byt[7] == img_png[7]) {
            return true;
        } else if (byt[0] == img_gif[0] && byt[1] == img_gif[1] && byt[2] == img_gif[2] && byt[3] == img_gif[3]
                && (byt[4] == img_gif[4] || byt[4] == 0x37) && byt[5] == img_gif[5]) {
            return true;
        } else if (byt[0] == img_bmp[0] && byt[1] == img_bmp[1]) {
            return true;
        }
        return false;
    }
}