【问题标题】:Android BitmapFactory.decodeStream can't decode some URL'sAndroid BitmapFactory.decodeStream 无法解码某些 URL
【发布时间】:2012-12-15 20:55:49
【问题描述】:

我有一个奇怪的问题,我已经尝试解决了几个小时。问题是下面的代码可以解码所有图像,除了名称中第一个字母小的图像。例如,它适用于 Dog.png 或 123.png,但不适用于 dog.png、cat.png 或任何其他首字母较小的文件。它只是为它们显示一些随机颜色。我很困惑。有什么想法吗?

    Bitmap bitmap = null;

    options.inJustDecodeBounds = false;
    try {
        bitmap =  BitmapFactory.decodeStream((InputStream)new URL(imagePath).getContent(), null, options);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    image.setImageBitmap(bimage);

【问题讨论】:

  • 您的代码无法编译 - image.setImageBitmap(bimage); = 错字。请复制并粘贴您的真实代码。
  • 评论#2:拆分“new URL(imagePath).getContent()”,测试是否为空。粘贴堆栈跟踪..(帮助我们帮助您)
  • 这是真正的代码。我在复制/粘贴该顶部代码后手动添加了最后一行,所以我打错了。我测试了 new URL(imagePath).getContent() 并且它不返回 null。这真是一个奇怪的问题。第一个字母是大写还是小写并不重要。

标签: android bitmap stream


【解决方案1】:

我找到了解决方案。这些 URL 中的图片可以被解码,但问题是它太大了,所以它显示得非常大,看起来好像没有显示。

首先我们需要像这样捕获图像的描述:

options.inJustDecodeBounds = true;
BitmapFactory.decodeStream((InputStream)new URL(url).getContent(), null, options);

然后将其缩放到所需的宽度/高度,reqHeight/reqWidth 是想要的尺寸参数:

int height = options.outHeight;
int width = options.outWidth;
int inSampleSize;

if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} 
else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}

之后只需重复问题中的代码:

Bitmap bitmap = null;

options.inJustDecodeBounds = false;
try {
    bitmap =  BitmapFactory.decodeStream((InputStream)new URL(imagePath).getContent(), null, options);
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

现在我们可以将它保存到某个目录:

File file = new File(some_path\image.png);

    if (!file.exists() || file.length() == 0) {
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();
            fos.flush();

现在保存的图像,我们可以抓取它并显示在名为 image 的 ImageView 中:

Bitmap bitmap = BitmapFactory.decodeFile(some_path\image.png);
image.setImageBitmap(bitmap);

【讨论】:

  • 所以我可以设置options.inSampleSize = inSampleSize
猜你喜欢
  • 2019-08-19
  • 2015-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-23
相关资源
最近更新 更多