作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图通过链接从 Internet 获取图像,并通过按下按钮将其显示在 imageView 上,但图像不会显示。经过一些调试后,我发现该行 imgView.setImageBitmap(myImg);抛出异常。
public class MainActivity extends AppCompatActivity {
ImageView imgView;
public void imageFromWeb(View view){
imageDownloader task = new imageDownloader();
Bitmap myImg;
try{
myImg = task.execute("https://upload.wikimedia.org/wikipedia/commons/4/40/R_federer.jpg").get();
imgView.setImageBitmap(myImg);
}catch(Exception e){
Log.i("check","error");
e.printStackTrace();
}
}
public class imageDownloader extends AsyncTask<String, Void, Bitmap>{
@Override
protected Bitmap doInBackground(String... urls) {
URL url;
HttpURLConnection urlConnection;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
Bitmap img = BitmapFactory.decodeStream(inputStream);
return img;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
imgView = findViewById(R.id.imageView);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
当我运行应用程序并单击按钮时,我看到打印了“检查错误”行,我在 imageFromWeb 函数的 catch block 中打印了 log.i 以及
2019-05-28 10:29:13.515 4764-4764/com.ashwin.imagefromweb I/Choreographer: Skipped 53 frames! The application may be doing too much work on its main thread.
这里出了什么问题?非常感谢!
最佳答案
尝试使用 Glide 从 url 访问图像
Glide.with(this)
.load("url here") // image url
.placeholder(R.drawable.placeholder) // any placeholder to load at start
.error(R.drawable.imagenotfound) // any image in case of error
.override(200, 200); // resizing
.centerCrop();
.into(imageView); // imageview object
关于java - 我正在尝试从链接下载图像并将其显示在 ImageView 中,但行 imgView.setImageBitmap(myImg);抛出一些错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56347440/
我试图通过链接从 Internet 获取图像,并通过按下按钮将其显示在 imageView 上,但图像不会显示。经过一些调试后,我发现该行 imgView.setImageBitmap(myImg);
我是一名优秀的程序员,十分优秀!