我试图从图像路径中获取位图图像。但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();
我在更多网站上搜索过,但仍然没有得到解决方案。
答案 0 :(得分:14)
获得解决方案:
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();
问题是,一旦您使用InputStream
中的HttpUrlConnection
,就无法再次回放并再次使用相同的InputStream
。因此,您必须为图像的实际采样创建新的InputStream
。否则,我们必须中止HTTP
请求。
答案 1 :(得分: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;
}
别忘了在一个帖子(不是主线程)中调用它
答案 2 :(得分:0)
使用以下代码,我可以从网址
下载图片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);
答案 3 :(得分:0)
在decodestream之前需要BufferedInputStream ....
试试这个,它非常适合我使用;
BufferedInputStream buf = new BufferedInputStream(inputsteam, 1024);
传递buf解码流,它将完美地工作。
Bitmap theImage = BitmapFactory.decodeStream(buf);
最后设置你的位图。
答案 4 :(得分:0)
我有同样的问题但在我的情况下问题是资源(图像)。由于Android不支持CMYK图像,因此请确保图像不是CMYK颜色模式。有关详细信息,请参阅this question
祝你好运;)