天天看點

照相機拍照NullPointerException 問題

ACTION_IMAGE_CAPTURE 照相時遇到了NullPointerException問題。

因機器不同,在獲得圖檔的方式上有所不同。

EXTRA_OUTPUT不能将拍下的圖檔儲存到臨時檔案中,顯示時就會出現NullPointerException問題。

根據data直接獲得圖檔的URI位址,可以顯出圖檔。

File tempFile;

String TEMP = "temp.jpg";

private File getTempFile() {
            File dir = new File(Util.getTempImageDirectory());
            if (!dir.exists()) {
                if (!dir.mkdirs()) {
                    return null;
                }
            }
            tempFile = new File(Util.getTempImageDirectory(), TEMP);
            try {
                tempFile.createNewFile();
            } catch (IOException e) {
                return null;
            }
            return tempFile;
    }

protected void getImagesFromCamera(){
        Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        uri = Uri.fromFile(tempFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, GET_CODE_ORIGINAL_IMAGE_BY_CAMERA);

    }

//獲得圖檔
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_CANCELED) {
        }
        else {
             BitmapFactory.Options options = new BitmapFactory.Options();
             options.inSampleSize = 2;
             Bitmap myBitmaptemp = BitmapFactory.decodeFile(tempFile.getAbsolutePath(),options);
             if(myBitmaptemp == null){
                 Uri imageUri = data.getData();
                 ContentResolver cr = getContentResolver();
                 InputStream imgIS  = cr.openInputStream(imageUri);
                 myBitmaptemp=BitmapFactory.decodeStream(imgIS);
             }
             myBitmaptemp = zoomBitmap(myBitmaptemp,(int)imgWidth,(int)imgHeight);
             .................
          }
    }

 //修改圖檔尺寸
 public static Bitmap zoomBitmap(Bitmap bitmap,int w,int h){
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidht = ((float)w / width);
        float scaleHeight = ((float)h / height);
        if(scaleWidht < scaleHeight ){
            matrix.postScale(scaleWidht, scaleWidht);
        }else{
            matrix.postScale(scaleHeight, scaleHeight);
        }
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width , height , matrix,true);
        return newbmp;
    }