当前位置:   article > 正文

将图像加载到位图对象时出现内存不足问题_improper call to jpeg library in state 100

improper call to jpeg library in state 100

我有一个列表视图,每行都有几个图像按钮。 当您单击列表行时,它将启动一个新活动。 由于相机布局存在问题,我不得不构建自己的标签。 为结果而启动的活动是地图。 如果单击我的按钮以启动图像预览(将图像从SD卡加载),则应用程序将从活动返回到listview活动,再返回到结果处理程序,以重新启动我的新活动,无非就是图像小部件。

列表视图上的图像预览是使用光标和ListAdapter 。 这非常简单,但是我不确定如何放置一个调整大小后的图像(即,较小的位大小而不是像素作为飞行中图像按钮的src 。因此,我只是调整了从电话摄像头传来的图像的大小。

问题是,当它尝试返回并重新启动第二个活动时,出现内存不足错误。

  • 有没有一种方法可以轻松地逐行构建列表适配器,从而可以即时调整大小(逐 )?

这将是更可取的,因为我也需要对每行中的小部件/元素的属性进行一些更改,因为由于焦点问题而无法使用触摸屏选择一行。 ( 我可以用滚球。

  • 我知道我可以进行带外调整大小并保存图像,但这并不是我真正想做的,但是一些示例代码会很不错。

一旦禁用列表视图中的图像,它就会再次正常工作。

仅供参考:这就是我的做法:

  1. String[] from = new String[] { DBHelper.KEY_BUSINESSNAME,DBHelper.KEY_ADDRESS,DBHelper.KEY_CITY,DBHelper.KEY_GPSLONG,DBHelper.KEY_GPSLAT,DBHelper.KEY_IMAGEFILENAME + ""};
  2. int[] to = new int[] {R.id.businessname,R.id.address,R.id.city,R.id.gpslong,R.id.gpslat,R.id.imagefilename };
  3. notes = new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
  4. setListAdapter(notes);

其中R.id.imagefilenameButtonImage

这是我的LogCat:

  1. 01-25 05:05:49.877: ERROR/dalvikvm-heap(3896): 6291456-byte external allocation too large for this process.
  2. 01-25 05:05:49.877: ERROR/(3896): VM wont let us allocate 6291456 bytes
  3. 01-25 05:05:49.877: ERROR/AndroidRuntime(3896): Uncaught handler: thread main exiting due to uncaught exception
  4. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
  5. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
  6. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:304)
  7. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:149)
  8. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:174)
  9. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.graphics.drawable.Drawable.createFromPath(Drawable.java:729)
  10. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.ImageView.resolveUri(ImageView.java:484)
  11. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.ImageView.setImageURI(ImageView.java:281)
  12. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.SimpleCursorAdapter.setViewImage(SimpleCursorAdapter.java:183)
  13. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.SimpleCursorAdapter.bindView(SimpleCursorAdapter.java:129)
  14. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.CursorAdapter.getView(CursorAdapter.java:150)
  15. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.AbsListView.obtainView(AbsListView.java:1057)
  16. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.ListView.makeAndAddView(ListView.java:1616)
  17. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.ListView.fillSpecific(ListView.java:1177)
  18. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.ListView.layoutChildren(ListView.java:1454)
  19. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.AbsListView.onLayout(AbsListView.java:937)
  20. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.view.View.layout(View.java:5611)
  21. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1119)
  22. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.LinearLayout.layoutHorizontal(LinearLayout.java:1108)
  23. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.LinearLayout.onLayout(LinearLayout.java:922)
  24. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.view.View.layout(View.java:5611)
  25. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.FrameLayout.onLayout(FrameLayout.java:294)
  26. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.view.View.layout(View.java:5611)
  27. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1119)
  28. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:999)
  29. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.LinearLayout.onLayout(LinearLayout.java:920)
  30. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.view.View.layout(View.java:5611)
  31. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.widget.FrameLayout.onLayout(FrameLayout.java:294)
  32. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.view.View.layout(View.java:5611)
  33. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.view.ViewRoot.performTraversals(ViewRoot.java:771)
  34. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.view.ViewRoot.handleMessage(ViewRoot.java:1103)
  35. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.os.Handler.dispatchMessage(Handler.java:88)
  36. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.os.Looper.loop(Looper.java:123)
  37. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at android.app.ActivityThread.main(ActivityThread.java:3742)
  38. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at java.lang.reflect.Method.invokeNative(Native Method)
  39. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at java.lang.reflect.Method.invoke(Method.java:515)
  40. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
  41. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:497)
  42. 01-25 05:05:49.917: ERROR/AndroidRuntime(3896): at dalvik.system.NativeStart.main(Native Method)
  43. 01-25 05:10:01.127: ERROR/AndroidRuntime(3943): ERROR: thread attach failed

显示图像时也出现了新错误:

  1. 01-25 22:13:18.594: DEBUG/skia(4204): xxxxxxxxxxx jpeg error 20 Improper call to JPEG library in state %d
  2. 01-25 22:13:18.604: INFO/System.out(4204): resolveUri failed on bad bitmap uri:
  3. 01-25 22:13:18.694: ERROR/dalvikvm-heap(4204): 6291456-byte external allocation too large for this process.
  4. 01-25 22:13:18.694: ERROR/(4204): VM won't let us allocate 6291456 bytes
  5. 01-25 22:13:18.694: DEBUG/skia(4204): xxxxxxxxxxxxxxxxxxxx allocPixelRef failed

#1楼

Android Training类“ 高效显示位图 ”为理解和处理异常java.lang.OutOfMemoryError: bitmap size exceeds VM budget提供了一些重要信息java.lang.OutOfMemoryError: bitmap size exceeds VM budget加载位图时位java.lang.OutOfMemoryError: bitmap size exceeds VM budget


读取位图尺寸和类型

BitmapFactory类提供了几种用于从各种来源创建Bitmap解码方法( decodeByteArray()decodeFile()decodeResource()等)。 根据您的图像数据源选择最合适的解码方法。 这些方法尝试为构造的位图分配内存,因此很容易导致OutOfMemory异常。 每种类型的解码方法都有其他签名,可让您通过BitmapFactory.Options类指定解码选项。 解码时将inJustDecodeBounds属性设置为true可以避免内存分配,为位图对象返回null ,但是设置outWidthoutHeightoutMimeType 。 此技术使您可以在位图的构造(和内存分配)之前读取图像数据的尺寸和类型。

  1. BitmapFactory.Options options = new BitmapFactory.Options();
  2. options.inJustDecodeBounds = true;
  3. BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
  4. int imageHeight = options.outHeight;
  5. int imageWidth = options.outWidth;
  6. String imageType = options.outMimeType;

为避免java.lang.OutOfMemory异常,请在解码位图之前检查其大小,除非您完全相信该源可为您提供大小可预测的图像数据,以适合可用内存。


将缩小版本加载到内存

现在已经知道了图像尺寸,可以将它们用于确定是否应将完整图像加载到内存中,或者是否应该加载子采样版本。 以下是一些要考虑的因素:

  • 将完整映像加载到内存中的估计内存使用情况。
  • 给定应用程序的任何其他内存要求,您愿意承诺加载此映像的内存量。
  • 要将图像加载到其中的目标ImageView或UI组件的尺寸。
  • 当前设备的屏幕尺寸和密度。

例如,如果将1024x768像素的图像最终显示在ImageView中的128x96像素的缩略图中,则不值得将其加载到内存中。

