2

by using Canvas and JS I can draw a shape like this and have the x,y of each point : enter image description here

Tha area can be choosen by more than 4 points, look at this link to have an idea.

I need to save and crop the image of the selected area by using the points. I can not use BufferedImage as it is just rectangular. Which lib in java I can use?

Majico
  • 3,810
  • 2
  • 24
  • 36
  • Well, the image is always s going to be rectangular, you could use the points to generate a shape and use them to generate a clipping area to paint the image into, but as I said, the result will always be a rectangular image, just with what you've selected and what ever background color you've decided to use – MadProgrammer Apr 21 '17 at 11:12

1 Answers1

3

Okay, so starting with...

Your original image

I used...

BufferedImage source = ImageIO.read(new File("Example.jpg"));
GeneralPath clip = new GeneralPath();
clip.moveTo(65, 123);
clip.lineTo(241, 178);
clip.lineTo(268, 405);
clip.lineTo(145, 512);
clip.closePath();

Rectangle bounds = clip.getBounds();
BufferedImage img = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
clip.transform(AffineTransform.getTranslateInstance(-65, -123));
g2d.setClip(clip);
g2d.translate(-65, -123);
g2d.drawImage(source, 0, 0, null);
g2d.dispose();

ImageIO.write(img, "png", new File("Clipped.png"));

to generate...

Clipped

Now, the image is rectangular, that's just the way it works

Now, setClip is quite rough and isn't effect by any RenderingHints, you could make use of "soft clipping" instead, which is more involved, but generates a nicer results. See this example and this exmaple for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Thank you, but What if I choose 5 or 6 points instead of 4, on that case i can not use "Rectangle" bounds! – Majico Apr 21 '17 at 13:27
  • Look at this to see what it might happen if you choose more than 4 points : http://www.jqueryrain.com/?FahE34Ft – Majico Apr 21 '17 at 13:34
  • @Majico You can use as many points as you like and still use `getBounds`, but you might want to look into `Rectangle#getMinX/Y` and `Rectangle#getMaxX/Y` – MadProgrammer Apr 21 '17 at 22:02
  • Thanks for your complate solution, it works like a charm! :) – Majico Apr 27 '17 at 08:11