2017-09-17 71 views
-1

我已经在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空值。

预先感谢您!

+0

看到logcat的,什么是崩溃的原因。 – 2017-09-17 05:09:10

+0

你是否在任何线程中运行代码? – 2017-09-17 05:10:41

+0

什么是你的logcart消息? – 2017-09-17 05:16:06

回答

0

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); 
    } 


} 
+0

谢谢你的回答,但我试过了,位图仍然是空的 – justinj

+0

你试过用另一个链接吗?可能是链接被破坏? –

+0

感谢您的帮助,但我没有尝试过几个链接,都没有工作 – justinj