要告诉解码器对图像进行二次采样,将较小的版本加载到内存中,请在BitmapFactory.Options对象中将inSampleSize设置为true 。 例如,使用inSampleSize为4解码的分辨率为2048x1536的图像会生成大约512x384的位图。 将其加载到内存中需要使用0.75MB而不是12MB的完整图像(假设ARGB_8888的位图配置)。 这是一种根据目标宽度和高度计算样本大小值(是2的幂)的方法:

  1. public static int calculateInSampleSize(
  2. BitmapFactory.Options options, int reqWidth, int reqHeight) {
  3. // Raw height and width of image
  4. final int height = options.outHeight;
  5. final int width = options.outWidth;
  6. int inSampleSize = 1;
  7. if (height > reqHeight || width > reqWidth) {
  8. final int halfHeight = height / 2;
  9. final int halfWidth = width / 2;
  10. // Calculate the largest inSampleSize value that is a power of 2 and keeps both
  11. // height and width larger than the requested height and width.
  12. while ((halfHeight / inSampleSize) > reqHeight
  13. && (halfWidth / inSampleSize) > reqWidth) {
  14. inSampleSize *= 2;
  15. }
  16. }
  17. return inSampleSize;
  18. }

注意 :计算2的幂是因为解码器根据inSampleSize文档通过舍入到最接近的2的幂来使用最终值。

要使用此方法,请先将inJustDecodeBounds设置为true进行解码,再传递选项,然后使用新的inSampleSize值和inJustDecodeBounds设置为false再次解码:

  1. public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
  2. int reqWidth, int reqHeight) {
  3. // First decode with inJustDecodeBounds=true to check dimensions
  4. final BitmapFactory.Options options = new BitmapFactory.Options();
  5. options.inJustDecodeBounds = true;
  6. BitmapFactory.decodeResource(res, resId, options);
  7. // Calculate inSampleSize
  8. options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
  9. // Decode bitmap with inSampleSize set
  10. options.inJustDecodeBounds = false;
  11. return BitmapFactory.decodeResource(res, resId, options);
  12. }

使用此方法可以轻松地将任意大尺寸的位图加载到显示100x100像素缩略图的ImageView中,如以下示例代码所示:

  1. mImageView.setImageBitmap(
  2. decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));

通过根据需要替换适当的BitmapFactory.decode*方法,可以遵循类似的过程来解码其他来源的位图。


#2楼

这对我有用!

  1. public Bitmap readAssetsBitmap(String filename) throws IOException {
  2. try {
  3. BitmapFactory.Options options = new BitmapFactory.Options();
  4. options.inPurgeable = true;
  5. Bitmap bitmap = BitmapFactory.decodeStream(assets.open(filename), null, options);
  6. if(bitmap == null) {
  7. throw new IOException("File cannot be opened: It's value is null");
  8. } else {
  9. return bitmap;
  10. }
  11. } catch (IOException e) {
  12. throw new IOException("File cannot be opened: " + e.getMessage());
  13. }
  14. }

#3楼

通过调用System.gc()等不能完全解决此类OutofMemoryException

通过参考 活动生命周期

活动状态由操作系统本身决定,取决于每个进程的内存使用情况和每个进程的优先级。

您可以考虑所使用的每个位图图片的大小和分辨率。 我建议减小尺寸,重新采样以降低分辨率,请参考画廊的设计(一幅小图片PNG和一幅原始图片。)


#4楼

仅在Android模拟器中会发生此问题。 我在模拟器中也遇到了这个问题,但是当我检入设备时,它运行良好。

因此,请检入设备。 它可以在设备中运行。


#5楼

我最近看到了很多有关OOM异常和缓存的问题。 开发人员指南对此有非常好的文章 ,但有些人往往无法以合适的方式实现它。

因此,我编写了一个示例应用程序,演示了在Android环境中的缓存。 此实现尚未获得OOM。

在此答案的末尾找到源代码的链接。

要求:

  • Android API 2.1或更高版本(我根本无法在API 1.6中获取应用程序的可用内存-这是唯一在API 1.6中不起作用的代码)
  • Android支持包

屏幕截图

特征:

  • 如果方向改变则保留缓存 ,使用单例
  • 将分配的应用程序内存的八分之一用于高速缓存(如果需要,请修改)
  • 大型位图会缩放 (您可以定义要允许的最大像素)
  • 在下载位图之前控制是否有Internet连接可用
  • 确保每行仅实例化一个任务
  • 如果您不使用ListView ,它根本不会下载之间的位图

这不包括:

  • 磁盘缓存。 无论如何,这应该很容易实现-只是指向另一个任务,该任务从磁盘上获取位图

样例代码:

正在下载的图像是来自Flickr的图像(75x75)。 但是,请放置您要处理的任何图像URL,如果超出最大数量,应用程序将按比例缩小它。 在此应用程序中,URL仅位于String数组中。

LruCache具有处理位图的好方法。 但是,在此应用程序中,我将LruCache的实例放在我创建的另一个缓存类中,以使应用程序更可行。

Cache.java的关键要素( loadBitmap()方法最重要):

  1. public Cache(int size, int maxWidth, int maxHeight) {
  2. // Into the constructor you add the maximum pixels
  3. // that you want to allow in order to not scale images.
  4. mMaxWidth = maxWidth;
  5. mMaxHeight = maxHeight;
  6. mBitmapCache = new LruCache<String, Bitmap>(size) {
  7. protected int sizeOf(String key, Bitmap b) {
  8. // Assuming that one pixel contains four bytes.
  9. return b.getHeight() * b.getWidth() * 4;
  10. }
  11. };
  12. mCurrentTasks = new ArrayList<String>();
  13. }
  14. /**
  15. * Gets a bitmap from cache.
  16. * If it is not in cache, this method will:
  17. *
  18. * 1: check if the bitmap url is currently being processed in the
  19. * BitmapLoaderTask and cancel if it is already in a task (a control to see
  20. * if it's inside the currentTasks list).
  21. *
  22. * 2: check if an internet connection is available and continue if so.
  23. *
  24. * 3: download the bitmap, scale the bitmap if necessary and put it into
  25. * the memory cache.
  26. *
  27. * 4: Remove the bitmap url from the currentTasks list.
  28. *
  29. * 5: Notify the ListAdapter.
  30. *
  31. * @param mainActivity - Reference to activity object, in order to
  32. * call notifyDataSetChanged() on the ListAdapter.
  33. * @param imageKey - The bitmap url (will be the key).
  34. * @param imageView - The ImageView that should get an
  35. * available bitmap or a placeholder image.
  36. * @param isScrolling - If set to true, we skip executing more tasks since
  37. * the user probably has flinged away the view.
  38. */
  39. public void loadBitmap(MainActivity mainActivity,
  40. String imageKey, ImageView imageView,
  41. boolean isScrolling) {
  42. final Bitmap bitmap = getBitmapFromCache(imageKey);
  43. if (bitmap != null) {
  44. imageView.setImageBitmap(bitmap);
  45. } else {
  46. imageView.setImageResource(R.drawable.ic_launcher);
  47. if (!isScrolling && !mCurrentTasks.contains(imageKey) &&
  48. mainActivity.internetIsAvailable()) {
  49. BitmapLoaderTask task = new BitmapLoaderTask(imageKey,
  50. mainActivity.getAdapter());
  51. task.execute();
  52. }
  53. }
  54. }

除非要实现磁盘缓存,否则无需编辑Cache.java文件中的任何内容。

