在Java中按多边形区域裁剪图像 [英] Crop image by polygon area in Java

查看:67
本文介绍了在Java中按多边形区域裁剪图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过使用Canvas和JS,我可以绘制这样的形状并具有每个点的x,y:



Tha区域可以选择4点以上,请查看此



我用过...

  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();

矩形边界= clip.getBounds();
BufferedImage img =新的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,新File( Clipped.png));

生成...



< a href = https://i.stack.imgur.com/58KBL.png rel = nofollow noreferrer>



现在,图像为矩形,这就是它的工作方式



现在, setClip 相当粗糙,不受任何 RenderingHints 的影响,您可以使用软剪辑 ,它会涉及更多的内容,但会产生更好的结果。参见此示例此示例了解详情


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

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?

解决方案

Okay, so starting with...

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...

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

这篇关于在Java中按多边形区域裁剪图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