如何解决将图像 url 转换为 android 中的位图时的 java.lang.OutOfMemoryError 异常?
How to resolve java.lang.OutOfMemoryError exception when converting image url to bitmap in android?
这是我为将图像从 url 获取到位图而编写的方法,每当我使用 Handler
[=17= 向下滚动主视图时,我都会将其设为 运行 ]
public void setimage(final ImageView imageview, final String urll,final int postion)
{
new Thread(new Runnable()
{
@Override
public void run()
{
URL url = null;
try {
url = new URL(urll);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
final Bitmap myBitmap = BitmapFactory.decodeStream(input);
handler.post(new Runnable()
{
@Override
public void run() {
imageview.setImageBitmap(Bitmap.createScaledBitmap(myBitmap, 160, 140, true));
}
});
web.get(postion).setImage(myBitmap);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}).start();
}
这是我在 logcat
中向下滚动以查看更多图像时在自定义适配器中遇到的异常
java.lang.OutOfMemoryError
android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
请告诉我哪里做错了
您可以使用
请求使用更多
android:largeHeap="true"
在清单中。
参考:How to solve java.lang.OutOfMemoryError trouble in Android
当你设置位图之前放这行
System.gc();
您可以使用 decodeStream 的重载,它在第三个参数中接受 BitmapOptions 来缩小尺寸和图像质量。
看看this
希望对您有所帮助。
两个答案都不太好。大堆可能意味着任何事情。在某些设备上它会正常,在某些设备上则不会。 Android 没有提供任何关于这个堆有多大的信息。如果你的位图真的很大,你不应该把它下载到 ram 内存,而是下载到闪存(一些文件)。而不是立即阅读它按比例缩小。在这种方法中,您还有一个免费的缓存实现:)
请查看这篇文章http://developer.android.com/training/displaying-bitmaps/index.html
这是我为将图像从 url 获取到位图而编写的方法,每当我使用 Handler
[=17= 向下滚动主视图时,我都会将其设为 运行 ]
public void setimage(final ImageView imageview, final String urll,final int postion)
{
new Thread(new Runnable()
{
@Override
public void run()
{
URL url = null;
try {
url = new URL(urll);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
final Bitmap myBitmap = BitmapFactory.decodeStream(input);
handler.post(new Runnable()
{
@Override
public void run() {
imageview.setImageBitmap(Bitmap.createScaledBitmap(myBitmap, 160, 140, true));
}
});
web.get(postion).setImage(myBitmap);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}).start();
}
这是我在 logcat
java.lang.OutOfMemoryError android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
请告诉我哪里做错了
您可以使用
请求使用更多android:largeHeap="true"
在清单中。
参考:How to solve java.lang.OutOfMemoryError trouble in Android
当你设置位图之前放这行
System.gc();
您可以使用 decodeStream 的重载,它在第三个参数中接受 BitmapOptions 来缩小尺寸和图像质量。
看看this
希望对您有所帮助。
两个答案都不太好。大堆可能意味着任何事情。在某些设备上它会正常,在某些设备上则不会。 Android 没有提供任何关于这个堆有多大的信息。如果你的位图真的很大,你不应该把它下载到 ram 内存,而是下载到闪存(一些文件)。而不是立即阅读它按比例缩小。在这种方法中,您还有一个免费的缓存实现:)
请查看这篇文章http://developer.android.com/training/displaying-bitmaps/index.html