MainActivity.java的关键内容:

  1. public void onScrollStateChanged(AbsListView view, int scrollState) {
  2. if (view.getId() == android.R.id.list) {
  3. // Set scrolling to true only if the user has flinged the
  4. // ListView away, hence we skip downloading a series
  5. // of unnecessary bitmaps that the user probably
  6. // just want to skip anyways. If we scroll slowly it
  7. // will still download bitmaps - that means
  8. // that the application won't wait for the user
  9. // to lift its finger off the screen in order to
  10. // download.
  11. if (scrollState == SCROLL_STATE_FLING) {
  12. mIsScrolling = true;
  13. } else {
  14. mIsScrolling = false;
  15. mListAdapter.notifyDataSetChanged();
  16. }
  17. }
  18. }
  19. // Inside ListAdapter...
  20. @Override
  21. public View getView(final int position, View convertView, ViewGroup parent) {
  22. View row = convertView;
  23. final ViewHolder holder;
  24. if (row == null) {
  25. LayoutInflater inflater = getLayoutInflater();
  26. row = inflater.inflate(R.layout.main_listview_row, parent, false);
  27. holder = new ViewHolder(row);
  28. row.setTag(holder);
  29. } else {
  30. holder = (ViewHolder) row.getTag();
  31. }
  32. final Row rowObject = getItem(position);
  33. // Look at the loadBitmap() method description...
  34. holder.mTextView.setText(rowObject.mText);
  35. mCache.loadBitmap(MainActivity.this,
  36. rowObject.mBitmapUrl, holder.mImageView,
  37. mIsScrolling);
  38. return row;
  39. }

getView()经常被调用。 如果我们没有执行检查以确保我们不会在每行中启动无限数量的线程,那么在那儿下载映像通常不是一个好主意。 Cache.java检查是否rowObject.mBitmapUrl已经是一个任务,如果是,它不会开始另一个。 因此,我们很可能不会超出AsyncTask池中的工作队列限制。

下载:

您可以从https://www.dropbox.com/s/pvr9zyl811tfeem/ListViewImageCache.zip下载源代码。


最后的话:

我已经对此进行了几周的测试,但还没有一个OOM异常。 我已经在模拟器,Nexus One和Nexus S上对此进行了测试。我已经测试了包含高清质量图像的图像URL。 唯一的瓶颈是下载时间更长。

我可以想象只有一种可能的情况,即OOM会出现,也就是说,如果我们下载许多非常大的图像,并且在将它们缩放和放入缓存之前,它们将同时占用更多内存并导致OOM。 但这毕竟不是一个理想的情况,而且很可能不可能以更可行的方式解决。

报告评论中的错误! :-)


#6楼

这对我有用。

  1. Bitmap myBitmap;
  2. BitmapFactory.Options options = new BitmapFactory.Options();
  3. options.InPurgeable = true;
  4. options.OutHeight = 50;
  5. options.OutWidth = 50;
  6. options.InSampleSize = 4;
  7. File imgFile = new File(filepath);
  8. myBitmap = BitmapFactory.DecodeFile(imgFile.AbsolutePath, options);

这是在C#monodroid上。 您可以轻松更改图像的路径。 这里重要的是要设置的选项。


#7楼

此代码将有助于从drawable加载大位图

  1. public class BitmapUtilsTask extends AsyncTask<Object, Void, Bitmap> {
  2. Context context;
  3. public BitmapUtilsTask(Context context) {
  4. this.context = context;
  5. }
  6. /**
  7. * Loads a bitmap from the specified url.
  8. *
  9. * @param url The location of the bitmap asset
  10. * @return The bitmap, or null if it could not be loaded
  11. * @throws IOException
  12. * @throws MalformedURLException
  13. */
  14. public Bitmap getBitmap() throws MalformedURLException, IOException {
  15. // Get the source image's dimensions
  16. int desiredWidth = 1000;
  17. BitmapFactory.Options options = new BitmapFactory.Options();
  18. options.inJustDecodeBounds = true;
  19. BitmapFactory.decodeResource(context.getResources(), R.drawable.green_background , options);
  20. int srcWidth = options.outWidth;
  21. int srcHeight = options.outHeight;
  22. // Only scale if the source is big enough. This code is just trying
  23. // to fit a image into a certain width.
  24. if (desiredWidth > srcWidth)
  25. desiredWidth = srcWidth;
  26. // Calculate the correct inSampleSize/scale value. This helps reduce
  27. // memory use. It should be a power of 2
  28. int inSampleSize = 1;
  29. while (srcWidth / 2 > desiredWidth) {
  30. srcWidth /= 2;
  31. srcHeight /= 2;
  32. inSampleSize *= 2;
  33. }
  34. // Decode with inSampleSize
  35. options.inJustDecodeBounds = false;
  36. options.inDither = false;
  37. options.inSampleSize = inSampleSize;
  38. options.inScaled = false;
  39. options.inPreferredConfig = Bitmap.Config.ARGB_8888;
  40. options.inPurgeable = true;
  41. Bitmap sampledSrcBitmap;
  42. sampledSrcBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.green_background , options);
  43. return sampledSrcBitmap;
  44. }
  45. /**
  46. * The system calls this to perform work in a worker thread and delivers
  47. * it the parameters given to AsyncTask.execute()
  48. */
  49. @Override
  50. protected Bitmap doInBackground(Object... item) {
  51. try {
  52. return getBitmap();
  53. } catch (MalformedURLException e) {
  54. e.printStackTrace();
  55. } catch (IOException e) {
  56. e.printStackTrace();
  57. }
  58. return null;
  59. }
  60. }

#8楼

