gpt4 book ai didi

java - 下载图像时 BitmapFactory.decodeStream 返回空值

转载 作者:太空宇宙 更新时间:2023-11-04 11:49:38 27 4
gpt4 key购买 nike

我们使用下面的函数从 URL 下载图像。有时,BitmapFactory.decodeStream 我们会得到 null。由于这个问题,收到的通知没有图像。任何人都可以帮助我们解决该问题..

这是我的代码:

private Bitmap getImageBitmap(String url)
{
Bitmap bmsd = null;
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bmsd = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
return bmsd;
}

最佳答案

尝试这样,如果位图大小太大,我们需要调整位图大小。

private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);

//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;

//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}

//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);

//Find the correct scale value. It should be the power of 2.
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}

//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}

public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}

关于java - 下载图像时 BitmapFactory.decodeStream 返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41976438/

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