简体   繁体   English

如何在Android中压缩图像

[英]How to compress an image in android

How to compress the image in android application. 如何在Android应用程序中压缩图像。

My application selects photo from gallery using intent and sets the photo as background for the layout,This works fine when i select a photo of small pixel,bit photo taken from camera it does not fit the screen. 我的应用程序使用意图从图库中选择照片,并将照片设置为布局的背景。当我选择小像素照片(从相机拍摄的位照片不适合屏幕)时,此方法效果很好。

how to compress the photo or image. 如何压缩照片或图像。

Use following intent to get image of required size from Gallery. 使用以下意图从图库中获取所需尺寸的图像。

         Intent photoPickerIntent = new Intent(
                        Intent.ACTION_PICK,
                         android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                // photoPickerIntent.setType("image/*");
                photoPickerIntent.putExtra("crop", "true");
                photoPickerIntent.putExtra("outputX", 512);
                photoPickerIntent.putExtra("outputY", 512);
                photoPickerIntent.putExtra("aspectX", 1);
                photoPickerIntent.putExtra("aspectY", 1);
                photoPickerIntent.putExtra("scale", true);
                File f = new File(android.os.Environment
                        .getExternalStorageDirectory(), "tt.jpg");
                // imgpath=f.getAbsolutePath();
                System.err.println("Path$$$$$$$$$ " + f.getAbsolutePath());
                photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(f));
                photoPickerIntent.putExtra("outputFormat",
                        Bitmap.CompressFormat.PNG.toString());
                startActivityForResult(photoPickerIntent, SELECT_FILE);

To measure the width and height of your Imageview at run time 在运行时测量Imageview的宽度和高度

ViewTreeObserver vto = mUserPicImageView.getViewTreeObserver();
    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        public boolean onPreDraw() {

            if (mImageHeight == 0) {
                mImageHeight = mUserPicImageView.getMeasuredHeight();
                mImageWidth = mUserPicImageView.getMeasuredWidth();
                Log.e("mImageHeight", mImageHeight + "");

            }
            return true;
        }
    });

Create image of the above width and height 创建具有上述宽度和高度的图像

 Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap,mImageHeight,mImageWidth, true);

Set the image to ImageView 图像设置ImageView

mUserPicImageView.setImageBitmap(scaledBitmap);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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