2011-10-03 56 views
0

我想从这个URL photo如何从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 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

回答

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


     } 
1

我会在图片上

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

检查%20间隔对我来说,%20将不会呈现一个空间,从而确保这在代码中指出

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

的个人,而不是在你的图像名称中使用空格我会用,无需进行任何其他代码try_renaming_your_photo_to_this.jpg :)

+0

下划线使用的好处。 android中的URI类也有安全编码和解码URL/URI的内容。 http://developer.android.com/reference/android/net/Uri.html#encode%28java.lang.String%29 –