OutOfMemory exception when loading bitmap from external storage

前端 未结 13 1706
广开言路
广开言路 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:33

    The best solution i found and edited according to my need
    
    public static Bitmap getImageBitmap(String path) throws IOException{
            // Allocate files and objects outside of timingoops             
            File file = new File(thumbpath);        
            RandomAccessFile in = new RandomAccessFile(file, "rws");
            final FileChannel channel = in.getChannel();
            final int fileSize = (int)channel.size();
            final byte[] testBytes = new byte[fileSize];
            final ByteBuffer buff = ByteBuffer.allocate(fileSize);
            final byte[] buffArray = buff.array();
            @SuppressWarnings("unused")
            final int buffBase = buff.arrayOffset();
    
            // Read from channel into buffer, and batch read from buffer to byte array;
            long time1 = System.currentTimeMillis();
            channel.position(0);
            channel.read(buff);
            buff.flip();
            buff.get(testBytes);
            long time1 = System.currentTimeMillis();
            Bitmap bmp = Bitmap_process(buffArray);
            long time2 = System.currentTimeMillis();        
            System.out.println("Time taken to load: " + (time2 - time1) + "ms");
    
            return bmp;
        }
    
        public static Bitmap Bitmap_process(byte[] buffArray){
            BitmapFactory.Options options = new BitmapFactory.Options();
    
            options.inDither=false;                     //Disable Dithering mode
            options.inPurgeable=true;                   //Tell to gc that whether it needs free memory, the Bitmap can be cleared
            options.inInputShareable=true;              //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
            options.inTempStorage=new byte[32 * 1024];  //Allocate some temporal memory for decoding
    
            options.inSampleSize=1;
    
            Bitmap imageBitmap = BitmapFactory.decodeByteArray(buffArray, 0, buffArray.length, options);
            return imageBitmap;
        }
    

提交回复
热议问题