BitmapFactory.decodeStream(..)总是返回null作为Bitmap



我想在后台线程中从Url加载位图。我的方法如下所示:

public Bitmap decodeSampledBitmapFromURL(String url,int reqWidth, int reqHeight) {
        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        InputStream is=null;
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Rect rect = new Rect(-1, -1, -1, -1);
        Bitmap bmp1 = BitmapFactory.decodeStream(is,rect, options);
        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        Bitmap bmp2 = BitmapFactory.decodeStream(is,rect, options);
        return bmp2;
    }

我总是得到bmp1和bmp2为空。为什么?

可以检查输入流是否为空,以查看是否有错误的位图代码或获取输入流代码。也许矩形应该有合适的尺寸?

您正在解码带有解码边界选项的流,因此显然位图输出将为空,然后您正在尝试解码来自同一流的位图,该流已在第一次解码中使用。您可以尝试将流读入字节数组缓冲区,然后包装bytearrayInputstreams,记住为每个解码创建新的流

最新更新