2010-06-01 65 views
2

我正在使用BitmapFactory.decodeFile将Bitmap图像加载到我的应用程序中。但是,该函数在大图像(例如来自相机的图像)上返回null。文件路径绝对正确,我只是不知道为什么它会返回null。我尝试了超取样,但似乎没有帮助。Android将相机图像加载为位图

有没有人有任何想法,为什么它会这样做,或者我怎么可以更容易地加载从相机拍摄的图像到一个位图?

下面是我使用的代码:

public static Bitmap loadBitmap(String filePath){ 
    Bitmap result = BitmapFactory.decodeFile(filePath); 

    if(result == null){ 
     if(filePath.contains(".jpg") || filePath.contains(".png")){ 
      //This is the error that occurs when I attempt to load an image from the Camera DCIM folder or a large png I imported from my computer. 
      Utils.Toast("Could not load file -- too big?"); 
     } else { 
      Utils.Toast("Could not load file -- image file type is not supported"); 
     } 
    } 
    return result; 
} 
+0

您是否将相机图像保存到SD卡上?是否存在所有的路径? – 2010-06-01 07:12:59

+0

是的,图像是通过文件浏览器选择的,所以路径一定是正确的。在同一文件夹中选择的其他(较小)图像完美地工作。 – GuyNoir 2010-06-02 15:59:37

+0

你能提供一些你正在使用的代码吗? – Cristian 2010-06-06 04:01:51

回答

3

您需要提供问题的详细信息,如代码片段所使用。如果你想知道什么时候/为什么BitmapFactory.decodeFile方法将返回null,则可以直接读取它的源代码:http://casidiablo.in/BitmapFactory

例如,导致BitmapFactory.decodeFile返回NULL是,如果同时开扩的文件出现问题的原因之一。奇怪的是,开发者不会记录任何有这样问题的东西......看看的评论“什么都不做,如果异常发生在open上,那么bm将为null”。

public static Bitmap decodeFile(String pathName, Options opts) { 
    Bitmap bm = null; 
    InputStream stream = null; 
    try { 
     stream = new FileInputStream(pathName); 
     bm = decodeStream(stream, null, opts); 
    } catch (Exception e) { 
     /* do nothing. 
      If the exception happened on open, bm will be null. 
     */ 
    } finally { 
     if (stream != null) { 
      try { 
       stream.close(); 
      } catch (IOException e) { 
       // do nothing here 
      } 
     } 
    } 
    return bm; 
} 

正如你所看到的,BitmapFactory.decodeFile不独立工作...但它使用的BitmapFactory类的一些其他的方法(例如,BitmapFactory.decodeStreamBitmapFactory.nativeDecodeStreamBitmapFactory.finishDecode等)。问题可能出在这些方法之一上,所以如果我是你,我会尝试阅读并理解它们是如何工作的,以便我能够知道它们在哪些情况下返回null。

+0

我刚刚发布了代码(可能在您输入回复时)。我会研究一些你建议的方法。谢谢! – GuyNoir 2010-06-06 16:09:40

+0

好吧,我只是尝试了FileInputStream方法,而实际上它确实说这个文件不存在。考虑到那里有一个文件,这很奇怪。 我会继续摆弄。 – GuyNoir 2010-06-06 16:15:47

+1

好吧,似乎文件的名称是问题。当我将它们重命名为“image.jpg”而不是基于照片时间戳的名称时,我实际上可以加载图像。谢谢您的帮助。 当然,我现在得到一个OOM异常,但这是别的东西要处理的。 您是否碰巧知道我在哪里可以找到Gallery应用程序的源代码(或任何此类问题)。我只需要弄清楚在加载和显示大型图像时如何解决小堆大小问题。 – GuyNoir 2010-06-06 16:27:45

0

这听起来很明显,但检查你的filePath实际上指向一个文件。您提到您正在使用文件管理器来选择要打开的映像 - 文件管理器可能会返回到内容提供者的路径而不是文件。

使用ContentResolver类可以打开文件的更健壮的方式,它可以打开InputStream到内容提供者,文件或资源,而无需事先知道传递它的路径。

唯一的问题是,您需要在调用openInputStream()而不是String时调用Uri对象。

public static Bitmap loadBitmap(String filePath, Context c) { 
    InputStream inStream; 

    try { 
     inStream = c.getContentResolver().openInputStream(Uri.parse(filePath)); 
    } catch (FileNotFoundException e) { 
     // handle file not found 
    } 

    return BitmapFactory.decodeStream(inStream); 
} 

这也恰好是ImageView的小部件如何时,尝试使用它setImageURI方法加载图像。