简体   繁体   中英

Android - how to compress or downsize an 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. It takes a photo and then stores it in two locations, the default location on the SDcard and the /folder/ file i want the photo to be stored in also. Once taken 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 refreshes the image button so the user can see the image they have taken. However, this is appears very big and fills the screen. Is there any way i can compress or downsize the image so the user can see it at a reasonable size? thanks

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

Where the second and third parameters to createScaledBitmap are the width and height respectively.

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

EDIT: It now occurred to me that you can do this in a faster, more efficient way, using B itmapFactory.Options and the inSampleSize option:

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 downsizing should take less time.

你可以搞乱ImageButton的scaleType属性(例如fitXY,或cropCenter),通过设置一个固定大小到LayoutPreferences(高度和宽度),你将全部设置。

Android Library SiliCompressor为您提供此功能,可在保持图像质量的同时压缩图像。

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