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

时间:2011-10-03 13:49:12

标签: android

我想阅读此网址photo

中的图片

我正在使用以下代码

 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;

        }

位图总是返回给我null ..我还使用了互联网上的其他功能。 all将位图返回为空值:S

2 个答案:

答案 0 :(得分:1)

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

http://184.173.7.132/RealAds_Images/Apartment%20for%20sale,%20Sheikh%20Zayed%20_%201.jpg

对我来说,%20不会渲染空格,所以请确保在代码中注明

如果您将文件更改为apartmentforsalesheikhzayed20201.jpg或类似测试apartment.jpg,它将起作用。

就个人而不是在图像名称中使用空格而言,我会在空格之间使用下划线,因此不需要其他代码try_renaming_your_photo_to_this.jpg:)

答案 1 :(得分:1)

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

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


      }