Home » Android » android – cut the portion of bitmap

android – cut the portion of bitmap

Posted by: admin April 23, 2020 Leave a comment

Questions:

Possible Duplicate:
How to crop the parsed image in android?

I have selected a portion from the bitmap and i am copying the selected portion in the same bitmap.. Now i want to remove the selected portion after copying.. How to do it?? please help me out..

How to&Answers:

Easiest way I am aware of is to use XFer mode processing from the Graphics package. Function below cuts region starting from (30,30) till (100,100) to the 320×480 image loaded from resources. Adapt coordinates to change dynamically:

private Bitmap cropBitmap1() {
    Bitmap bmp2 = BitmapFactory.decodeResource(this.getResources(), R.drawable.image1); 
    Bitmap bmOverlay = Bitmap.createBitmap(320, 480, Bitmap.Config.ARGB_8888);

    Paint paint = new Paint();
    paint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));

    Canvas canvas = new Canvas(bmOverlay); 
    canvas.drawBitmap(bmp2, 0, 0, null); 
    canvas.drawRect(30, 30, 100, 100, paint);

    return bmOverlay;
}

Answer:

Just in case someone is trying to solve same problem, there is a better solution: Bitmap.createBitmap(Bitmap, int x, int y, int width, int height). For example, if you need to crop 10 pixels from each side of a bitmap then use this:

Bitmap croppedBitmap = Bitmap.createBitmap(originalBitmap, 10, 10, originalBitmap.getWidth() - 20, originalBitmap.getHeight() - 20);