gpt4 book ai didi

java - Android从服务器下载图像并保存到sdcard而不使用BitmapFactory

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:17:36 25 4
gpt4 key购买 nike

我正在尝试创建一个用于从服务器下载图像并将其显示到 ListView 中的应用程序。我造成的问题是内存泄漏并使我的应用程序崩溃。我在 Android 博客中搜索这样的 link ,它显示了一个好主意,但它仍然不足以用多线程来完成。 android的一些设备可以使用它,但有些设备只能在单线程中处理,有时根本无法工作。

我的应用程序有很多 Activity ,每个 Activity 都有一个 ListView ,需要尽可能快地显示图像。通过 Google IO 2012,他们使用缓冲区将原始图像保存到 SD 卡,它解决了内存泄漏问题,但由于需要下载的图像太大,加载速度很慢。

我的问题是:有没有什么方法可以在将图像写入 SD 卡的同时缩放图像?我发现一些可能的解决方案是在输入流对象中使用 Skip byte,并且我能够找到我需要下载的图像的每像素宽度和高度。

以下代码在 Google IO 2012 中使用,它适用于多线程,在我的例子中,我有 4 个线程在后台运行。

private void downloadAndWriteFile(final String url, final File file) throws OutOfMemoryError {
BufferedOutputStream out = null;

try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setDoInput(true);
conn.connect();

final InputStream in = new BufferedInputStream(conn.getInputStream(), IO_BUFFER_SIZE_BYTES); // buffer size 1KB
out = new BufferedOutputStream(new FileOutputStream(file), IO_BUFFER_SIZE_BYTES);

int b;
while ((b = in.read()) != -1) {
out.write(b);
}
out.close();
conn.disconnect();
}
catch (Exception e) {
Log.e(TAG, "!!downloadAndWriteFile " + e.getMessage());
file.delete();
}
}

最佳答案

1) 在设置图像之前使用以下代码释放与此位图关联的 native 对象,并清除对像素数据的引用。如果没有其他引用,它只是允许对其进行垃圾回收。

BitmapDrawable drawable = (BitmapDrawable) myImage.getDrawable();
Bitmap bitmap = drawable.getBitmap();
if (bitmap != null)
{
bitmap.recycle();
}

2) 使用此方法减小位图在内存中的大小:

/**
* decodes image and scales it to reduce memory consumption
*
* @param file
* @param requiredSize
* @return
*/
public static Bitmap decodeFile(File file, int requiredSize) {
try {

// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(file), null, o);

// The new size we want to scale to

// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < requiredSize
|| height_tmp / 2 < requiredSize)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}

// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;

Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(file),
null, o2);

return bmp;

} catch (FileNotFoundException e) {
} finally {
System.gc();
}
return null;
}

关于java - Android从服务器下载图像并保存到sdcard而不使用BitmapFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12329136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com