【问题标题】:Why the bitmap is empty为什么位图为空
【发布时间】:2014-11-26 12:28:21
【问题描述】:

我正在按照教程 here 使用其他应用和自定义 SurfaceView 拍照。

使用SurfaceView拍照时,拍照成功(我退出了我的应用程序,看到文件管理器中确实存在结果图像文件,并且图像内容是正确的。),但图片无法在我的应用程序中正确显示。 ImageView 什么都不显示。

我的代码是这样的:

  public void onPictureTaken(byte[] data, Camera camera) {
    try {
      File file = Utils.getOutputMediaFile(Utils.MediaFileType.Image);
      FileOutputStream os = new FileOutputStream(file);
      os.write(data);
      os.flush();
      os.close();

      final Uri uri = Uri.fromFile(file);
      showImage(uri);
    } catch (FileNotFoundException e) {
      Log.d(TAG, "onPictureTaken, e=" + e);
    } catch (IOException e) {
      Log.d(TAG, "onPictureTaken, e=" + e);
    }

    camera.startPreview();
  }

  private void showImage(Uri imageFileUri) {
    int w = mContentContainer.getWidth();
    int h = mContentContainer.getHeight();
    Bitmap bmp = Utils.loadBitmapFromFile(imageFileUri.getPath(), w, h);
    mImageView.setImageBitmap(bmp);
    mStatusTextView.setText("take photo: succcess");
  }

  public static Bitmap loadBitmapFromFile(String filename, int maxWidth, int maxHeight) {
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inJustDecodeBounds = true;

    BitmapFactory.decodeFile(filename, opt);
    Log.d(TAG, "loadBitmapFromFile, w=" + opt.outWidth + ", h=" + opt.outHeight);

    int widthRatio = (int) Math.ceil(opt.outWidth / maxWidth);
    int heightRatio = (int) Math.ceil(opt.outHeight / maxHeight);

    if (widthRatio > 1 || heightRatio > 1) {
      if (widthRatio > heightRatio) {
        opt.inSampleSize = widthRatio;
      } else {
        opt.inSampleSize = heightRatio;
      }
    }

    opt.inJustDecodeBounds = false;
    Bitmap bmp = BitmapFactory.decodeFile(filename, opt);
    Log.d(TAG, "loadBitmapFromFile, bmp=" + bmp);
    return bmp;
  }

从日志中,我看到从文件中正确加载了宽度和高度,并且 bmp 不为空,但 ImageView 只是空的。

奇怪的是,如果我的应用先拍照并用 showImage() 显示照片(ImageView 正确显示照片),然后用 SurfaceView 拿手机并用 showImage() 显示,照片显示正确。但是如果直接用SurfaceView和showImage()取手机,ImageView是空的。

关于 ImageView 为何为空的任何问题?谢谢。

【问题讨论】:

    标签: android


    【解决方案1】:

    试试(见comments):

      private void showImage(Uri imageFileUri) {
        int w = mContentContainer.getWidth();
        int h = mContentContainer.getHeight();
        Bitmap bmp = Utils.loadBitmapFromFile(imageFileUri.getPath(), w, h);
        mImageView.requestLayout(); //try to request the layout first
        mImageView.setImageBitmap(bmp);
        //if its still not working try to call invalidate() method here
        mStatusTextView.setText("take photo: succcess");
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      相关资源
      最近更新 更多