3

我从 Internet 下载照片,然后将其保存在 Bitmap 变量中。

我试图修复它导致的崩溃(它是一个内存问题)。

这就是他们在这里建议的代码:Loading Bitmaps

但是他们只谈论来自资源的图像,所以我卡住了..

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight) {

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

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

我可以以某种方式转换它以使其与下载的位图一起使用吗?

4

3 回答 3

3

您可以使用它BitmapFactory.decodeStream(inputStream, null, options);从 inputStream 解码。但是,它只能运行一次,因为inputStream只能使用一次。因此,您不能真正inSampleSize通过调用decodeStream两次来计算 。如果您知道要下载的图像的大小,请尝试对inSampleSize.

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 2; \\ hard code it to whatever is reasonable
    return BitmapFactory.decodeStream(inputStream, null, options);
于 2013-11-06T00:55:35.980 回答
1

是的,您可以解码位图。我建议您动态计算 inSampleSize。

public static Bitmap decodeSampledBitmapFromResource(Context context, Uri uri,
                                                     int reqWidth, int reqHeight) 
                                                   throws FileNotFoundException {
    ContentResolver contentResolver = context.getContentResolver();
    InputStream inputStream = contentResolver.openInputStream(uri);
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(inputStream, null, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    inputStream = contentResolver.openInputStream(uri);
    return BitmapFactory.decodeStream(inputStream, null, options);
}
于 2015-01-08T15:04:15.863 回答
1

有一种方法可以从 InputStream 计算 inSampleSize :关键是我们应该缓存从 inputStream 读取的数据

InputStream in = conn.getInputStream();
byte[] data = Utils.streamToBytes(in);
BitmapFactory.Options option = new BitmapFactory.Options();
option.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(data, 0, data.length, option);
option.inSampleSize = Utils.getBitmapSampleSize(option.outWidth, reqWidth);
option.inJustDecodeBounds = false;
return BitmapFactory.decodeByteArray(data, 0, data.length, option);

Utils.streamToBytes:

 byte[] buffer = new byte[1024];
 ByteArrayOutputStream output = new ByteArrayOutputStream();
 int len = 0;
 while((len = in.read(buffer)) != -1) {
        output.write(buffer, 0, len);
 }
 output.close();
 in.close();
 return output.toByteArray();
于 2015-02-05T09:19:02.653 回答