【问题标题】:BitmapFactory's decodeFile returns nullBitmapFactory 的 decodeFile 返回 null
【发布时间】:2016-04-07 17:33:06
【问题描述】:

这是我的代码的简化版本。我得到了应用程序屏幕的两个屏幕截图并存储在 first.png 和 sec.png 中,我可以看到它们位于 app\src 文件夹中。我可以打开图像并查看它们是否是正确的屏幕截图。但是,当我尝试使用 bitmapfactory 将它们放入位图中时,我得到空值。我已经尝试给出绝对路径和相对路径,并且我已经关注了其他相同的问题回复,所以请在将其标记为重复之前查看它。

class Test{
private static boolean compareImages() throws FileNotFoundException {
    ​Bitmap bitmap1 = BitmapFactory.decodeFile("src/"+imgFirst);
    Bitmap bitmap2 = BitmapFactory.decodeFile("src/"+imgSecond);
    if (bitmap1.getWidth() != bitmap2.getWidth() ||
            bitmap1.getHeight() != bitmap2.getHeight()) {
        return false;
    }

    for (int y = 0; y < bitmap1.getHeight(); y++) {
        for (int x = 0; x < bitmap1.getWidth(); x++) {
            if (bitmap1.getPixel(x, y) != bitmap2.getPixel(x, y)) {
                return false;
            }
        }
    }
    return true;
}
 public static boolean test() {

    File scrFile = (Setup.getDriver()).getScreenshotAs(OutputType.FILE);//The Setup.getDriver() returns an AppiumDriver.
    FileUtils.copyFile(scrFile, new File(imgFirst));
    scrFile = (Setup.getDriver()).getScreenshotAs(OutputType.FILE);
    FileUtils.copyFile(scrFile, new File(imgSecond));
    if(compareImages())
        return false;
    else
        return true;
 }
    private static String imgFirst = "first.png";
    private static String imgSecond = "sec.png";
 }

【问题讨论】:

  • 在您的代码中,BitmapFactory 是在哪里导入的?
  • 我已经导入了android.graphics.Bitmapandroid.graphics.BitmapFactory
  • 好的,你能添加你得到的异常的堆栈跟踪
  • 显示您在磁盘中存储屏幕截图的代码。您应该能够使用相同的路径来检索图像。

标签: android appium android-bitmap bitmapfactory


【解决方案1】:

如果您在BitmapFactory.decodeFile 上获得NPE,您应该尝试获取文件的绝对路径并将其用作:

String firstImage=new File(getFilesDir(), imgFirst).getAbsolutePath();
​Bitmap bitmap1 = BitmapFactory.decodeFile(firstImage);

参考:SO-3388898

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 2012-01-28
    • 2016-03-22
    相关资源
    最近更新 更多