【问题标题】:How to decode a Bitmap to a certain filesize?如何将位图解码为特定的文件大小?
【发布时间】:2012-11-02 17:08:57
【问题描述】:

我目前正在缩小位图以避免 OutOfMemoryException。有没有办法指定要解码的文件大小?所以无论输入图像是什么文件大小,都会被缩小到指定的文件大小。

我正在使用来自http://androidbysravan.wordpress.com/category/outofmemory-exception-when-decoding-with-bitmapfactory/ 的以下代码,直到找到指定输出文件大小的方法。

Bitmap bm = null; 
BitmapFactory.Options options = new BitmapFactory.Options(); 
options.inSampleSize = 10; 
AssetFileDescriptor fileDescriptor =null; 
try { 
    fileDescriptor = _context.getContentResolver().openAssetFileDescriptor(selectedImage,"r"); 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} 
finally{ 
    try { 
        bm = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options); 
        fileDescriptor.close(); 
    } catch (IOException e) { 
        e.printStackTrace(); 
    } 
} 
return bm; 
} 

【问题讨论】:

  • 文件大小在这里没有意义,因为图像在文件中时被压缩(例如,PNG,JPEG)。

标签: android bitmap out-of-memory decode bitmapfactory


【解决方案1】:

您解码的图像将采用压缩格式,例如 PNG、JPEG 等。因此,当您解码它们时,您所做的就是将它们以 android 可以理解的格式解压缩到内存中。虽然您无法控制解码图像的大小,但是您可以使用BitmapFactory.Options 类控制允许您有效解码图像的某些属性。

这是关于如何正确使用此类来有效加载图像的优秀官方指南:

http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

【讨论】:

  • 感谢您的链接,我看了看并根据高度和我正在将位图加载到的 ImageView 计算 inSampleSize。
猜你喜欢
  • 2011-01-06
  • 1970-01-01
  • 2017-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多