如何在Java中裁剪图像的某些区域?
我正在尝试执行以下代码:
private void crop(HttpServletRequest request, HttpServletResponse response){
int x = 100;
int y = 100;
int w = 3264;
int h = 2448;
String path = "D:images\\upload_final\\030311175258.jpg";
BufferedImage image = ImageIO.read(new File(path));
BufferedImage out = image.getSubimage(x, y, w, h);
ImageIO.write(out, "jpg", new File(path));
}
但不断给我同样的错误:
java.awt.image.RasterFormatException: (x + width) is outside of Raster
sun.awt.image.ByteInterleavedRaster.createWritableChild(ByteInterleavedRaster.java:1230)
java.awt.image.BufferedImage.getSubimage(BufferedImage.java:1156)
我的错误在哪里?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我最初的猜测是你的
(x + w) > image.getWidth()。
如果打印出image.getWidth(),是3264吗? :O
你目前正在做的是这样的:
如果你想修剪掉原稿的顶角,并且只是得到“重叠”那么你需要做
如果你想这样做:
那么你需要做这:
My initial guess is that your
(x + w) > image.getWidth()
.If you print out image.getWidth(), is it 3264? :O
What you're currently doing is this:
If you're trying to trim off the top corner of orig, and just get "overlap" then you need to do
If you're trying to do this:
Then you need to do this:
对于那些只想在软件上进行裁剪和其他基本图像处理功能的人,我建议使用图像处理库。通常,实现是优化且稳定的。
一些Java图像处理库:ImageJ、马文,JMagick,JIU, JH 实验室,imgscalr。
另一个优点是让事情变得简单。只需几行代码就可以完成很多事情。在下面的示例中,我使用 Marvin Framework 进行裁剪。
原文:
裁剪:
来源:
For those who just want cropping and other basic image manipulation features on your software I recommend to use an image processing library. Usually the implementations are optimized and stable.
Some Java image processing libraries: ImageJ, Marvin, JMagick, JIU, JH Labs, imgscalr.
Another advantage is to keep things simple on your side. You can do a lot of things with just a few lines of code. In the example below, I used Marvin Framework for cropping.
Original:
Cropped:
Source: