使用URL下载图像
我正在尝试使用我的应用中的URL和按钮下载图像。 当我在手机上运行时,我无法下载图像。 任何人都可以指出这个问题。 我在这里先向您的帮助表示感谢 :)
这是我的代码。
public class MainActivity extends AppCompatActivity { ImageView download; public void downloadImage(View view){ DownloadImage image = new DownloadImage(); Bitmap result; try { result = image.execute("https://en.wikipedia.org/wiki/File:Bart_Simpson_200px.png").get(); download.setImageBitmap(result); } catch(Exception e) { e.printStackTrace(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); download = (ImageView) findViewById(R.id.imageView); } public class DownloadImage extends AsyncTask{ @Override protected Bitmap doInBackground(String... urls) { URL url; HttpURLConnection urlConnection = null; try { url = new URL(urls[0]); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoInput(true); urlConnection.connect(); InputStream in = urlConnection.getInputStream(); Bitmap Image = BitmapFactory.decodeStream(in); in.close(); return Image; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } } }
你可以通过两种方式从url下载图像
1.您可以使用Glide库从url加载图像查看下面的代码,它可以帮助您以简单的方式
编译这个库
implementation 'com.github.bumptech.glide:glide:4.6.1'
比这样加载图像
Glide.with(MainActivity.this) .load(url) .apply(new RequestOptions().placeholder(R.drawable.booked_circle).error(R.drawable.booked_circle)) .into(imageview);
2。如果您不想使用第三方库,请执行此操作
new DownloadImage(imamgeview).execute(url);
创建异步任务
public class DownloadImage extends AsyncTask { ImageView bmImage; public DownloadImage(ImageView bmImage) { this.bmImage = (ImageView ) bmImage; } protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.d("Error", e.getStackTrace().toString()); } return mIcon11; } protected void onPostExecute(Bitmap result) { bmImage.setImageBitmap(result); } }
我希望它适用于你的情况
你没有调用该函数
downloadImage(view);
在oncreate中(在findviewbyid行之后)
还要检查互联网权限是否在Android清单文件中:
话虽如此,你应该使用像Glide \ Picasso \ Ion等的库……比这个purpuse的asynctask要好得多
https://github.com/bumptech/glide – 滑翔
https://github.com/koush/ion – 离子
http://square.github.io/picasso/ – 毕加索
希望它有所帮助。