2012-12-15 36 views
0

我有一个奇怪的问题,我试图解决它几个小时了。问题在于,下面的代码可以解码除名字中第一个字母小的那些图像以外的所有图像。例如,它适用于Dog.png或123.png,但它不适用于dog.png,cat.png或任何其他带有小首字母的文件。它只是显示一些随机的颜色。我很困惑。有任何想法吗?Android BitmapFactory.decodeStream无法解码一些URL的

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); 
+1

你的代码不能编译 - image.setImageBitmap(bimage); =错字。请复制并粘贴您的真实代码。 – auval

+0

评论#2:拆分“新的URL(imagePath).getContent()”,测试你是否得到空。粘贴堆栈跟踪..(帮我们帮你) – auval

+0

这是真正的代码。在复制/粘贴该顶级代码后,我手动添加了最后一行,因此我输错了它。我测试了新的URL(imagePath).getContent()并且它不返回null。这真是个奇怪的问题。如果第一个字母是大写或小写,这不应该很重要。 – Cristiano

回答

2

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

首先,我们需要捕捉图像的描述是这样的:

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(); 

形象现在保存,我们可以抓住它,并显示在我们的ImageView称为图像:

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

为什么你在上面使用inSampleSize这个变量,如果没有必要? – duggu

+0

所以我可以设置'options.inSampleSize = inSampleSize'。 – Cristiano

相关问题