无法从HttpUrlConnection(PNG到位图)加载图像,inputStream中的位图为空
问题描述:
我已经在Stack Overflow和Internet上研究了如何从URL
加载图像并将其作为Bitmap
(原本一个.png
文件)。我按照说明进行操作,代码如下,代码的类别为AsyncTask
。无法从HttpUrlConnection(PNG到位图)加载图像,inputStream中的位图为空
try {
imageUrl = new URL(currentApp.getImageURL());
HttpURLConnection urlConnection = (HttpURLConnection)
imageUrl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
***urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
imageBitmap = BitmapFactory.decodeStream(inputStream);
viewHolder.tvImage.setImageBitmap(imageBitmap);
inputStream.close();***
} catch (MalformedURLException e) {
Log.d(TAG, "getView: " + e.toString());
} catch (IOException e) {
Log.d(TAG, "getView: " + e.toString());
} finally {
}
为我所用的调试工具来帮助我,我发现,从连接响应代码是200,但imageBitmap = BitmapFactory.decodeStream(inputStream);
,我得到imageBitmap
空值。
预先感谢您!
答
Decode Stream return null如果输入流为空或不能用于解码位图。尝试从另一个URL下载图像,我下载的YouTube播放列表的缩略图和其工作110%为我好,试试这个代码
public class DownloadImagesTask extends AsyncTask<ImageView, Void, ImageView> {
ImageView iv=null;
Bitmap bitmap=null;
String url=null;
public DownloadImagesTask(ImageView iv,int position,String url) {
this.iv = iv;
this.position=position;
this.url = url;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected ImageView doInBackground(ImageView... url) {
try {
Log.e("url", this.url);
URL ulrn = new URL(this.url);
HttpURLConnection con = (HttpURLConnection) ulrn.openConnection();
InputStream is = con.getInputStream();
this.bitmap = BitmapFactory.decodeStream(is);
if (null != this.bitmap)
{
return iv;
}
}catch(Exception e){}
return null;
}
@Override
protected void onPostExecute(ImageView result) {
if(result!=null) {
this.iv.setImageBitmap(bitmap);
}
else
iv.setImageResource(R.drawable.loading);
}
}
看到logcat的,什么是崩溃的原因。 – 2017-09-17 05:09:10
你是否在任何线程中运行代码? – 2017-09-17 05:10:41
什么是你的logcart消息? – 2017-09-17 05:16:06