Compress bitmap to a specific byte size in Android

前端 未结 4 2161
再見小時候
再見小時候 2020-12-18 11:28

Is there a way to compress Bitmap to a specific byte size? For example, 1.5MB. The matter is all the examples I have seen so far were resizing width and height, but my requi

4条回答
  •  没有蜡笔的小新
    2020-12-18 12:07

    See my answer at (Which doesn't use a while loop): How to reduce image size into 1MB

    This method works if your current passed Bitmap is in the ARGB_8888 configuration (So 4 bytes per pixel. When it isn't ARGB_8888 you can convert it to that bitmap by using:

    /**
     * Convert a Bitmap to a Bitmap that has 4 bytes per pixel
     * @param input The bitmap to convert to a 4 bytes per pixel Bitmap
     * 
     * @return The converted Bitmap. Note: The caller of this method is 
     * responsible for reycling the input
     */
    public static Bitmap to4BytesPerPixelBitmap(@NonNull final Bitmap input){
        final Bitmap bitmap = Bitmap.createBitmap(input.width, input.height, Bitmap.Config.ARGB_8888);
        // Instantiate the canvas to draw on:
        final Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(input, 0, 0, null);
        // Return the new bitmap:
        return bitmap;  
    }   
    

提交回复
热议问题