我正在尝试使用我的应用程序中的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<String, Void, Bitmap>{ @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<String, Void, Bitmap> { 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); } }
我希望它能适合您的情况