这似乎是与社区共享我的实用程序类以加载和处理图像的合适位置,欢迎您使用和自由修改它。

  1. package com.emil;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import android.graphics.Bitmap;
  5. import android.graphics.BitmapFactory;
  6. /**
  7. * A class to load and process images of various sizes from input streams and file paths.
  8. *
  9. * @author Emil http://stackoverflow.com/users/220710/emil
  10. *
  11. */
  12. public class ImageProcessing {
  13. public static Bitmap getBitmap(InputStream stream, int sampleSize, Bitmap.Config bitmapConfig) throws IOException{
  14. BitmapFactory.Options options=ImageProcessing.getOptionsForSampling(sampleSize, bitmapConfig);
  15. Bitmap bm = BitmapFactory.decodeStream(stream,null,options);
  16. if(ImageProcessing.checkDecode(options)){
  17. return bm;
  18. }else{
  19. throw new IOException("Image decoding failed, using stream.");
  20. }
  21. }
  22. public static Bitmap getBitmap(String imgPath, int sampleSize, Bitmap.Config bitmapConfig) throws IOException{
  23. BitmapFactory.Options options=ImageProcessing.getOptionsForSampling(sampleSize, bitmapConfig);
  24. Bitmap bm = BitmapFactory.decodeFile(imgPath,options);
  25. if(ImageProcessing.checkDecode(options)){
  26. return bm;
  27. }else{
  28. throw new IOException("Image decoding failed, using file path.");
  29. }
  30. }
  31. public static Dimensions getDimensions(InputStream stream) throws IOException{
  32. BitmapFactory.Options options=ImageProcessing.getOptionsForDimensions();
  33. BitmapFactory.decodeStream(stream,null,options);
  34. if(ImageProcessing.checkDecode(options)){
  35. return new ImageProcessing.Dimensions(options.outWidth,options.outHeight);
  36. }else{
  37. throw new IOException("Image decoding failed, using stream.");
  38. }
  39. }
  40. public static Dimensions getDimensions(String imgPath) throws IOException{
  41. BitmapFactory.Options options=ImageProcessing.getOptionsForDimensions();
  42. BitmapFactory.decodeFile(imgPath,options);
  43. if(ImageProcessing.checkDecode(options)){
  44. return new ImageProcessing.Dimensions(options.outWidth,options.outHeight);
  45. }else{
  46. throw new IOException("Image decoding failed, using file path.");
  47. }
  48. }
  49. private static boolean checkDecode(BitmapFactory.Options options){
  50. // Did decode work?
  51. if( options.outWidth<0 || options.outHeight<0 ){
  52. return false;
  53. }else{
  54. return true;
  55. }
  56. }
  57. /**
  58. * Creates a Bitmap that is of the minimum dimensions necessary
  59. * @param bm
  60. * @param min
  61. * @return
  62. */
  63. public static Bitmap createMinimalBitmap(Bitmap bm, ImageProcessing.Minimize min){
  64. int newWidth, newHeight;
  65. switch(min.type){
  66. case WIDTH:
  67. if(bm.getWidth()>min.minWidth){
  68. newWidth=min.minWidth;
  69. newHeight=ImageProcessing.getScaledHeight(newWidth, bm);
  70. }else{
  71. // No resize
  72. newWidth=bm.getWidth();
  73. newHeight=bm.getHeight();
  74. }
  75. break;
  76. case HEIGHT:
  77. if(bm.getHeight()>min.minHeight){
  78. newHeight=min.minHeight;
  79. newWidth=ImageProcessing.getScaledWidth(newHeight, bm);
  80. }else{
  81. // No resize
  82. newWidth=bm.getWidth();
  83. newHeight=bm.getHeight();
  84. }
  85. break;
  86. case BOTH: // minimize to the maximum dimension
  87. case MAX:
  88. if(bm.getHeight()>bm.getWidth()){
  89. // Height needs to minimized
  90. min.minDim=min.minDim!=null ? min.minDim : min.minHeight;
  91. if(bm.getHeight()>min.minDim){
  92. newHeight=min.minDim;
  93. newWidth=ImageProcessing.getScaledWidth(newHeight, bm);
  94. }else{
  95. // No resize
  96. newWidth=bm.getWidth();
  97. newHeight=bm.getHeight();
  98. }
  99. }else{
  100. // Width needs to be minimized
  101. min.minDim=min.minDim!=null ? min.minDim : min.minWidth;
  102. if(bm.getWidth()>min.minDim){
  103. newWidth=min.minDim;
  104. newHeight=ImageProcessing.getScaledHeight(newWidth, bm);
  105. }else{
  106. // No resize
  107. newWidth=bm.getWidth();
  108. newHeight=bm.getHeight();
  109. }
  110. }
  111. break;
  112. default:
  113. // No resize
  114. newWidth=bm.getWidth();
  115. newHeight=bm.getHeight();
  116. }
  117. return Bitmap.createScaledBitmap(bm, newWidth, newHeight, true);
  118. }
  119. public static int getScaledWidth(int height, Bitmap bm){
  120. return (int)(((double)bm.getWidth()/bm.getHeight())*height);
  121. }
  122. public static int getScaledHeight(int width, Bitmap bm){
  123. return (int)(((double)bm.getHeight()/bm.getWidth())*width);
  124. }
  125. /**
  126. * Get the proper sample size to meet minimization restraints
  127. * @param dim
  128. * @param min
  129. * @param multipleOf2 for fastest processing it is recommended that the sample size be a multiple of 2
  130. * @return
  131. */
  132. public static int getSampleSize(ImageProcessing.Dimensions dim, ImageProcessing.Minimize min, boolean multipleOf2){
  133. switch(min.type){
  134. case WIDTH:
  135. return ImageProcessing.getMaxSampleSize(dim.width, min.minWidth, multipleOf2);
  136. case HEIGHT:
  137. return ImageProcessing.getMaxSampleSize(dim.height, min.minHeight, multipleOf2);
  138. case BOTH:
  139. int widthMaxSampleSize=ImageProcessing.getMaxSampleSize(dim.width, min.minWidth, multipleOf2);
  140. int heightMaxSampleSize=ImageProcessing.getMaxSampleSize(dim.height, min.minHeight, multipleOf2);
  141. // Return the smaller of the two
  142. if(widthMaxSampleSize<heightMaxSampleSize){
  143. return widthMaxSampleSize;
  144. }else{
  145. return heightMaxSampleSize;
  146. }
  147. case MAX:
  148. // Find the larger dimension and go bases on that
  149. if(dim.width>dim.height){
  150. return ImageProcessing.getMaxSampleSize(dim.width, min.minDim, multipleOf2);
  151. }else{
  152. return ImageProcessing.getMaxSampleSize(dim.height, min.minDim, multipleOf2);
  153. }
  154. }
  155. return 1;
  156. }
  157. public static int getMaxSampleSize(int dim, int min, boolean multipleOf2){
  158. int add=multipleOf2 ? 2 : 1;
  159. int size=0;
  160. while(min<(dim/(size+add))){
  161. size+=add;
  162. }
  163. size = size==0 ? 1 : size;
  164. return size;
  165. }
  166. public static class Dimensions {
  167. int width;
  168. int height;
  169. public Dimensions(int width, int height) {
  170. super();
  171. this.width = width;
  172. this.height = height;
  173. }
  174. @Override
  175. public String toString() {
  176. return width+" x "+height;
  177. }
  178. }
  179. public static class Minimize {
  180. public enum Type {
  181. WIDTH,HEIGHT,BOTH,MAX
  182. }
  183. Integer minWidth;
  184. Integer minHeight;
  185. Integer minDim;
  186. Type type;
  187. public Minimize(int min, Type type) {
  188. super();
  189. this.type = type;
  190. switch(type){
  191. case WIDTH:
  192. this.minWidth=min;
  193. break;
  194. case HEIGHT:
  195. this.minHeight=min;
  196. break;
  197. case BOTH:
  198. this.minWidth=min;
  199. this.minHeight=min;
  200. break;
  201. case MAX:
  202. this.minDim=min;
  203. break;
  204. }
  205. }
  206. public Minimize(int minWidth, int minHeight) {
  207. super();
  208. this.type=Type.BOTH;
  209. this.minWidth = minWidth;
  210. this.minHeight = minHeight;
  211. }
  212. }
  213. /**
  214. * Estimates size of Bitmap in bytes depending on dimensions and Bitmap.Config
  215. * @param width
  216. * @param height
  217. * @param config
  218. * @return
  219. */
  220. public static long estimateBitmapBytes(int width, int height, Bitmap.Config config){
  221. long pixels=width*height;
  222. switch(config){
  223. case ALPHA_8: // 1 byte per pixel
  224. return pixels;
  225. case ARGB_4444: // 2 bytes per pixel, but depreciated
  226. return pixels*2;
  227. case ARGB_8888: // 4 bytes per pixel
  228. return pixels*4;
  229. case RGB_565: // 2 bytes per pixel
  230. return pixels*2;
  231. default:
  232. return pixels;
  233. }
  234. }
  235. private static BitmapFactory.Options getOptionsForDimensions(){
  236. BitmapFactory.Options options = new BitmapFactory.Options();
  237. options.inJustDecodeBounds=true;
  238. return options;
  239. }
  240. private static BitmapFactory.Options getOptionsForSampling(int sampleSize, Bitmap.Config bitmapConfig){
  241. BitmapFactory.Options options = new BitmapFactory.Options();
  242. options.inJustDecodeBounds = false;
  243. options.inDither = false;
  244. options.inSampleSize = sampleSize;
  245. options.inScaled = false;
  246. options.inPreferredConfig = bitmapConfig;
  247. return options;
  248. }
  249. }

