如何在Android中从URL读取图像?

如何在Android中从URL读取图像?,android,Android,我想从这个URL中读取一个图像 我使用下面的代码 public static Bitmap DownloadImage(String URL) { Bitmap bitmap=null; InputStream in=null; try { in=networking.OpenHttpConnection("http://izwaj.com/"+URL); BitmapFactory.Options options=new BitmapF

我想从这个URL中读取一个图像

我使用下面的代码

 public static Bitmap DownloadImage(String URL)
{
    Bitmap bitmap=null;
    InputStream in=null;
    try {
        in=networking.OpenHttpConnection("http://izwaj.com/"+URL);
        BitmapFactory.Options options=new BitmapFactory.Options();
        options.inSampleSize=8;

        bitmap=BitmapFactory.decodeStream(in, null, options);
        in.close();
    } catch (Exception e) {
        // TODO: handle exception
    }
    return bitmap;
}

 public class Networking {
public InputStream OpenHttpConnection(String urlString)

        throws IOException
        {
    InputStream in=null;
    int response = -1;

    URL url=new URL(urlString);
    URLConnection conn=url.openConnection();

    if(!(conn instanceof HttpURLConnection))
    {
        throw new IOException("Not an HTTP connection");
    }

    try {
        HttpURLConnection httpconn=(HttpURLConnection)conn;
        httpconn.setAllowUserInteraction(false);
        httpconn.setInstanceFollowRedirects(true);
        httpconn.setRequestMethod("GET");
        httpconn.connect();
        response=httpconn.getResponseCode();
        if(response==HttpURLConnection.HTTP_OK)
        {
            in=httpconn.getInputStream();
        }
    }



    catch (Exception ex) {
        throw new IOException("Error connecting");
    }
    return in;

        }

位图始终返回给我空。。我还使用了互联网上的其他功能。全部以空值返回位图:S

我将检查图片上的%20间距

http://184.173.7.132/RealAds_Images/Apartment%20for%20sale,%20Sheikh%20Zayed%20_%201.jpg
对我来说%20不会呈现空格,所以请确保在代码中注明这一点

如果您将文件更改为apartmentforsalesheikhzayed20201.jpg或类似的test-plant.jpg文件,它将起作用


就个人而言,我不会在图像名称中使用空格,而是在空格之间使用下划线,这样就不需要其他代码了。请尝试将您的照片重命名为this.jpg:)

使用此功能,它可能会对您有所帮助

public Bitmap convertImage(String url)
     {

        URL aURL = null;
        try 
       {
        final String imageUrl =url.replaceAll(" ","%20");
        Log.e("Image Url",imageUrl);
        aURL = new URL(imageUrl);
        URLConnection conn = aURL.openConnection();
        InputStream is = conn.getInputStream(); 
        //@SuppressWarnings("unused")
        BufferedInputStream bis = new BufferedInputStream(is); 
        Bitmap bm = BitmapFactory.decodeStream(new PatchInputStream(bis)); 
        if(bm==null)
        {}
        else
       Bitmap bit=Bitmap.createScaledBitmap(bm,72, 72, true);//mention size here

        return bit;

       } 


        catch (IOException e) 
        {
           Log.e("error in bitmap",e.getMessage());
          return null;
       }


      }

下划线用法的优点。android中的URI类还具有安全编码和解码URL/URI的功能。