0

I'm trying to write a method that takes a Bitmap and the crop values as parameters and returns the cropped Bitmap.

My code:

public Bitmap applyCrop(Bitmap bitmap, int leftCrop, int topCrop, int rightCrop, int bottomCrop) {
    return Bitmap.createBitmap(bitmap, leftCrop, topCrop, bitmap.getWidth() - rightCrop, bitmap.getHeight() - bottomCrop);
}

Using this code i'm receiving the following IllegalArgumentException:

java.lang.IllegalArgumentException: x + width must be <= bitmap.width()

What is wrong with my code?

2 Answers2

3

In case the Bitmap.createBitmap() is taking the size of crop image and not the coordinates of the second corner, You should do:

public Bitmap applyCrop(Bitmap bitmap, int leftCrop, int topCrop, int rightCrop, int bottomCrop) {
    int cropWidth = bitmap.getWidth() - rightCrop - leftCrop;
    int cropHeight = bitmap.getHeight() - bottomCrop - topCrop;
    return Bitmap.createBitmap(bitmap, leftCrop, topCrop, cropWidth, cropHeight);
}
Krzysztof Cichocki
  • 6,294
  • 1
  • 16
  • 32
-1

Here i have a sample for you. Use this

Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.abc);


//pass your bitmap here and give desired width and height
newBitmap=Bitmap.createBitmap(bitmap, 0,0,"GIVE WIDTH HERE", "GIVE HEIGHT HERE");

Let me know if this works! :)

New Coder
  • 873
  • 8
  • 14