Loading only part of a bitmap file in Android

后端 未结 5 817
醉话见心
醉话见心 2020-12-14 19:14

I would like to load a cropped version of a bitmap image into a Bitmap object, without loading the original bitmap as well.

Is this at all possible without writing c

5条回答
  •  情书的邮戳
    2020-12-14 19:59

    @RKN

    Your method can also throw OutOfMemoryError exception - if cropped bitmap exceeds VM.

    My method combines Yours and protection against this exeption: (l, t, r, b - % of image)

        Bitmap cropBitmap(ContentResolver cr, String file, float l, float t, float r, float b)
    {
        try 
        {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
    
            // First decode with inJustDecodeBounds=true to check dimensions
            BitmapFactory.decodeFile(file, options);
            int oWidth = options.outWidth;
            int oHeight = options.outHeight;
    
            InputStream istream = cr.openInputStream(Uri.fromFile(new File(file)));
    
            BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(istream, false);
            if (decoder != null)
            {
                options = new BitmapFactory.Options();
    
                int startingSize = 1;
                if ((r - l) * oWidth * (b - t) * oHeight > 2073600)
                    startingSize = (int) ((r - l) * oWidth * (b - t) * oHeight / 2073600) + 1;
    
                for (options.inSampleSize = startingSize; options.inSampleSize <= 32; options.inSampleSize++)
                {
                    try
                    {
                        return decoder.decodeRegion(new Rect((int) (l * oWidth), (int) (t * oHeight), (int) (r * oWidth), (int) (b * oHeight)), options);    
                    }
                    catch (OutOfMemoryError e)
                    {
                        Continue with for loop if OutOfMemoryError occurs
                    }
                }
            }
            else
                return null;
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    
        return null;
    }
    

    and returns max available bitmap or null

提交回复
热议问题