如何在android中压缩图像

时间:2013-11-19 18:07:28

标签: android android-layout android-intent

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

我的应用程序使用intent从图库中选择照片,并将照片设置为布局的背景,当我选择一个小像素的照片时,这可以正常工作,从相机拍摄的位照片不适合屏幕。

如何压缩照片或图像。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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