Android Image Type Get guessImageType(final byte[] input)

Here you can find the source of guessImageType(final byte[] input)

Description

Guesses the format of input image.

License

Open Source License

Parameter

Parameter Description
input Image as byte array.

Return

The image type or null when the type cannot be determined.

Declaration

public static String guessImageType(final byte[] input) 

Method Source Code

//package com.java2s;
/*//from ww w  . j a  v  a  2s .  c o m
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * Guesses the format of input image. Currently just the first few bytes are used. The type "GIF", "PNG", or "JPEG" is
     * returned when possible. Returns null when the guess failed.
     * 
     * @param input
     *            Image as byte array.
     * @return The image type or null when the type cannot be determined.
     */
    public static String guessImageType(final byte[] input) {
        if (input == null) {
            return null;
        }
        if (input.length >= 3 && input[0] == 'G' && input[1] == 'I'
                && input[2] == 'F') {
            return "GIF";
        } else if (input.length >= 4 && input[0] == (byte) 0x89
                && input[1] == 'P' && input[2] == 'N' && input[3] == 'G') {
            // Note: vCard 2.1 officially does not support PNG, but we may have it and
            // using X- word like "X-PNG" may not let importers know it is PNG.
            // So we use the String "PNG" as is...
            return "PNG";
        } else if (input.length >= 2 && input[0] == (byte) 0xff
                && input[1] == (byte) 0xd8) {
            return "JPEG";
        } else {
            return null;
        }
    }
}

Related

  1. checkAndroidImageFormat(Image image)
  2. getFileSuffix(byte[] bytes)