Resize a large bitmap file to scaled output file on Android

前端 未结 21 961
执念已碎
执念已碎 2020-11-22 05:51

I have a large bitmap (say 3888x2592) in a file. Now, I want to resize that bitmap to 800x533 and save it to another file. I normally would scale the bitmap by calling

21条回答
  •  失恋的感觉
    2020-11-22 06:19

    This is 'Mojo Risin's and 'Ofir's solutions "combined". This will give you a proportionally resized image with the boundaries of max width and max height.

    1. It only reads meta data to get the original size (options.inJustDecodeBounds)
    2. It uses a rought resize to save memory (itmap.createScaledBitmap)
    3. It uses a precisely resized image based on the rough Bitamp created earlier.

    For me it has been performing fine on 5 MegaPixel images an below.

    try
    {
        int inWidth = 0;
        int inHeight = 0;
    
        InputStream in = new FileInputStream(pathOfInputImage);
    
        // decode image size (decode metadata only, not the whole image)
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(in, null, options);
        in.close();
        in = null;
    
        // save width and height
        inWidth = options.outWidth;
        inHeight = options.outHeight;
    
        // decode full image pre-resized
        in = new FileInputStream(pathOfInputImage);
        options = new BitmapFactory.Options();
        // calc rought re-size (this is no exact resize)
        options.inSampleSize = Math.max(inWidth/dstWidth, inHeight/dstHeight);
        // decode full image
        Bitmap roughBitmap = BitmapFactory.decodeStream(in, null, options);
    
        // calc exact destination size
        Matrix m = new Matrix();
        RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight());
        RectF outRect = new RectF(0, 0, dstWidth, dstHeight);
        m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
        float[] values = new float[9];
        m.getValues(values);
    
        // resize bitmap
        Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap, (int) (roughBitmap.getWidth() * values[0]), (int) (roughBitmap.getHeight() * values[4]), true);
    
        // save image
        try
        {
            FileOutputStream out = new FileOutputStream(pathOfOutputImage);
            resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
        }
        catch (Exception e)
        {
            Log.e("Image", e.getMessage(), e);
        }
    }
    catch (IOException e)
    {
        Log.e("Image", e.getMessage(), e);
    }
    

提交回复
热议问题