java - 图像从 SD 卡加载

标签 java android

我从我的服务器下载了大约 100 张图片,以便在 listView 中显示它们,

因此我将它们保存在我的SD卡中,这样我就不会收到OutOfMemoryException。

但是,我发现即使我将它们下载到 SD 卡,我也必须将它们解码为位图,这会占用大量内存然后显示它们,因此我也会收到“OutOfMemory”异常。

有什么办法可以解决吗?

非常感谢

这是我从 SD 卡加载图像的代码:

Bitmap bmImg = BitmapFactory.decodeFile("path of img1");
imageView.setImageBitmap(bmImg);

最佳答案

尝试使用此代码从文件加载图像:

 img.setImageBitmap(decodeSampledBitmapFromFile(imagePath, 1000, 700));

decodeSampledBitmapFromFile时:

public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) 
{ // BEST QUALITY MATCH

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);

    // Calculate inSampleSize
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        int inSampleSize = 1;

        if (height > reqHeight) {
            inSampleSize = Math.round((float)height / (float)reqHeight);
        }

        int expectedWidth = width / inSampleSize;

        if (expectedWidth > reqWidth) {
            //if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
            inSampleSize = Math.round((float)width / (float)reqWidth);
        }
    options.inSampleSize = inSampleSize;

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    return BitmapFactory.decodeFile(path, options);
  }

您可以使用数字(本例中为 1000、700)来配置图像文件的输出质量。

关于java - 图像从 SD 卡加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15913502/

相关文章:

java - SpringBoot - UnsatisfiedDependencyException Spring Boot 不是扩展 CrudRepository 的 Autowiring Repository 接口(interface)

Android风格指定按钮颜色

java - 在依赖于 Android 插件的自定义 Gradle 插件的单元测试中模拟应用程序变体

java - 支持MapFragment和NullPointerException

java - Google App Engine 错误 503 - 服务不可用

java - 能找到符号变量Base64是什么原因?

android - "Error Parsing XML: XML declaration not well-formed"[安卓]

java - 当我尝试更新 onPostExecute(...) 方法中的字段时,Android 应用程序崩溃

java - 如何获取 PropertyPlaceHolderConfigurer 中所有属性的列表?

java - "setDataSource failed"异常