OutOfMemory exception when loading bitmap from external storage

前端 未结 13 1732
广开言路
广开言路 2020-11-29 06:52

In my application I load a couple of images from JPEG and PNG files. When I place all those files into assets directory and load it in this way, everything is ok:

         


        
13条回答
  •  星月不相逢
    2020-11-29 07:15

    Allows inSampleSize resize the final read image. getLength() of AssetFileDescriptor allows get size of file.

    You can vary inSampleSize according to getLength() to prevent OutOfMemory like this :

    private final int MAX_SIZE = 500000;
    
    public Bitmap readBitmap(Uri selectedImage)
    {
        Bitmap bm = null;
        AssetFileDescriptor fileDescriptor = null;
        try
        {
            fileDescriptor = this.getContentResolver().openAssetFileDescriptor(selectedImage,"r");
            long size = fileDescriptor.getLength();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = (int) (size / MAX_SIZE);
            bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try {
                if(fileDescriptor != null) fileDescriptor.close();
            } catch (IOException e) {}
        }
        return bm;
    }
    

提交回复
热议问题