如何在Java中裁剪一些图像区域?

时间:2011-03-03 21:11:04

标签: java image-processing crop

我正在尝试执行以下代码:

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)

我的错误在哪里?

2 个答案:

答案 0 :(得分:33)

我最初的猜测是你的(x + w) > image.getWidth()

如果你打印出image.getWidth(),它是3264吗? :o

您目前正在做的是:

<-- 3264 ------>
+--------------+
|    orig      | +-- Causing the problem
|              | V
|   +--------------+
|100| overlap  |   |
|   |          |   |
|   |          |   |
+---|----------+   |
    |              |
    |    out       |
    +--------------+

如果你试图修剪orig的顶角,只是得到“重叠”,那么你需要做

BufferedImage out = image.getSubimage(x, y, w-x, h-y);

如果你想这样做:

+------------------+
|                  |
|  +-----------+   |
|  |           |   |
|  |           |   |
|  |           |   |
|  |           |   |
|  +-----------+   |
|                  |
+------------------+

然后你需要这样做:

BufferedImage out = image.getSubimage(x, y, w-2*x, h-2*y);

答案 1 :(得分:5)

对于那些只想在您的软件上进行裁剪和其他基本图像处理功能的人,我建议使用图像处理库。通常,实现是优化和稳定的。

一些Java图像处理库:ImageJMarvinJMagickJIUJH Labsimgscalr

另一个优点是让事情变得简单。只需几行代码即可完成许多工作。在下面的示例中,我使用Marvin Framework进行裁剪。

<强>原始
enter image description here

<强>裁切后:
enter image description here

<强>来源:

MarvinImage image = MarvinImageIO.loadImage("./res/famousFace.jpg");
crop(image.clone(), image, 60, 32, 182, 62);
MarvinImageIO.saveImage(image, "./res/famousFace_cropped.jpg");