繁体   English   中英

如何在Android中压缩图像

[英]How to compress an image in android

如何在Android应用程序中压缩图像。

我的应用程序使用意图从图库中选择照片,并将照片设置为布局的背景。当我选择小像素照片(从相机拍摄的位照片不适合屏幕)时,此方法效果很好。

如何压缩照片或图像。

使用以下意图从图库中获取所需尺寸的图像。

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

在运行时测量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;
        }
    });

创建具有上述宽度和高度的图像

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

图像设置ImageView

mUserPicImageView.setImageBitmap(scaledBitmap);

暂无
暂无

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

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