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

2022-09-02 03:20:14

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

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)

我的错误在哪里?


答案 1

我最初的猜测是你的.(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);

答案 2

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

一些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");

推荐