如何以相同的意图从相机获取全尺寸照片和缩略图

时间:2015-08-17 05:17:42

标签: android thumbnails filepath android-camera-intent

我一直需要为这个问题找到解决方案。我已经搜索并测试过这个社区的许多解决方案,但是任何人都适合帮助我。

我有两个活动,第一个拍照并将其发送到另一个有ImageView接收它(直到这里我遇到问题)和一个查询以在数据库中插入文件路径(做最后一部分的代码很好。)

我认为View更适合将图像低分辨率加载为缩略图。因此,要保存到数据库中,我想从全尺寸图片中获取整个路径。

是否可能图像必须位于特定目录中,我可以选择给定函数参数的名称。

也许任何人都知道如何自动设置相机的最小分辨率。

2 个答案:

答案 0 :(得分:1)

如果您想拥有完整大小的图片,则需要在Intent的额外数据上提供URI。这样做,不会返回缩略图,因此您需要生成自己的缩略图。

要修改第二个Activity,您可以使用第二个Activity的onResume()方法,使用数据库中保存的路径更新ImageView;只是一定要确认它不是空的。

public static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;

private boolean hasCamera(){
    return getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
}

public void takePicture(){

    // Check if there is a camera.
    if(!hasCamera())
    {
        Toast.makeText(getActivity(), "This device does not have a camera.", Toast.LENGTH_SHORT).show();
        return;
    }

    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    //TODO: Set this to the path you want to save, 
    //you can use Environment.getExternalStorageDirectory() 
    //and a TimeStamp to generate an unique name
    //Save the path to your DB
    Uri exampleUri  = Uri.parse("file:///sdcard/photo.jpg");
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, exampleUri);
    startActivityForResult(takePictureIntent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}



@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
    {
        if (resultCode == RESULT_OK)
        {
            // Image captured and saved to fileUri specified in the Intent
            Toast.makeText(this, "Image saved", Toast.LENGTH_LONG).show();

           //If you no use onResume(); to update the ImageView
           //Another way is calling here your method for update the ImageView
           //with the path of your DB
        }
        else
        {
            if (resultCode == RESULT_CANCELED)
            {
                // User cancelled the image capture
                // So need to Delete the path from DB
            }
        }
    }

生成缩略图的简便方法:

Bitmap thumbImage = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(imagePath), THUMBSIZE, THUMBSIZE);
imageView.setImageBitmap(thumbImage);

答案 1 :(得分:1)

使用camera意图

获取完整尺寸图片和缩略图的示例

首先声明一个按钮拍照...

Button takePhoto = (Button) findViewById(R.id.btn_takePhoto);
        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, 1);
            }
        });

然后在onActivityResult我们获取数据......

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

        if(requestCode == 1 && resultCode == Activity.RESULT_OK){

                //path from full size image
                Cursor cursor = MyActivity.this.getContentResolver().query(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{
                                MediaStore.Images.Media.DATA,
                                MediaStore.Images.Media.DATE_ADDED,
                                MediaStore.Images.ImageColumns.ORIENTATION
                        },
                        MediaStore.Images.Media.DATE_ADDED,
                        null,
                        "date_added DESC");

                Bitmap fullsize;
                if (cursor != null && cursor.moveToFirst()) {
                    Uri uri = Uri.parse(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)));
                    String photoPath = uri.toString();
                    cursor.close();
                    if (photoPath != null) {
                        System.out.println("path: "+photoPath); //path from image full size
                        fullsize = decodeSampledBitmap(photoPath);//here is the bitmap of image full size
                    }
                }

                // do whatever you want with the Bitmap .... fullsize


                // thumbnail
                Bitmap thumbnail;
                thumbnail = (Bitmap) data.getExtras().get("data");
                // do whatever you want with the Bitmap .... thumbnail
            }
        }

对于内存泄漏,请使用此功能

private int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // 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;
            }
        }

        return inSampleSize;
    } 



private Bitmap decodeSampledBitmap(String pathName,
                                   int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(pathName, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFile(pathName, options);
}

//I added this to have a good approximation of the screen size:
private Bitmap decodeSampledBitmap(String pathName) {
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    int height = size.y;
    return decodeSampledBitmap(pathName, width, height);
}

注意: decodeSampledBitmap是一个更好的内存泄漏性能的函数,比如当你得到OOM(内存不足)时....

Loading Large Bitmaps Efficiently