How to get the Image Format of the images from Gallery

Vineet Shukla picture Vineet Shukla · Feb 23, 2012 · Viewed 8.7k times · Source

I want to know the Image format (i.e. JPFG/PNG etc) of the images which I am getting from the gallery.

My need is to pic images from the gallery of the device and send it to server in Base64 format but the server wants to know image format.

Any help is appreciated.

Answer

dbernard picture dbernard · Apr 17, 2012

Edited:

Use the following method to retrieve the MIME type of an image from the gallery:

public static String GetMimeType(Context context, Uri uriImage)
{
    String strMimeType = null;

    Cursor cursor = context.getContentResolver().query(uriImage,
                        new String[] { MediaStore.MediaColumns.MIME_TYPE },
                        null, null, null);

    if (cursor != null && cursor.moveToNext())
    {
        strMimeType = cursor.getString(0);
    }

    return strMimeType;
}

This will return something like "image/jpeg".


Previous answer:

You can use the following code to convert the image from the Gallery to the format you want, like a JPG:

ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();

Bitmap bitmapImage = BitmapFactory.decodeStream(
                         getContentResolver().openInputStream(myImageUri));

if (bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, outputBuffer))
{
    // Then perform a base64 of the byte array...
}

This way you will control the image format your are sending to the server, and can even compress more to save bandwidth. ;)