gpt4 book ai didi

android - BitmapFactory.decodeStream 无一异常(exception)地返回 null

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:56:46 28 4
gpt4 key购买 nike

我尝试从服务器加载远程图像,感谢 stackoverflow 上的大量代码示例,我有一个解决方案可以在 3 个图像中的 2 个中工作。我真的不知道第三张图片有什么问题,有时当让代码在调试器中运行时图片正在加载。另外,如果我先加载问题图片,有时其他两张图片不会加载。

代码如下:

public static Drawable getPictureFromURL(Context ctx, String url, final int REQUIRED_SIZE) throws NullPointerException {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
int scale = 1;
if (o.outWidth > REQUIRED_SIZE) {
scale = (int) Math.pow(2, (int) Math.round(Math.log(REQUIRED_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
Log.i(Prototype.TAG, "scale: "+scale);

//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bmp;
try {
bmp = BitmapFactory.decodeStream((InputStream) Tools.fetch(url), null, o2);
if(bmp!=null)
return new BitmapDrawable(ctx.getResources(), bmp);
else
return null;
} catch (Exception e) {
Log.e(Prototype.TAG, "Exception while decoding stream", e);
return null;
}
}

调试时发现o.outWidth为-1表示错误,但没有抛出Exception,所以我也说不清哪里出了问题。 InputStream 始终返回一个有效值,我知道该图片存在于服务器上。

祝你好运,丹尼尔

最佳答案

我找到了答案 here并将获取方法更新为:

private static InputStream fetch(String address) throws MalformedURLException,IOException {
HttpGet httpRequest = new HttpGet(URI.create(address) );
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream instream = bufHttpEntity.getContent();
return instream;
}

关于android - BitmapFactory.decodeStream 无一异常(exception)地返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4414839/

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