#9楼

通常android设备的堆大小只有16MB(根据设备/操作系统的不同,请参阅post Heap Sizes ),如果您正在加载图像并且大小超过16MB,则会抛出内存不足异常,而不是将Bitmap用于,加载来自SD卡,资源或什至来自网络的图像尝试使用getImageUri ,加载位图需要更多内存,或者如果使用该位图完成工作,则可以将位图设置为null。


#10楼

我认为避免OutOfMemoryError最佳方法是面对并理解它。

我制作了一个有意引起OutOfMemoryError应用程序 ,并监视内存使用情况。

在使用此应用程序进行了大量实验后,我得出以下结论:

我要先介绍Honey Comb之前的SDK版本。

  1. 位图存储在本机堆中,但会自动收集垃圾,因此无需调用recycle()。

  2. 如果{VM堆大小} + {已分配的本机堆内存}> = {设备的VM堆大小限制},而您尝试创建位图,则会引发OOM。

    注意:计算的是VM HEAP SIZE,而不是VM分配的内存。

  3. 即使增加了分配的VM内存,VM Heap大小也将永远不会缩小。

  4. 因此,您必须将峰值VM内存保持尽可能低,以防止VM堆大小变得太大而无法为位图节省可用内存。

  5. 手动调用System.gc()是没有意义的,系统会先尝试调用它,然后再尝试增加堆大小。

  6. 本机堆大小也永远不会缩小,但不算在OOM中,因此无需担心。

然后,让我们讨论从Honey Comb开始的SDK。

  1. 位图存储在VM堆中,本机内存不计入OOM。

  2. OOM的条件要简单得多:{VM堆大小}> = {设备的VM堆大小限制}。

  3. 因此,您拥有更多可用内存来创建具有相同堆大小限制的位图,因此不太可能引发OOM。

这是我对垃圾回收和内存泄漏的一些观察。

您可以在应用程序中自己查看。 如果活动在销毁活动后执行了仍在运行的AsyncTask,则在AsyncTask完成之前将不会收集垃圾。

这是因为AsyncTask是匿名内部类的实例,它包含Activity的引用。

如果任务在后台线程的IO操作中被阻止,则调用AsyncTask.cancel(true)不会停止执行。

回调也是匿名内部类,因此,如果项目中的静态实例将其保留且不释放它们,则内存将泄漏。

如果您安排了重复任务或延迟任务(例如Timer),并且没有在onPause()中调用cancel()和purge(),则内存将被泄漏。


#11楼

这里的答案很好,但是我想要一个完全可用的课程来解决这个问题。所以我做了一个。

这是我的BitmapHelper类 ,它是OutOfMemoryError证明的:-)

  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import android.graphics.Bitmap;
  4. import android.graphics.Bitmap.Config;
  5. import android.graphics.BitmapFactory;
  6. import android.graphics.Canvas;
  7. import android.graphics.Matrix;
  8. import android.graphics.drawable.BitmapDrawable;
  9. import android.graphics.drawable.Drawable;
  10. public class BitmapHelper
  11. {
  12. //decodes image and scales it to reduce memory consumption
  13. public static Bitmap decodeFile(File bitmapFile, int requiredWidth, int requiredHeight, boolean quickAndDirty)
  14. {
  15. try
  16. {
  17. //Decode image size
  18. BitmapFactory.Options bitmapSizeOptions = new BitmapFactory.Options();
  19. bitmapSizeOptions.inJustDecodeBounds = true;
  20. BitmapFactory.decodeStream(new FileInputStream(bitmapFile), null, bitmapSizeOptions);
  21. // load image using inSampleSize adapted to required image size
  22. BitmapFactory.Options bitmapDecodeOptions = new BitmapFactory.Options();
  23. bitmapDecodeOptions.inTempStorage = new byte[16 * 1024];
  24. bitmapDecodeOptions.inSampleSize = computeInSampleSize(bitmapSizeOptions, requiredWidth, requiredHeight, false);
  25. bitmapDecodeOptions.inPurgeable = true;
  26. bitmapDecodeOptions.inDither = !quickAndDirty;
  27. bitmapDecodeOptions.inPreferredConfig = quickAndDirty ? Bitmap.Config.RGB_565 : Bitmap.Config.ARGB_8888;
  28. Bitmap decodedBitmap = BitmapFactory.decodeStream(new FileInputStream(bitmapFile), null, bitmapDecodeOptions);
  29. // scale bitmap to mathc required size (and keep aspect ratio)
  30. float srcWidth = (float) bitmapDecodeOptions.outWidth;
  31. float srcHeight = (float) bitmapDecodeOptions.outHeight;
  32. float dstWidth = (float) requiredWidth;
  33. float dstHeight = (float) requiredHeight;
  34. float srcAspectRatio = srcWidth / srcHeight;
  35. float dstAspectRatio = dstWidth / dstHeight;
  36. // recycleDecodedBitmap is used to know if we must recycle intermediary 'decodedBitmap'
  37. // (DO NOT recycle it right away: wait for end of bitmap manipulation process to avoid
  38. // java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@416ee7d8
  39. // I do not excatly understand why, but this way it's OK
  40. boolean recycleDecodedBitmap = false;
  41. Bitmap scaledBitmap = decodedBitmap;
  42. if (srcAspectRatio < dstAspectRatio)
  43. {
  44. scaledBitmap = getScaledBitmap(decodedBitmap, (int) dstWidth, (int) (srcHeight * (dstWidth / srcWidth)));
  45. // will recycle recycleDecodedBitmap
  46. recycleDecodedBitmap = true;
  47. }
  48. else if (srcAspectRatio > dstAspectRatio)
  49. {
  50. scaledBitmap = getScaledBitmap(decodedBitmap, (int) (srcWidth * (dstHeight / srcHeight)), (int) dstHeight);
  51. recycleDecodedBitmap = true;
  52. }
  53. // crop image to match required image size
  54. int scaledBitmapWidth = scaledBitmap.getWidth();
  55. int scaledBitmapHeight = scaledBitmap.getHeight();
  56. Bitmap croppedBitmap = scaledBitmap;
  57. if (scaledBitmapWidth > requiredWidth)
  58. {
  59. int xOffset = (scaledBitmapWidth - requiredWidth) / 2;
  60. croppedBitmap = Bitmap.createBitmap(scaledBitmap, xOffset, 0, requiredWidth, requiredHeight);
  61. scaledBitmap.recycle();
  62. }
  63. else if (scaledBitmapHeight > requiredHeight)
  64. {
  65. int yOffset = (scaledBitmapHeight - requiredHeight) / 2;
  66. croppedBitmap = Bitmap.createBitmap(scaledBitmap, 0, yOffset, requiredWidth, requiredHeight);
  67. scaledBitmap.recycle();
  68. }
  69. if (recycleDecodedBitmap)
  70. {
  71. decodedBitmap.recycle();
  72. }
  73. decodedBitmap = null;
  74. scaledBitmap = null;
  75. return croppedBitmap;
  76. }
  77. catch (Exception ex)
  78. {
  79. ex.printStackTrace();
  80. }
  81. return null;
  82. }
  83. /**
  84. * compute powerOf2 or exact scale to be used as {@link BitmapFactory.Options#inSampleSize} value (for subSampling)
  85. *
  86. * @param requiredWidth
  87. * @param requiredHeight
  88. * @param powerOf2
  89. * weither we want a power of 2 sclae or not
  90. * @return
  91. */
  92. public static int computeInSampleSize(BitmapFactory.Options options, int dstWidth, int dstHeight, boolean powerOf2)
  93. {
  94. int inSampleSize = 1;
  95. // Raw height and width of image
  96. final int srcHeight = options.outHeight;
  97. final int srcWidth = options.outWidth;
  98. if (powerOf2)
  99. {
  100. //Find the correct scale value. It should be the power of 2.
  101. int tmpWidth = srcWidth, tmpHeight = srcHeight;
  102. while (true)
  103. {
  104. if (tmpWidth / 2 < dstWidth || tmpHeight / 2 < dstHeight)
  105. break;
  106. tmpWidth /= 2;
  107. tmpHeight /= 2;
  108. inSampleSize *= 2;
  109. }
  110. }
  111. else
  112. {
  113. // Calculate ratios of height and width to requested height and width
  114. final int heightRatio = Math.round((float) srcHeight / (float) dstHeight);
  115. final int widthRatio = Math.round((float) srcWidth / (float) dstWidth);
  116. // Choose the smallest ratio as inSampleSize value, this will guarantee
  117. // a final image with both dimensions larger than or equal to the
  118. // requested height and width.
  119. inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
  120. }
  121. return inSampleSize;
  122. }
  123. public static Bitmap drawableToBitmap(Drawable drawable)
  124. {
  125. if (drawable instanceof BitmapDrawable)
  126. {
  127. return ((BitmapDrawable) drawable).getBitmap();
  128. }
  129. Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
  130. Canvas canvas = new Canvas(bitmap);
  131. drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
  132. drawable.draw(canvas);
  133. return bitmap;
  134. }
  135. public static Bitmap getScaledBitmap(Bitmap bitmap, int newWidth, int newHeight)
  136. {
  137. int width = bitmap.getWidth();
  138. int height = bitmap.getHeight();
  139. float scaleWidth = ((float) newWidth) / width;
  140. float scaleHeight = ((float) newHeight) / height;
  141. // CREATE A MATRIX FOR THE MANIPULATION
  142. Matrix matrix = new Matrix();
  143. // RESIZE THE BIT MAP
  144. matrix.postScale(scaleWidth, scaleHeight);
  145. // RECREATE THE NEW BITMAP
  146. Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false);
  147. return resizedBitmap;
  148. }
  149. }

