Crop a Bitmap image

AndroidCropImage Editing

Android Problem Overview


How can i crop a bitmap image? this is my question i have tried some concepts using intents but still fail..

I am having a bitmap image which i want to crop!!

here is the code :

 Intent intent = new Intent("com.android.camera.action.CROP");  
					  intent.setClassName("com.android.camera", "com.android.camera.CropImage");  
					  File file = new File(filePath);  
					  Uri uri = Uri.fromFile(file);  
					  intent.setData(uri);  
					  intent.putExtra("crop", "true");  
					  intent.putExtra("aspectX", 1);  
					  intent.putExtra("aspectY", 1);  
					  intent.putExtra("outputX", 96);  
					  intent.putExtra("outputY", 96);  
					  intent.putExtra("noFaceDetection", true);  
					  intent.putExtra("return-data", true);                                  
					  startActivityForResult(intent, REQUEST_CROP_ICON);

Could anybody help me regarding this @Thanks

Android Solutions


Solution 1 - Android

I used this method to crop the image and it works perfect:

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.xyz);

Bitmap resizedBmp = Bitmap.createBitmap(bmp, 0, 0, yourwidth, yourheight);

createBitmap() takes bitmap, start X, start Y, width & height as parameters.

Solution 2 - Android

Using the answer above does not work if you want to slice/crop areas particular out of bounds! Using this code you will always get your desired size - even if the source is smaller.

//  Here I want to slice a piece "out of bounds" starting at -50, -25
//  Given an endposition of 150, 75 you will get a result of 200x100px
Rect rect = new Rect(-50, -25, 150, 75);  
//  Be sure that there is at least 1px to slice.
assert(rect.left < rect.right && rect.top < rect.bottom);
//  Create our resulting image (150--50),(75--25) = 200x100px
Bitmap resultBmp = Bitmap.createBitmap(rect.right-rect.left, rect.bottom-rect.top, Bitmap.Config.ARGB_8888);
//  draw source bitmap into resulting image at given position:
new Canvas(resultBmp).drawBitmap(bmp, -rect.left, -rect.top, null);

...and you're done!

Solution 3 - Android

I had similar problem with cropping and after trying numerous approaches I figured out this one which made sense to me. This method only crops the image to square shape, I am still working on the circular shape (Feel free to modify the code to get shape you need).

So, first you have yout bitmap that you want to crop:

Bitmap image; //you need to initialize it in your code first of course

The image information is stored in an int [ ] array what is nothing more than an array of integers containing the color value of each pixel, starting at the top left corner of the image with index 0 and ending at the bottom right corner with index N. You can obtain this array with Bitmap.getPixels() method which takes various arguments.

We need the square shape, therefore we need to shorten the longer of the sides. Also, to keep the image centered the cropping needs to be done at the both sides of the image. Hopefully the image will help you understand what I mean. Visual representation of the cropping. The red dots in the image represent the initial and final pixels that we need and the variable with the dash is numerically equal to the same variable without the dash.

Now finally the code:

int imageHeight = image.getHeight(); //get original image height
int imageWidth = image.getWidth();  //get original image width
int offset = 0;

int shorterSide = imageWidth < imageHeight ? imageWidth : imageHeight;
int longerSide = imageWidth < imageHeight ? imageHeight : imageWidth;
boolean portrait = imageWidth < imageHeight ? true : false;  //find out the image orientation
//number array positions to allocate for one row of the pixels (+ some blanks - explained in the Bitmap.getPixels() documentation)
int stride = shorterSide + 1; 
int lengthToCrop = (longerSide - shorterSide) / 2; //number of pixel to remove from each side 
//size of the array to hold the pixels (amount of pixels) + (amount of strides after every line)
int pixelArraySize = (shorterSide * shorterSide) + (shorterImageDimension * 1);
int pixels = new int[pixelArraySize];

//now fill the pixels with the selected range 
image.getPixels(pixels, 0, stride, portrait ? 0 : lengthToCrop, portrait ? lengthToCrop : 0, shorterSide, shorterSide);

//save memory
image.recycle();

//create new bitmap to contain the cropped pixels
Bitmap croppedBitmap = Bitmap.createBitmap(shorterSide, shorterSide, Bitmap.Config.ARGB_4444);
croppedBitmap.setPixels(pixels, offset, 0, 0, shorterSide, shorterSide);

//I'd recommend to perform these kind of operations on worker thread
listener.imageCropped(croppedBitmap);

//Or if you like to live dangerously
return croppedBitmap;

Solution 4 - Android

For cropping bitmap with given width from left and right side simply use this code

int totalCropWidth = "your total crop width"; int cropingSize = totalCropWidth / 2; Bitmap croppedBitmap = Bitmap.createBitmap(yourSourceBitmap, cropingSize ,0,yourSourceBitmapwidth-totalCropWidth , yourheight);

Solution 5 - Android

I extend @sankettt's method, when you want to scale down a large bitmap and crop it fit with your ImageView size

use this method:

/**
 * crop a img with new expected size
 * @param src
 * @param newSize
 * @return
 */
public static Bitmap scaleAndGenerateBmpWithNewSize(Bitmap src, SizeManager newSize) {
    Bitmap bitmapRes;
    int imageWidth = src.getWidth();
    int imageHeight = src.getHeight();

    float newWidth = newSize.width;
    float scaleFactor = newWidth / imageWidth;
    int newHeight = (int) (imageHeight * scaleFactor);
    bitmapRes = Bitmap.createScaledBitmap(src, (int) newWidth, newHeight, true);
    bitmapRes = Bitmap.createBitmap(bitmapRes, 0, 0, (int) newWidth, (int) newSize.height);
    return bitmapRes;
}

SizeManager class:

public class SizeManager {
    public float width;
    public float height;

    public SizeManager() {
    }

    public SizeManager(float width, float height) {
        this.width = width;
        this.height = height;
    }

    public void set(float width, float height) {
        this.width = width;
        this.height = height;
    }

    public float getWidth() {
        return width;
    }

    public void setWidth(float width) {
        this.width = width;
    }

    public float getHeight() {
        return height;
    }

    public void setHeight(float height) {
        this.height = height;
    }
}

Usage:

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.src);
imgView.setImageBitmap(scaleAndGenerateBmpWithNewSize(bitmap, new SizeManager(100, 100)));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2134412View Question on Stackoverflow
Solution 1 - AndroidsanketttView Answer on Stackoverflow
Solution 2 - AndroidcoyerView Answer on Stackoverflow
Solution 3 - AndroidPeter PalkaView Answer on Stackoverflow
Solution 4 - AndroidVajani KishanView Answer on Stackoverflow
Solution 5 - AndroiddotrinhView Answer on Stackoverflow