从 jpeg 图像中剪裁多边形图像 Java

Clipping polygon image from jpeg image Java

伙计们!

我有一些问题。我需要从 jpg 图像中剪切一些多边形图像并保存。 此刻我用的是OpenSlideJNI.openslide_read_region,但是OpenSlide可以裁剪唯一的矩形。

你有什么想法吗?

基本代码为:

// load the image

BufferedImage originalImage = ImageIO.read(...);

// create the polygon

Polygon polygon = new Polygon();
polygon.addPoint(50, 50);
polygon.addPoint(150, 50);
polygon.addPoint(250, 150);
polygon.addPoint(150, 150);

Rectangle bounds = polygon.getBounds();

// create a transparent clipped image based on the bounds of the Polygon

BufferedImage clippedImage = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = clippedImage.createGraphics();

polygon.translate(-bounds.x, -bounds.y);
g.setClip(polygon);
g.drawImage(originalImage, -bounds.x, -bounds.y, null);

// save the clipped image

ImageIO.write(...);

当然图像仍然是矩形的,但非裁剪区域将是透明的。