How to reduce image size into 1MB

前端 未结 3 1345
情话喂你
情话喂你 2021-01-13 00:03

I want my application to upload image with no size limit, but in the code, I want to resize the image into 1MB if the image size exceeds. I have tried many ways but I could

3条回答
  •  孤街浪徒
    2021-01-13 00:20

    If you really want the Bitmap that scales down to the Bitmap that is the closest to a given amount of bytes, heres the method I use. (It does not uses a while loop)

    NOTE: This method only works if passed bitmap is in ARGB_8888 configuration. See: Compress bitmap to a specific byte size in Android for the conversion method.

    /**
     * Method to scale the Bitmap to respect the max bytes
     *
     * @param input    the Bitmap to scale if too large
     * @param maxBytes the amount of bytes the Image may be
     * @return The scaled bitmap or the input if already valid
     * @Note: The caller of this function is responsible for recycling once the input is no longer needed
     */
    public static Bitmap scaleBitmap(final Bitmap input, final long maxBytes) {
        final int currentWidth = input.getWidth();
        final int currentHeight = input.getHeight();
        final int currentPixels = currentWidth * currentHeight;
        // Get the amount of max pixels:
        // 1 pixel = 4 bytes (R, G, B, A)
        final long maxPixels = maxBytes / 4; // Floored
        if (currentPixels <= maxPixels) {
            // Already correct size:
            return input;
        }
        // Scaling factor when maintaining aspect ratio is the square root since x and y have a relation:
        final double scaleFactor = Math.sqrt(maxPixels / (double) currentPixels);
        final int newWidthPx = (int) Math.floor(currentWidth * scaleFactor);
        final int newHeightPx = (int) Math.floor(currentHeight * scaleFactor);
        Timber.i("Scaled bitmap sizes are %1$s x %2$s when original sizes are %3$s x %4$s and currentPixels %5$s and maxPixels %6$s and scaled total pixels are: %7$s",
                newWidthPx, newHeightPx, currentWidth, currentHeight, currentPixels, maxPixels, (newWidthPx * newHeightPx));
        final Bitmap output = Bitmap.createScaledBitmap(input, newWidthPx, newHeightPx, true);
        return output;
    }
    

    Where the Sample use would look something like:

    // (1 MB)
    final long maxBytes = 1024 * 1024; 
    // Scale it
    final Bitmap scaledBitmap = BitmapUtils.scaleBitmap(yourBitmap, maxBytes);
    if(scaledBitmap != yourBitmap){
        // Recycle the bitmap since we can use the scaled variant:
        yourBitmap.recycle();
    } 
    // ... do something with the scaled bitmap
    
    

提交回复
热议问题