程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> android-不能從 url 中獲取圖像

android-不能從 url 中獲取圖像

編輯:編程綜合問答
不能從 url 中獲取圖像

我想從url中獲取圖像,用的下面的代碼:

 public class Img extends Activity {
/** Called when the activity is first created. */
ImageView img;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    img = (ImageView)findViewById(R.id.imgview);

    Bitmap bm = getBitmapFromURL("http://l.yimg.com/a/i/us/we/52/21.gif");
    if(bm == null)
        Toast.makeText(this, "Image can't load", 1).show();
    else
        img.setImageBitmap(bm);
}


public static Bitmap getBitmapFromURL(String src) {
    try {
        Log.e("src",src);
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        Log.e("Bitmap","returned");
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("Exception",e.getMessage());
        return null;
    }
}
}

但是獲得的消息是: "Image can't load"。如何解決這個問題?

最佳回答:


試一下下面的代碼:

 ImageView img;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    img = (ImageView)findViewById(R.id.imgview);

    Drawable image = getBitmapFromURL("http://l.yimg.com/a/i/us/we/52/21.gif");
    if(image == null)
        Toast.makeText(this, "Image can't load", 1).show();
    else
        img.setImageDrawable(image);
}

public Drawable  getBitmapFromURL(String url) {
try {
    InputStream is = (InputStream) new URL(url).getContent();
    Drawable d = Drawable.createFromStream(is, "src name");
    return d;
} catch (Exception e) {
    return null;
}
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved