从jpeg图像Java剪切多边形图像

时间:2016-05-18 11:16:11

标签: java image-clipping

人!

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

你有什么想法吗?

1 个答案:

答案 0 :(得分:2)

基本代码是:

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

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