6

画像のパスからビットマップ画像を取得しようとしました。しかし、値をBitmapFactory.decodeStream返しnullます。

コード:

URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
connection.disconnect();
input.close();

もっと多くのサイトを検索しましたが、それでも解決策が得られませんでした。

4

5 に答える 5

15

解決策を得ました:

HttpGet httpRequest = new HttpGet(URI.create(path) );
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
bmp = BitmapFactory.decodeStream(bufHttpEntity.getContent());
httpRequest.abort();

問題は、一度InputStreamfromHttpUrlConnectionを使用すると、巻き戻して同じものを再度使用することができないことでしInputStreamた。InputStreamしたがって、画像の実際のサンプリング用に新しいを作成する必要があります。HTTPそれ以外の場合は、リクエストを中止する必要があります。

于 2012-05-18T12:19:31.873 に答える
1

私は同じ問題を抱えていましたが、私の場合、問題はリソース(画像)でした。Android は CMYK 画像をサポートしていないため、画像が CMYK カラー モードでないことを確認してください。詳細については、この質問を参照してください

幸運を ;)

于 2014-01-15T19:06:25.283 に答える
1
public Bitmap getBitmapFromUrl(String url)
{
Bitmap bm = null;
InputStream is = null;
BufferedInputStream bis = null;
try 
{
    URLConnection conn = new URL(url).openConnection();
    conn.connect();
    is = conn.getInputStream();
    bis = new BufferedInputStream(is, 8192);
    bm = BitmapFactory.decodeStream(bis);
}
catch (Exception e) 
{
    e.printStackTrace();
}
finally {
    if (bis != null) 
    {
        try 
        {
            bis.close();
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
    if (is != null) 
    {
        try 
        {
            is.close();
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
}
return bm;
}

これをスレッド内で呼び出すことを忘れないでください(メインスレッドではありません)

于 2012-05-18T10:36:33.043 に答える
0

次のコードを使用して、URLから画像をダウンロードできます。

String IMAGE_URL = "http://www.kolkatabirds.com/rainquail8vt.jpg";
            //where we want to download it from
            URL url;
            try {
                url = new URL(IMAGE_URL);

                //open the connection
                URLConnection ucon = url.openConnection();

                //buffer the download
                InputStream is = ucon.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is,1024);

                //get the bytes one by one
                int current = 0;

                while ((current = bis.read()) != -1) {
                    baf.append((byte) current);
                }
                //convert it back to an image
                ByteArrayInputStream imageStream = new ByteArrayInputStream(baf.toByteArray());
                Bitmap theImage = BitmapFactory.decodeStream(imageStream);
                img.setImageBitmap(theImage);
于 2012-05-18T10:14:17.283 に答える