简体   繁体   中英

Most efficient way to check if image used to create bitmap was .PNG - Android

Given a bitmap object I want to determine if the image I used to create the Bitmap was in.PNG or.JPG format. I wrote the below code to determine that. I perform a scaling operation to the bitmap and then search pixel by pixel to find if there is any transparent pixel. Is there any better way to do that?

public static boolean isBitmapPNG(Bitmap bitmap)
{
    int scaledWidth=20;
    int scaledHeight=20;
    Bitmap scaledBitmap = resizeBitmap(bitmap,scaledWidth,scaledHeight);

    for (int x=0;x<scaledBitmap.getWidth();x++)
        for (int y=0;y<scaledBitmap.getHeight();y++)
            if (((scaledBitmap.getPixel(x,y) & 0xff000000) >> 24)==0)
                return true;
             
   return false;     
}


public static Bitmap resizeBitmap(Bitmap image, int maxWidth, int maxHeight)
{
    if (maxHeight > 0 && maxWidth > 0) {
        int width = image.getWidth();
        int height = image.getHeight();
        float ratioBitmap = (float) width / (float) height;
        float ratioMax = (float) maxWidth / (float) maxHeight;

        int finalWidth = maxWidth;
        int finalHeight = maxHeight;
        if (ratioMax > ratioBitmap) {
            finalWidth = (int) ((float)maxHeight * ratioBitmap);
        } else {
            finalHeight = (int) ((float)maxWidth / ratioBitmap);
        }
        image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true);
        return image;
    } else {
        return image;
    }
}

Try:

bitmap.hasAlpha() method. If it returns true then it is a png. If not then jpg.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM