can i get image file width and height from uri in android?

前端 未结 10 2057
深忆病人
深忆病人 2020-12-08 01:58

i can getting the image width through MediaStore.Images.Media normally

but i need to getting the image width and height from image which selected from d

相关标签:
10条回答
  • 2020-12-08 02:55

    The accepted answer returns with me a 0 of width/height, by replacing uri.getPath() with uri.getLastPathSegment(), it returns the correct dimensions

    public static int[] getImageDimension(Uri uri){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(new File(uri.getLastPathSegment()).getAbsolutePath(), options);
        return new int[]{options.outWidth, options.outHeight};
    }
    
    0 讨论(0)
  • 2020-12-08 03:00

    Blackbelt's answer is correct if you have a file uri. However, if you are using the new file providers as in the official camera tutorial, it won't work. This works for that case:

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(
            getContext().getContentResolver().openInputStream(mPhotoUri),
            null,
            options);
    int imageHeight = options.outHeight;
    int imageWidth = options.outWidth;
    
    0 讨论(0)
  • 2020-12-08 03:00

    the solution is use new File(uri.getPath()).getAbsolutePath() instead of uri.toString()

    0 讨论(0)
  • 2020-12-08 03:05

    Please use InputStream:

    public int[] getImageSize(Uri uri){
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            InputStream input = this.getContentResolver().openInputStream(uri);
            BitmapFactory.decodeStream(input, null, options);  input.close();
            return new int[]{options.outWidth, options.outHeight};
        }
        catch (Exception e){}
        return new int[]{0,0};
    }
    

    It'll return in array form:

    int[]{ width , height }
    
    0 讨论(0)
提交回复
热议问题