#12楼

在我的一个应用程序中,我需要从Camera/Gallery 。 如果用户单击“摄像机”中的图像(可能是2MP,5MP或8MP),则图像大小从kB s到MB s不等。 如果图像大小小于(或高达1-2MB)以上代码工作正常,但如果我的图像大小大于4MB或5MB,则OOM进入框架:(

然后我努力解决了这个问题,最后我对Fedor做了以下改进(感谢Fedor做出了如此出色的解决方案)代码:)

  1. private Bitmap decodeFile(String fPath) {
  2. // Decode image size
  3. BitmapFactory.Options opts = new BitmapFactory.Options();
  4. /*
  5. * If set to true, the decoder will return null (no bitmap), but the
  6. * out... fields will still be set, allowing the caller to query the
  7. * bitmap without having to allocate the memory for its pixels.
  8. */
  9. opts.inJustDecodeBounds = true;
  10. opts.inDither = false; // Disable Dithering mode
  11. opts.inPurgeable = true; // Tell to gc that whether it needs free
  12. // memory, the Bitmap can be cleared
  13. opts.inInputShareable = true; // Which kind of reference will be used to
  14. // recover the Bitmap data after being
  15. // clear, when it will be used in the
  16. // future
  17. BitmapFactory.decodeFile(fPath, opts);
  18. // The new size we want to scale to
  19. final int REQUIRED_SIZE = 70;
  20. // Find the correct scale value.
  21. int scale = 1;
  22. if (opts.outHeight > REQUIRED_SIZE || opts.outWidth > REQUIRED_SIZE) {
  23. // Calculate ratios of height and width to requested height and width
  24. final int heightRatio = Math.round((float) opts.outHeight
  25. / (float) REQUIRED_SIZE);
  26. final int widthRatio = Math.round((float) opts.outWidth
  27. / (float) REQUIRED_SIZE);
  28. // Choose the smallest ratio as inSampleSize value, this will guarantee
  29. // a final image with both dimensions larger than or equal to the
  30. // requested height and width.
  31. scale = heightRatio < widthRatio ? heightRatio : widthRatio;//
  32. }
  33. // Decode bitmap with inSampleSize set
  34. opts.inJustDecodeBounds = false;
  35. opts.inSampleSize = scale;
  36. Bitmap bm = BitmapFactory.decodeFile(fPath, opts).copy(
  37. Bitmap.Config.RGB_565, false);
  38. return bm;
  39. }

我希望这将有助于哥们面临同样的问题!

有关更多信息,请参阅


#13楼

我的2分钱:我使用以下位图解决了OOM错误:

a)将我的图像缩放2倍

b)在我的自定义适配器中将Picasso库用于ListView,并在getView中进行如下调用: Picasso.with(context).load(R.id.myImage).into(R.id.myImageView);


#14楼

这里的所有解决方案都需要设置IMAGE_MAX_SIZE。 这限制了设备使用更强大的硬件,如果图像尺寸太小,则在高清屏幕上看起来很难看。

我提出了一种可与我的Samsung Galaxy S3和其他几款设备(包括功能较弱的设备)配合使用的解决方案,当使用功能更强大的设备时,图像质量会更高。

要点是要计算为特定设备上的应用程序分配的最大内存,然后将比例设置为尽可能小,而不会超出此内存。 这是代码:

  1. public static Bitmap decodeFile(File f)
  2. {
  3. Bitmap b = null;
  4. try
  5. {
  6. // Decode image size
  7. BitmapFactory.Options o = new BitmapFactory.Options();
  8. o.inJustDecodeBounds = true;
  9. FileInputStream fis = new FileInputStream(f);
  10. try
  11. {
  12. BitmapFactory.decodeStream(fis, null, o);
  13. }
  14. finally
  15. {
  16. fis.close();
  17. }
  18. // In Samsung Galaxy S3, typically max memory is 64mb
  19. // Camera max resolution is 3264 x 2448, times 4 to get Bitmap memory of 30.5mb for one bitmap
  20. // If we use scale of 2, resolution will be halved, 1632 x 1224 and x 4 to get Bitmap memory of 7.62mb
  21. // We try use 25% memory which equals to 16mb maximum for one bitmap
  22. long maxMemory = Runtime.getRuntime().maxMemory();
  23. int maxMemoryForImage = (int) (maxMemory / 100 * 25);
  24. // Refer to
  25. // http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
  26. // A full screen GridView filled with images on a device with
  27. // 800x480 resolution would use around 1.5MB (800*480*4 bytes)
  28. // When bitmap option's inSampleSize doubled, pixel height and
  29. // weight both reduce in half
  30. int scale = 1;
  31. while ((o.outWidth / scale) * (o.outHeight / scale) * 4 > maxMemoryForImage)
  32. scale *= 2;
  33. // Decode with inSampleSize
  34. BitmapFactory.Options o2 = new BitmapFactory.Options();
  35. o2.inSampleSize = scale;
  36. fis = new FileInputStream(f);
  37. try
  38. {
  39. b = BitmapFactory.decodeStream(fis, null, o2);
  40. }
  41. finally
  42. {
  43. fis.close();
  44. }
  45. }
  46. catch (IOException e)
  47. {
  48. }
  49. return b;
  50. }

我将此位图使用的最大内存设置为最大分配内存的25%,您可能需要根据自己的需要进行调整,并确保该位图已清理完毕并且在使用完后不留在内存中。 通常,我使用此代码执行图像旋转(源位图和目标位图),因此我的应用程序需要同时在内存中加载2个位图,而25%的位图为我提供了良好的缓冲区,并且在执行图像旋转时不会耗尽内存。

希望这可以帮助某人。


#15楼

对于从SdCard中选择的每个图像或可绘制的位图对象,请使用这些代码。

  1. Resources res = getResources();
  2. WindowManager window = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
  3. Display display = window.getDefaultDisplay();
  4. @SuppressWarnings("deprecation")
  5. int width = display.getWidth();
  6. @SuppressWarnings("deprecation")
  7. int height = display.getHeight();
  8. try {
  9. if (bitmap != null) {
  10. bitmap.recycle();
  11. bitmap = null;
  12. System.gc();
  13. }
  14. bitmap = Bitmap.createScaledBitmap(BitmapFactory
  15. .decodeFile(ImageData_Path.get(img_pos).getPath()),
  16. width, height, true);
  17. } catch (OutOfMemoryError e) {
  18. if (bitmap != null) {
  19. bitmap.recycle();
  20. bitmap = null;
  21. System.gc();
  22. }
  23. BitmapFactory.Options options = new BitmapFactory.Options();
  24. options.inPreferredConfig = Config.RGB_565;
  25. options.inSampleSize = 1;
  26. options.inPurgeable = true;
  27. bitmapBitmap.createScaledBitmap(BitmapFactory.decodeFile(ImageData_Path.get(img_pos)
  28. .getPath().toString(), options), width, height,true);
  29. }
  30. return bitmap;

使用ImageData_Path.get(img_pos).getPath()的图像路径。


#16楼

不幸的是,如果上述方法均无效,则将其添加到清单文件中。 内部应用标签

  1. <application
  2. android:largeHeap="true"

#17楼

我对Fedor的代码做了一些小的改进。 它基本上具有相同的功能,但是没有(在我看来)丑陋的while循环,并且总是产生2的幂。 感谢Fedor提出了原始解决方案,直到发现他的存在,我才被困住了,然后我得以做出这个:)

  1. private Bitmap decodeFile(File f){
  2. Bitmap b = null;
  3. //Decode image size
  4. BitmapFactory.Options o = new BitmapFactory.Options();
  5. o.inJustDecodeBounds = true;
  6. FileInputStream fis = new FileInputStream(f);
  7. BitmapFactory.decodeStream(fis, null, o);
  8. fis.close();
  9. int scale = 1;
  10. if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
  11. scale = (int)Math.pow(2, (int) Math.ceil(Math.log(IMAGE_MAX_SIZE /
  12. (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
  13. }
  14. //Decode with inSampleSize
  15. BitmapFactory.Options o2 = new BitmapFactory.Options();
  16. o2.inSampleSize = scale;
  17. fis = new FileInputStream(f);
  18. b = BitmapFactory.decodeStream(fis, null, o2);
  19. fis.close();
  20. return b;
  21. }

#18楼

使用此bitmap.recycle(); 这可以帮助您解决任何图像质量问题。


#19楼

我有一个更有效的解决方案,不需要进行任何缩放。 只需将您的位图解码一次,然后针对其名称将其缓存在映射中。 然后只需根据名称检索位图,然后在ImageView中进行设置。 没有什么需要做的了。

这将起作用,因为已解码位图的实际二进制数据未存储在dalvik VM堆中。 它存储在外部。 因此,每次解码位图时,它都会在VM堆之外分配内存,而该内存不会被GC回收

为了帮助您更好地理解这一点,假设您已将ur图像保存在drawable文件夹中。 您只需通过执行getResources()。getDrwable(R.drawable。)来获取图像。 这不会每次都解码图像,而是每次调用它时都重新使用已经解码的实例。 因此,从本质上讲,它是缓存的。

现在,由于您的图像位于某个位置的文件中(甚至可能来自外部服务器),因此您有责任缓存已解码的位图实例,以便在需要的任何地方重复使用。

希望这可以帮助。


#20楼

我做了以下工作来拍摄图像并即时调整其大小。 希望这可以帮助

  1. Bitmap bm;
  2. bm = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(filepath), 100, 100, true);
  3. mPicture = new ImageView(context);
  4. mPicture.setImageBitmap(bm);

#21楼

这里有两个问题。

  • 位图内存不在VM堆中,而是在本机堆中-请参阅BitmapFactory OOM使我发疯
  • 本机堆的垃圾收集比VM堆慢-因此,每次执行Activity的onPause或onDestroy时,您都必须非常积极地进行bitmap.recycle和bitmap = null

#22楼

似乎这是一个长期运行的问题,有许多不同的解释。 我在这里提出了两个最常见的答案,但是这些都没有解决我关于VM的问题,声称VM无法承受执行该过程的解码部分所需的字节数。 经过一番挖掘后,我了解到真正的问题是解码过程不占用NATIVE堆。

看到这里: BitmapFactory OOM让我发疯

这导致我进入另一个讨论线程,在那里我找到了解决该问题的更多解决方案。 一种是调用System.gc(); 在显示图像后手动进行。 但这实际上使您的应用程序使用更多的内存,以减少本机堆。 从2.0版(甜甜圈)开始,更好的解决方案是使用BitmapFactory选项“ inPurgeable”。 所以我只是添加了o2.inPurgeable=true; 就在o2.inSampleSize=scale;

有关该主题的更多信息: 内存堆的限制是否仅为6M?

现在,说了这么多,我对Java和Android也是一个完全的傻瓜。 因此,如果您认为这是解决此问题的可怕方法,那么您可能是对的。 ;-)但这对我来说是个奇迹,我发现现在无法在堆缓存中运行VM。 我可以发现的唯一缺点是,您正在丢弃缓存的绘制图像。 这意味着,如果您向右返回该图像,则每次都将重新绘制它。 就我的应用程序如何工作而言,这并不是真正的问题。 你的旅费可能会改变。


#23楼

这是一个已知的错误 ,不是因为文件很大。 由于Android会缓存Drawable,因此使用少量图像后,内存就会耗尽。 但是我通过跳过android默认的缓存系统找到了另一种方法。

解决方案 :将图像移到“资产”文件夹,然后使用以下函数获取BitmapDrawable:

  1. public static Drawable getAssetImage(Context context, String filename) throws IOException {
  2. AssetManager assets = context.getResources().getAssets();
  3. InputStream buffer = new BufferedInputStream((assets.open("drawable/" + filename + ".png")));
  4. Bitmap bitmap = BitmapFactory.decodeStream(buffer);
  5. return new BitmapDrawable(context.getResources(), bitmap);
  6. }

#24楼

我已经通过以下方式解决了相同的问题。

  1. Bitmap b = null;
  2. Drawable d;
  3. ImageView i = new ImageView(mContext);
  4. try {
  5. b = Bitmap.createBitmap(320,424,Bitmap.Config.RGB_565);
  6. b.eraseColor(0xFFFFFFFF);
  7. Rect r = new Rect(0, 0,320 , 424);
  8. Canvas c = new Canvas(b);
  9. Paint p = new Paint();
  10. p.setColor(0xFFC0C0C0);
  11. c.drawRect(r, p);
  12. d = mContext.getResources().getDrawable(mImageIds[position]);
  13. d.setBounds(r);
  14. d.draw(c);
  15. /*
  16. BitmapFactory.Options o2 = new BitmapFactory.Options();
  17. o2.inTempStorage = new byte[128*1024];
  18. b = BitmapFactory.decodeStream(mContext.getResources().openRawResource(mImageIds[position]), null, o2);
  19. o2.inSampleSize=16;
  20. o2.inPurgeable = true;
  21. */
  22. } catch (Exception e) {
  23. }
  24. i.setImageBitmap(b);

#25楼

我遇到了同样的问题,并通过避免使用BitmapFactory.decodeStream或encodeFile函数来解决它,而是使用了BitmapFactory.decodeFileDescriptor

decodeFileDescriptor看起来好像调用了与ADCStream / decodeFile不同的本机方法。

无论如何,这是行得通的(请注意,我添加了一些上述选项,但这并没有什么不同。关键是对BitmapFactory.decodeFileDescriptor的调用,而不是defineStreamencodeFile的调用 ):

  1. private void showImage(String path) {
  2. Log.i("showImage","loading:"+path);
  3. BitmapFactory.Options bfOptions=new BitmapFactory.Options();
  4. bfOptions.inDither=false; //Disable Dithering mode
  5. bfOptions.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared
  6. bfOptions.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
  7. bfOptions.inTempStorage=new byte[32 * 1024];
  8. File file=new File(path);
  9. FileInputStream fs=null;
  10. try {
  11. fs = new FileInputStream(file);
  12. } catch (FileNotFoundException e) {
  13. //TODO do something intelligent
  14. e.printStackTrace();
  15. }
  16. try {
  17. if(fs!=null) bm=BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
  18. } catch (IOException e) {
  19. //TODO do something intelligent
  20. e.printStackTrace();
  21. } finally{
  22. if(fs!=null) {
  23. try {
  24. fs.close();
  25. } catch (IOException e) {
  26. // TODO Auto-generated catch block
  27. e.printStackTrace();
  28. }
  29. }
  30. }
  31. //bm=BitmapFactory.decodeFile(path, bfOptions); This one causes error: java.lang.OutOfMemoryError: bitmap size exceeds VM budget
  32. im.setImageBitmap(bm);
  33. //bm.recycle();
  34. bm=null;
  35. }

我认为在解码流/解码文件中使用的本机函数存在问题。 我已经确认,使用解码文件描述符时会调用其他本机方法。 我还读到的是“图像(位图)不是通过标准Java方式分配的,而是通过本机调用分配的;分配是在虚拟堆之外完成的,但要对它进行计数!


#26楼

要修复OutOfMemory错误,您应该执行以下操作:

  1. BitmapFactory.Options options = new BitmapFactory.Options();
  2. options.inSampleSize = 8;
  3. Bitmap preview_bitmap = BitmapFactory.decodeStream(is, null, options);

inSampleSize选项可减少内存消耗。

这是一个完整的方法。 首先,它读取图像大小而不解码内容本身。 然后,它找到最佳的inSampleSize值,应为2的幂,最后对图像进行解码。

  1. // Decodes image and scales it to reduce memory consumption
  2. private Bitmap decodeFile(File f) {
  3. try {
  4. // Decode image size
  5. BitmapFactory.Options o = new BitmapFactory.Options();
  6. o.inJustDecodeBounds = true;
  7. BitmapFactory.decodeStream(new FileInputStream(f), null, o);
  8. // The new size we want to scale to
  9. final int REQUIRED_SIZE=70;
  10. // Find the correct scale value. It should be the power of 2.
  11. int scale = 1;
  12. while(o.outWidth / scale / 2 >= REQUIRED_SIZE &&
  13. o.outHeight / scale / 2 >= REQUIRED_SIZE) {
  14. scale *= 2;
  15. }
  16. // Decode with inSampleSize
  17. BitmapFactory.Options o2 = new BitmapFactory.Options();
  18. o2.inSampleSize = scale;
  19. return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
  20. } catch (FileNotFoundException e) {}
  21. return null;
  22. }

#27楼

上面的答案都对我没有用,但是我确实提出了一个可怕的丑陋变通办法来解决问题。 我在项目中添加了一个很小的1x1像素图像作为资源,并在调用垃圾回收之前将其加载到ImageView中。 我认为可能是ImageView没有释放位图,所以GC从未选择它。 这很丑陋,但现在似乎可以使用。

  1. if (bitmap != null)
  2. {
  3. bitmap.recycle();
  4. bitmap = null;
  5. }
  6. if (imageView != null)
  7. {
  8. imageView.setImageResource(R.drawable.tiny); // This is my 1x1 png.
  9. }
  10. System.gc();
  11. imageView.setImageBitmap(...); // Do whatever you need to do to load the image you want.

#28楼

我来自iOS经验,对于发现诸如加载和显示图像这样的基本问题感到沮丧,我感到很沮丧。 毕竟,遇到此问题的每个人都在尝试显示合理大小的图像。 无论如何,这是修复我的问题的两个更改(并使我的应用程序响应速度很快)。

1)每次执行BitmapFactory.decodeXYZ() ,请确保传入inPurgeable设置为trueBitmapFactory.Options (最好将inInputShareable设置为true )。

