Android - how to compress or reduce image?

ImageButton avatarButton = (ImageButton) findViewById(R.id.ImageButton_Avatar); avatarButton.setImageResource(R.drawable.avatar); strAvatarFilename = "Image.jpg"; final Uri imageUriToSaveCameraImageTo = Uri.fromFile(new File(Environment.getExternalStorageDirectory()+"/Folder/"+strAvatarFilename)); avatarButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent pictureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); pictureIntent.putExtra( MediaStore.EXTRA_OUTPUT, imageUriToSaveCameraImageTo ); startActivityForResult(Intent.createChooser(pictureIntent, strAvatarPrompt), TAKE_AVATAR_CAMERA_REQUEST); Editor editor = Preferences.edit(); editor.putString(PREFERENCES_AVATAR, imageUriToSaveCameraImageTo.getPath()); editor.commit(); } }); 

I have this code. He takes a photo and then saves it in two places, by default on the SD card and in / folder / file I want the photo to be saved as well. After that, I refresh the screen using this ...

 ImageButton avatarButton = (ImageButton) findViewById(R.id.ImageButton_Avatar); String strAvatarUri = Preferences.getString(PREFERENCES_AVATAR, ""); Uri imageUri = Uri.parse(strAvatarUri); avatarButton.setImageURI(null); avatarButton.setImageURI(imageUri); 

This updates the image button so that the user can see the image they made. However, it looks very large and fills the screen. Is there a way to compress or reduce the image so that the user can see it with a reasonable size? thanks

+4
source share
3 answers

You can use the ImageButton scaleType scaling properties (e.g. fitXY or cropCenter), as well as setting a fixed size in LayoutPreferences (height and width). You will be tuned.

+1
source
 Bitmap thumb = Bitmap.createScaledBitmap (BitmapFactory.decodeFile(photoPath), 96, 96, false); 

If the second and third createScaledBitmap parameters are width and height, respectively.

http://developer.android.com/reference/android/graphics/Bitmap.html#createScaledBitmap%28android.graphics.Bitmap,%20int,%20int,%20boolean%29

EDIT: Now it occurred to me that you can do it faster and more efficiently using the B options itmapFactory.Options and inSampleSize :

 BitmapFactory.Options opts = new BitmapFactory.Options (); opts.inSampleSize = 2; // for 1/2 the image to be loaded Bitmap thumb = Bitmap.createScaledBitmap (BitmapFactory.decodeFile(photoPath, opts), 96, 96, false); 

This way you will save even more memory, and the reduction should take less time.

+17
source

SiliCompressor Android Library provides this feature to compress your images while maintaining image quality.

0
source

Source: https://habr.com/ru/post/913386/


All Articles