Search code examples
javaimagecrop

Crop image based on X, Y coordinates in java


I want to crop my image using 4 XY coordinates in an image. I looked at BufferedImage 's getSubImage method as well however didnt find it useful for my requirement.

Any way to crop it using the 4 coordinates points (x1,y1), (x2,y2), (x3,y3), (x4,y4)


Solution

  • A rectangle in plane with sides parallel to axes can be characterized by two points : top left (x1, y1) and bottom right (x2, y2) corners. So just use getSubImage() appropriately :

    /*    
    (x1, y1) ....... (w = y2-y1) .. (x2, y1)
     .
     .                                 
     (h = y2-y1)                        
     .
     .
    (x1, y2) .......................(x2, y2)  */  
    
    BufferedImage myImaxe;
    myImage.getSubImage(x1, y1, (x2-x1), (y2-y1));