我知道这个问题已被多次提出,但我已经尝试了许多解决方案而没有人工作。
在Android上,我试图从URL获取图像以将其放入图像视图中。 不幸的是,我收到以下错误:
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: http:/lorempixel.com/1920/1920/business (No such file or directory)
当我尝试从模拟器的浏览器访问此URL时,它可以正常工作。
我已经尝试过以下解决方案: Load image from url
How to get image from url website in imageview in android
how to set image from url for imageView
我的实际代码如下:
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView imgView;
public DownloadImage(ImageView imgView){
this.imgView = imgView;
}
@Override
protected Bitmap doInBackground(String... urls) {
return download_Image(urls[0]);
}
@Override
protected void onPostExecute(Bitmap result) {
if (result != null)
imgView.setImageBitmap(result);
}
private 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();
Log.e("CON ", "HTTP connection OK");
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
private Bitmap download_Image(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection("http://lorempixel.com/1920/1920/business");
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
}
在主要活动中,我的代码是:
ImageView img = (ImageView) findViewById(R.id.imageView);
DownloadImage download = new DownloadImage(img);
download.execute(url);
在清单中我添加了:
<uses-permission android:name="android.permission.INTERNET" />
我该怎么办?
答案 0 :(得分:0)
这很完美:
String urlPath = "http://anyWebsite.com/images/12"
Bitmap bm = BitmapFactory.decodeStream((InputStream) new URL(urlPath).getContent());
myImageView.setImageBitmap(bm);