2016-11-05 63 views
0

我想要获取widht和图片的高度,然后能够将其加载到我的活动画布上。当我尝试打印这个高度和宽度时,我总是得到0.我不明白为什么?从图片的URI获取宽度和高度

这里是我的代码:

private void openPicture() { 
     BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     try { 
      InputStream stream = context.getContentResolver().openInputStream(uri); 
      BitmapFactory.decodeStream(stream); 
      int width = options.outWidth; 
      int height = options.outHeight; 
      Log.d("DEBUG", ""+ width); 
      loadPicture(width, height); 
     } catch(IOException e) { 
      Log.e("FingerPainterView", e.toString()); 
     } 
    } 

    private void loadPicture(int w, int h) { 

     try { 
      // attempt to load the uri provided, scale to fit our canvas 
      InputStream stream = context.getContentResolver().openInputStream(uri); 
      Bitmap bm = BitmapFactory.decodeStream(stream); 
      bitmap = Bitmap.createScaledBitmap(bm, Math.max(w, h), Math.max(w, h), false); 
      stream.close(); 
      bm.recycle(); 
     } catch(IOException e) { 
      Log.e("FingerPainterView", e.toString()); 
     } 
     canvas = new Canvas(bitmap); 
    } 

回答

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

}