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

不想你离开。 提交于 2019-12-11 11:54:33

问题


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?


回答1:


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();



回答2:


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.



来源:https://stackoverflow.com/questions/50344081/how-to-use-bitmap-factory-to-compress-image-without-reduce-the-quality-taken-fro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!