我有一个 URL,我想转换为位图,但我没有得到 o/p 。我应用了一些方法来对这件事进行排序,但仍然没有得到任何东西。
我在 Stack Overflow 上的上一个答案中搜索了解决方案,但我也被它卡住了。我在做什么 :
URL url = new URl("http://www.XYZ.com/image.jpg");
并将这个东西放入
BitmapFactory.decodeStream(_ _ _);
我应该怎么做才能解决它?
private Drawable loadImageFromWeb(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
一个漫长但实用的解决方案
try
{
InputStream inn = OpenConnection(URL);
Bitmap bmp = BitmapFactory.decodeStream(inn);
inn.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
public InputStream OpenHttpConnection(String url) {
InputStream in = null;
int response = -1;
URL url = new URL(url);
URLConnection conn = url.openConnection();
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)
{
ex.printStackTrace();
}
return in;
}
这个怎么样?当我尝试时它有效。
URL url = new URL("http://www.XYZ.com/image.jpg");
Object content = url.getContent();
InputStream is = (InputStream) content;
//drawable
Drawable drawable = Drawable.createFromStream(is, "src");
//bitmap
Bitmap bitmap = BitmapFactory.decodeStream(is);