【问题标题】:Get Image Width and Height from URI从 URI 获取图像宽度和高度
【发布时间】:2014-07-15 02:11:45
【问题描述】:

是否可以从 URI 中获取图像文件的宽度和高度。我试图使用此代码,但他们的错误: getAbsolutePath() 后出现语法错误

标记“)”上的语法错误,ArgumentList 无效

private void getDropboxIMGSize(Uri uri){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(uri.getPath()).getAbsolutePath(), options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
}

【问题讨论】:

  • getAbsolutePath() 后的语法错误......令牌“)”上的语法错误,ArgumentList 无效......
  • 你错过了(在uri.getPath()之前

标签: android


【解决方案1】:

这样做

public void getDropboxIMGSize(Uri uri) {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(getAbsolutePath(uri), o);
        int imageHeight = o.outHeight;
        int imageWidth = o.outWidth;
    }



public String getAbsolutePath(Uri uri) {
        String[] projection = { MediaColumns.DATA };
        @SuppressWarnings("deprecation")
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } else
            return null;
    }

【讨论】:

  • 内容 URI 可能来自与 MediaStore 不同的提供者。在这种情况下,您将获得一个空路径。永远不要从 Uri 实例化 File
【解决方案2】:

如果您将参数提取到局部变量中,您将不太可能遗漏括号/包含一个额外的括号,并且会更容易阅读您的代码。

之前:

private void getDropboxIMGSize(Uri uri){
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(uri.getPath()).getAbsolutePath(), options);
    int imageHeight = options.outHeight;
    int imageWidth = options.outWidth;
}

之后:

private void getDropboxIMGSize(Uri uri){
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    String path = uri.getPath().getAbsolutePath();
    BitmapFactory.decodeFile(path, options);
    int imageHeight = options.outHeight;
    int imageWidth = options.outWidth;
}

注意,您已将options.outHeightoptions.outWidth 分配给局部变量,然后方法结束;你没有对这些值做任何事情。

【讨论】:

    【解决方案3】:

    我遇到了同样的问题,我在this answer找到了解决方案。你必须使用

    BitmapFactory.decodeFile(new File(uri.getPath()).getAbsolutePath(), options);
    

    在你的代码中而不是这个:

    BitmapFactory.decodeFile(uri.getPath()).getAbsolutePath(), options);
    

    【讨论】: