How to crop an image in android? [duplicate]

Solution 1:

From Bitmap.createBitmap: "Returns an immutable bitmap from the specified subset of the source bitmap. The new bitmap may be the same object as source, or a copy may have been made. It is initialized with the same density as the original bitmap."

Pass it a bitmap, and define the rectangle from which the new bitmap will be created.

// Take 10 pixels off the bottom of a Bitmap
Bitmap croppedBmp = Bitmap.createBitmap(originalBmp, 0, 0, originalBmp.getWidth(), originalBmp.getHeight()-10);

Solution 2:

The Android Contact manager EditContactActivity uses Intent("com.android.camera.action.CROP")

This is a sample code:

Intent intent = new Intent("com.android.camera.action.CROP");
// this will open all images in the Galery
intent.setDataAndType(photoUri, "image/*");
intent.putExtra("crop", "true");
// this defines the aspect ration
intent.putExtra("aspectX", aspectY);
intent.putExtra("aspectY", aspectX);
// this defines the output bitmap size
intent.putExtra("outputX", sizeX);
intent.putExtra("outputY", xizeY);
// true to return a Bitmap, false to directly save the cropped iamge
intent.putExtra("return-data", false);
//save output image in uri
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

Solution 3:

Try this:

ImageView ivPeakOver=(ImageView) findViewById(R.id.yourImageViewID);

Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.yourImageID);
int width=(int)(bmp.getWidth()*peakPercent/100);
int height=bmp.getHeight();

Bitmap resizedbitmap=Bitmap.createBitmap(bmp,0,0, width, height);
ivPeakOver.setImageBitmap(resizedbitmap);

From the Docs:

static Bitmap    createBitmap(Bitmap source, int x, int y, int width, int height)

Returns an immutable bitmap from the specified subset of the source bitmap.

Solution 4:

If you want to equally crop the outside of the image, you should check out the ScaleType attribute for an ImageView: http://developer.android.com/reference/android/widget/ImageView.ScaleType.html

In particular, you would be interested in the "centerCrop" option. It crops out part of the image that is larger than the defined size.

Here's an example of doing this in the XML layout:

<ImageView  android:id="@+id/title_logo"
            android:src="@drawable/logo"
            android:scaleType="centerCrop" android:padding="4dip"/>

Solution 5:

 int targetWidth = 100;
 int targetHeight = 100;
 RectF rectf = new RectF(0, 0, 100, 100);//was missing before update
 Bitmap targetBitmap = Bitmap.createBitmap(
 targetWidth, targetHeight,Bitmap.Config.ARGB_8888);
 Canvas canvas = new Canvas(targetBitmap);
 Path path = new Path();
 path.addRect(rectf, Path.Direction.CW);
 canvas.clipPath(path);
 canvas.drawBitmap(
 sourceBitmap,
 new Rect(0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight()),
 new Rect(0, 0, targetWidth, targetHeight),
 null);
 ImageView imageView = (ImageView)findViewById(R.id.my_image_view);
 imageView.setImageBitmap(targetBitmap);