Java SQL Blob getBlobType(byte[] image)

Here you can find the source of getBlobType(byte[] image)

Description

get Blob Type

License

Open Source License

Declaration

public static String getBlobType(byte[] image) 

Method Source Code

//package com.java2s;
/**/* ww  w .  j  a  v a 2  s .  co  m*/
 * Tysan Clan Website
 * Copyright (C) 2008-2013 Jeroen Steenbeeke and Ties van de Ven
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.sql.Blob;
import java.sql.SQLException;

public class Main {
    public static String getBlobType(byte[] image) {
        if (isJPEGImage(image)) {
            return "jpg";
        } else if (isPNGImage(image)) {
            return "png";
        } else if (isGIFImage(image)) {
            return "gif";
        }

        return "png";
    }

    public static String getBlobType(Blob blob) {
        try {
            byte[] image = blob.getBytes(0, (int) blob.length());

            return getBlobType(image);
        } catch (SQLException e) {
            // Silent ignore
        }

        return "png";
    }

    public static boolean isJPEGImage(byte[] image) {
        return image != null && image.length > 2 && image[0] == (byte) 0xFF && image[1] == (byte) 0xD8;
    }

    public static boolean isPNGImage(byte[] image) {
        return image != null && image.length > 8 && image[0] == -119 && image[1] == 80 && image[2] == 78
                && image[3] == 71 && image[4] == 13 && image[5] == 10 && image[6] == 26 && image[7] == 10;
    }

    /**
     * Checks if an image is a GIF file
     * 
     * @param image
     *            The image to check
     * @return {@code true} if we suspect this file is a GIF file, {@code false}
     *         otherwise
     */
    public static boolean isGIFImage(byte[] image) {
        return image != null && image.length > 6 && image[0] == (byte) 0x47 && image[1] == (byte) 0x49
                && image[2] == (byte) 0x46 && image[3] == (byte) 0x38
                && (image[4] == (byte) 0x39 || image[4] == (byte) 0x37) && image[5] == (byte) 0x61;
    }
}

Related

  1. blob2FloatArray(Blob blob)
  2. blobToBytes(Blob blob)
  3. blobToBytes(Blob blob)
  4. getAsString(Blob blob)
  5. getDataFromBlob(Blob b)
  6. getDataFromBlob(Blob b)
  7. getLongBlobTypeString(Connection conn)
  8. getString(Blob blob)