2)永远不要使用Bitmap.createBitmap(width, height, Config.ARGB_8888) 。 我的意思是永远! 经过数次传递之后,我再也没有出现过这样的事情不会引起内存错误的情况。 无论如何,都没有多少recycle()System.gc() 。 它总是引发异常。 实际工作的另一种方法是在可绘制对象(或使用上面的步骤1解码的另一个位图)中有一个虚拟图像,将其缩放到所需的大小,然后操作生成的位图(例如将其传递到Canvas)以获取更多乐趣)。 因此,您应该使用的是: Bitmap.createScaledBitmap(srcBitmap, width, height, false) 。 如果出于某种原因必须使用蛮力创建方法,则至少传递Config.ARGB_4444

几乎可以保证,即使没有几天,您也可以节省几个小时。 关于缩放图像等的所有讨论都无法真正实现(除非您考虑使用错误的尺寸或降级的图像作为解决方案)。


#29楼

我只是在几分钟前遇到了这个问题。 我通过在管理Listview适配器方面做得更好而解决了它。 我以为使用的数百个50x50px图像是个问题,事实证明,每次显示该行时,我都试图为自己的自定义视图充气。 只需通过测试以查看行是否已膨胀,就可以消除此错误,并且我正在使用数百个位图。 这实际上是一个Spinner,但是基本适配器对ListView的工作都相同。 这个简单的修复程序也极大地提高了适配器的性能。

  1. @Override
  2. public View getView(final int position, View convertView, final ViewGroup parent) {
  3. if(convertView == null){
  4. LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  5. convertView = inflater.inflate(R.layout.spinner_row, null);
  6. }
  7. ...

#30楼

我整天都在测试这些解决方案,而对我来说唯一有效的方法就是上述获取图像并手动调用GC的方法,我知道这不是必需的,但这是唯一有效的方法当我将我的应用置于重负载测试下时,在活动之间进行切换。 我的应用在的列表视图中有一个缩略图列表(让我们说活动A),当您单击其中一个图像时,它会带您到另一个活动(让我们说活动B),该活动显示该项目的主图像。 当我在两个活动之间来回切换时,最终会出现OOM错误,并且该应用程序将强制关闭。

当我到达列表视图的一半时,它将崩溃。

现在,当我在活动B中实现以下内容时,我可以毫无问题地遍历整个列表视图,并且不断前进……而且速度很快。

  1. @Override
  2. public void onDestroy()
  3. {
  4. Cleanup();
  5. super.onDestroy();
  6. }
  7. private void Cleanup()
  8. {
  9. bitmap.recycle();
  10. System.gc();
  11. Runtime.getRuntime().gc();
  12. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/198736
推荐阅读
相关标签
  

闽ICP备14008679号