Android相机位图问题

时间:2015-04-07 21:39:37

标签: android file bitmap bitmapimage android-bitmap

您好我在Android应用程序中使用相机功能时遇到问题。我可以使用相机实用程序拍摄照片,但是当返回时,位图图像为空白,但格式化为所拍照片的大小。我错过了什么,让图像显示?我应该不使用imageview吗?谢谢! -T

private Uri capturedImageUri;
ImageView picture;
Button snapButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.camera_observation);

    picture = (ImageView) findViewById(R.id.imageView);
    snapButton = (Button) findViewById(R.id.picButton);

    snapButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            open();
        }
    });
}

public void open (){
    File file = new File(Environment.getExternalStorageDirectory(),  ("test"+".jpg"));
    if(!file.exists()){
        try {
            file.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }else{
        file.delete();
        try {
            file.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    capturedImageUri = Uri.fromFile(file);
    Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    i.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
    startActivityForResult(i, 2);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    // super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 2) {
        //Bitmap bitmap = (Bitmap) data.getExtras().get("data");
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), capturedImageUri);
            picture.setImageBitmap(bitmap);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

1 个答案:

答案 0 :(得分:0)

1)调用相机意图

private void picPhoto() {
    Intent pickIntent = new Intent();
    if (Build.VERSION.SDK_INT < 19) {
        pickIntent.setType("image/jpeg");
        pickIntent.setAction(Intent.ACTION_GET_CONTENT);
    } else {
        pickIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        pickIntent.addCategory(Intent.CATEGORY_OPENABLE);
        pickIntent.setType("image/jpeg");
    }
    Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, getFileDirectory());
    takePhotoIntent.putExtra("android.intent.extras.CAMERA_FACING", 1);
    String pickTitle = "Select or take a new Picture";
    Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);

    chooserIntent.putExtra
            (
                    Intent.EXTRA_INITIAL_INTENTS,
                    new Intent[]{takePhotoIntent}
            );

    startActivityForResult(chooserIntent, PICK_IMAGE);
}

2)方法getFileDirectory()

 private Uri getFileDirectory() {
    File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
    imagesFolder.mkdirs();
    File image = new File(imagesFolder, "MY_PROFILE_PIC.jpg");
    return Uri.fromFile(image);
}

3)OnActivityResult

  @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == Activity.RESULT_OK) {
        // If gallary intent is choosed this condition remain true

        if (requestCode == PICK_IMAGE && data != null && data.getData() != null) {



            Uri _uri = data.getData();
            //User had pick an image.
            Cursor cursor = getActivity().getContentResolver().query(_uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null);
            cursor.moveToFirst();
            //Link to the image
            final String imageFilePath = cursor.getString(0);
            editPhoto1.setImageBitmap(null);
            if (bmp != null) {
                bmp.recycle();
            }
            setImagePicked(imageFilePath, 1);
            cursor.close();
        } else {
       // If camera intent is choosed this condition remain true
            editPhoto1.setImageBitmap(null);
            if (bmp != null) {
                bmp.recycle();
            }
            setImagePicked(getFileDirectory().getPath(), 0);
        }
    }


    super.onActivityResult(requestCode, resultCode, data);
}

3)设置图像

  private void setImagePicked(String filePath, int status) {
    try {
        bmp = ImageResizer.decodeSampledBitmapFromFile(new File(filePath).getAbsolutePath(), 512, 342);                                                  

         /* This for rotating the image use if necessary */
        if (status == 0) {
            Matrix mMatrix = new Matrix();
            Matrix mat = editPhoto1.getImageMatrix();
            mMatrix.set(mat);
            mMatrix.setRotate(270);
            bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(),
                    bmp.getHeight(), mMatrix, false);
        }

        editPhoto1.setImageBitmap(bmp);
    } catch (Exception e) {
        Log.e("Exception Image Set :: ", e.getMessage());
    }
}

4)最后是图像缩放器类

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class ImageResizer {

 public static Bitmap decodeSampledBitmapFromFile(String filename,
        int reqWidth, int reqHeight) {
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options
            options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filename, options);
    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(filename, options);
}




public static int calculateInSampleSize(BitmapFactory.Options options,
        int reqWidth, int reqHeight) {
    // BEGIN_INCLUDE (calculate_sample_size)
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }

        // This offers some additional logic in case the image has a strange
        // aspect ratio. For example, a panorama may have a much larger
        // width than height. In these cases the total pixels might still
        // end up being too large to fit comfortably in memory, so we should
        // be more aggressive with sample down the image (=larger inSampleSize).

        long totalPixels = width * height / inSampleSize;

        // Anything more than 2x the requested pixels we'll sample down further
        final long totalReqPixelsCap = reqWidth * reqHeight * 2;

        while (totalPixels > totalReqPixelsCap) {
            inSampleSize *= 2;
            totalPixels /= 2;
        }
    }
    return inSampleSize;
    // END_INCLUDE (calculate_sample_size)
}

}