Java 从URL获取位图
我正在尝试从URL获取位图图像。Java 从URL获取位图,java,android,Java,Android,我正在尝试从URL获取位图图像。 (例如:) 但是,connection.connect()行似乎有一个问题,我想不出来。 我已允许在应用程序中访问internet public static Bitmap getBitmapFromURL(String src) { HttpURLConnection connection = null; InputStream inputStream = null; try { URL url = new URL(sr
(例如:) 但是,
connection.connect()
行似乎有一个问题,我想不出来。我已允许在应用程序中访问internet
public static Bitmap getBitmapFromURL(String src) {
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
URL url = new URL(src);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();
}
return BitmapFactory.decodeStream(inputStream);
}
你可以用glide做一个简短的解决方案
implementation "com.github.bumptech.glide:glide:4.11.0"
annotationProcessor "com.github.bumptech.glide:compiler:4.11.0"
一般来说,网络连接应该在一个单独的线程中完成。您可以使用
AsyncTask
。例如,这项工作:
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_layout);
imageView = (ImageView) findViewById(R.id.imageView);
new LoadImage().execute("https://cdn.bulbagarden.net/upload/9/9a/Spr_7s_001.png");
}
private class LoadImage extends AsyncTask<String, Void, Bitmap>{
@Override
protected Bitmap doInBackground(String... strings) {
Bitmap bitmap = null;
try {
InputStream inputStream = new URL(strings[0]).openStream();
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
}
}
ImageView;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_布局);
imageView=(imageView)findViewById(R.id.imageView);
新建LoadImage()。执行(“https://cdn.bulbagarden.net/upload/9/9a/Spr_7s_001.png");
}
私有类LoadImage扩展了异步任务{
@凌驾
受保护位图doInBackground(字符串…字符串){
位图=空;
试一试{
InputStream InputStream=新URL(字符串[0])。openStream();
位图=BitmapFactory.decodeStream(inputStream);
}捕获(IOE异常){
e、 printStackTrace();
}
返回位图;
}
@凌驾
受保护的void onPostExecute(位图){
设置图像位图(位图);
}
}
链接不是png文件,而是包含html内容的网页。您需要有一个图像url。try{}block需要用catch{}关闭,或者最后{}遇到什么问题/错误?请检查以下答案:
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_layout);
imageView = (ImageView) findViewById(R.id.imageView);
new LoadImage().execute("https://cdn.bulbagarden.net/upload/9/9a/Spr_7s_001.png");
}
private class LoadImage extends AsyncTask<String, Void, Bitmap>{
@Override
protected Bitmap doInBackground(String... strings) {
Bitmap bitmap = null;
try {
InputStream inputStream = new URL(strings[0]).openStream();
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
}
}