3

インターネットから写真をダウンロードして、ビットマップ変数に保存します。

それが引き起こすクラッシュを修正しようとしています(メモリの問題です)。

それは彼らがここで提案するコードです: 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

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 に答える