gpt4 book ai didi

java - 如何从url获取图像并将其存储在Bitmap变量中

转载 作者:行者123 更新时间:2023-12-01 09:44:55 24 4
gpt4 key购买 nike

我是 Android 新手。我想从 url 获取图像并将其设置为 Bitmap 变量。我尝试了很多代码但没有得到。

这是我的代码:

String url = "https://www.google.com/intl/en_ALL/images/logo.gif";
ImageDownloaderTask image = new ImageDownloaderTask();
image.execute(new String[]{url});
Bitmap bitmap = image.bImage;

ImageDownloaderTask.java

public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {

Bitmap bImage;

@Override
public Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}

private Bitmap downloadBitmap(String src) {
HttpURLConnection urlConnection = null;
try {
URL url = new URL(src);
urlConnection = (HttpURLConnection) url.openConnection();

int statusCode = urlConnection.getResponseCode();
if (statusCode != HttpStatus.SC_OK) {
return null;
}

InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {

Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
Log.d("URLCONNECTIONERROR", e.toString());
if (urlConnection != null) {
urlConnection.disconnect();
}
Log.w("ImageDownloader", "Error downloading image from " + src);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();

}
}
return null;
}

protected void onPostExecute(Bitmap result) {
bImage = result;
}
}

提前致谢...

最佳答案

这是您可以使用的代码

new DownloadImage().execute("https://www.google.com/intl/en_ALL/images/logo.gif");



// DownloadImage AsyncTask
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {

@Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog

}

@Override
protected Bitmap doInBackground(String... URL) {

String imageURL = URL[0];

Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}

@Override
protected void onPostExecute(Bitmap result) {
// Do whatever you want to do with the bitmap

}
}

关于java - 如何从url获取图像并将其存储在Bitmap变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38143624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com