gpt4 book ai didi

android - 在 Android 中从 url 下载图像的最佳方法

转载 作者:IT王子 更新时间:2023-10-28 23:59:14 24 4
gpt4 key购买 nike

我正在使用以下方法从 url 下载单个图像

public static Bitmap getBitmap(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Bitmap d = BitmapFactory.decodeStream(is);
is.close();
return d;
} catch (Exception e) {
return null;
}
}

有时我会遇到内存不足异常。

我无法捕获内存不足异常。该应用程序将关闭。如何防止这种情况?

有没有更好更快的图片下载方法?

最佳答案

            public void DownloadImageFromPath(String path){
InputStream in =null;
Bitmap bmp=null;
ImageView iv = (ImageView)findViewById(R.id.img1);
int responseCode = -1;
try{

URL url = new URL(path);//"http://192.xx.xx.xx/mypath/img1.jpg
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoInput(true);
con.connect();
responseCode = con.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK)
{
//download
in = con.getInputStream();
bmp = BitmapFactory.decodeStream(in);
in.close();
iv.setImageBitmap(bmp);
}

}
catch(Exception ex){
Log.e("Exception",ex.toString());
}
}

关于android - 在 Android 中从 url 下载图像的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18210700/

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