java 图像裁剪

发布于 2024-09-14 09:37:15 字数 267 浏览 3 评论 0原文

我知道 BufferedImage.getSubimage 但是,它无法处理小于裁剪尺寸的裁剪图像并抛出异常:

java.awt.image.RasterFormatException: (y + height) is outside raster

我希望能够将 PNG/JPG/GIF 裁剪到一定的大小但是,如果图像小于白色背景上的裁剪区域中心。有要求这样做吗?或者我是否需要手动创建图像以使图像居中,如果是这样,我将如何处理?

谢谢

I am aware of BufferedImage.getSubimage However, it cant deal with cropping images that are smaller than the cropping size throwing the exception:

java.awt.image.RasterFormatException: (y + height) is outside raster

I want to be able to crop either a PNG/JPG/GIF to a certain size however if the image is smaller than the cropping area centre itself on a white background. Is there a call to do this? Or do I need to create an image manually to centre the image on if so, how would I go about this?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笑,眼淚并存 2024-09-21 09:37:15

您无法将图像裁剪得更大,只能裁剪得更小。因此,您从目标尺寸开始,假设为 100x100。还有您的 BufferedImage (bi),假设为 150x50。

创建目标的矩形:

Rectangle goal = new Rectangle(100, 100);

然后将其与图像的尺寸相交:

Rectangle clip = goal.intersection(new Rectangle(bi.getWidth(), bi.getHeight());

现在,剪辑对应于适合您的目标的 bi 部分。在本例中为 100 x50。

现在使用 clip 的值获取 subImage

BufferedImage clippedImg = bi.subImage(clip,1, clip.y, clip.width, clip.height);

创建一个新的 BufferedImage (bi2),其大小为 goal

BufferedImage bi2 = new BufferedImage(goal.width, goal.height);

用白色(或您选择的任何背景颜色)填充它:

Graphics2D big2 = bi2.getGraphics();
big2.setColor(Color.white);
big2.fillRect(0, 0, goal.width, goal.height);

并绘制将图像剪裁到其上。

int x = goal.width - (clip.width / 2);
int y = goal.height - (clip.height / 2);
big2.drawImage(x, y, clippedImg, null);

You cannot crop an image larger, only smaller. So, you start with the goal dimension,let's say 100x100. And your BufferedImage (bi), let's say 150x50.

Create a rectangle of your goal:

Rectangle goal = new Rectangle(100, 100);

Then intersect it with the dimensions of your image:

Rectangle clip = goal.intersection(new Rectangle(bi.getWidth(), bi.getHeight());

Now, clip corresponds to the portion of bi that will fit within your goal. In this case 100 x50.

Now get the subImage using the value of clip.

BufferedImage clippedImg = bi.subImage(clip,1, clip.y, clip.width, clip.height);

Create a new BufferedImage (bi2), the size of goal:

BufferedImage bi2 = new BufferedImage(goal.width, goal.height);

Fill it with white (or whatever bg color you choose):

Graphics2D big2 = bi2.getGraphics();
big2.setColor(Color.white);
big2.fillRect(0, 0, goal.width, goal.height);

and draw the clipped image onto it.

int x = goal.width - (clip.width / 2);
int y = goal.height - (clip.height / 2);
big2.drawImage(x, y, clippedImg, null);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文