简体   繁体   中英

How to use bitmap factory to compress image without reduce the quality taken from camera?

I have 3 images taken from camera and I want to set to 3 ImageView. But it throws OutOfMemory because the image has large size. I've read that bitmap factory can compress the size without reducing the quality. The problem is I don't know how to do that.

This is my onClick Button:

openCameraButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    file = new File(Environment.getExternalStorageDirectory(),
                            "imagename.jpg");
                    outPutfileUri = Uri.fromFile(file);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, outPutfileUri);
                    startActivityForResult(intent,0);
                    dialog.cancel();
                }
            });

And this is my onActivityResult:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
        //result from camera
    try{
        if (requestCode==0 && resultCode==RESULT_OK){
            //bitmap = (Bitmap)data.getExtras().get("data");
            bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), outPutfileUri);
            drawable = new BitmapDrawable(getResources(), bitmap);
            imageSelfie.setImageDrawable(drawable);
        }
    } catch (Exception ignored){}}

Anyone can help me?

Use like this :

File file = new File(Environment.getExternalStorageDirectory(),"imagename.jpg");
fileDeleted = !file.exists() || file.delete();
if (fileDeleted) {
FileOutputStream out = new FileOutputStream(file);
if (imageToSave != null) {
imageToSave.compress(Bitmap.CompressFormat.JPEG, 65, out);
}}
out.flush();
out.close();

Instead of using the media store which tries to give you a full bitmap you better open an inputstream and load a resized bitmap from it.

InputStream is = getContentResolver().openInputStream(outPutfileUri);

Then use BitmapFactory.decodeStream() with an options parameter where you scale down the image several times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM