java 图像裁剪
我知道 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法将图像裁剪得更大,只能裁剪得更小。因此,您从目标尺寸开始,假设为 100x100。还有您的
BufferedImage
(bi
),假设为 150x50。创建目标的矩形:
然后将其与图像的尺寸相交:
现在,剪辑对应于适合您的目标的
bi
部分。在本例中为 100 x50。现在使用
clip
的值获取subImage
。创建一个新的
BufferedImage
(bi2
),其大小为goal
:用白色(或您选择的任何背景颜色)填充它:
并绘制将图像剪裁到其上。
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:
Then intersect it with the dimensions of your image:
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 ofclip
.Create a new
BufferedImage
(bi2
), the size ofgoal
:Fill it with white (or whatever bg color you choose):
and draw the clipped image onto it.