BufferedImage getSubimage以看似好的参数抛出异常

时间:2018-05-03 13:57:33

标签: java bufferedimage

Java 8在这里。试图坚持使用BufferedImage API,而不是深入研究JavaFx。

我的JPG图像宽768像素,高432像素。我想使用BufferedImage#getSubimage(...)从中心裁剪居中 400x400像素的方块。

我有以下代码:

BufferedImage image = ImageIO.read(imageTempFile);

int dim = 400;
int xCropBuffer, yCropBuffer;
xCropBuffer = (image.getWidth() - dim) / 2;
yCropBuffer = (image.getHeight() - dim) / 2;

log.info("width = " + image.getWidth() + ", height = " + image.getHeight() + ", dim = " + dim + ", xCropBuffer = " + xCropBuffer + ", yCropBuffer = " + yCropBuffer);

image = image.getSubimage(xCropBuffer, yCropBuffer + dim, dim, dim);

在运行时,会抛出以下异常:

java.awt.image.RasterFormatException: (y + height) is outside of Raster
    at sun.awt.image.ByteInterleavedRaster.createWritableChild(ByteInterleavedRaster.java:1248)
    at java.awt.image.BufferedImage.getSubimage(BufferedImage.java:1202)
    at java_awt_image_BufferedImage$getSubimage.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:149)
    at com.myapp.DefaultMediaService.uploadImage(DefaultMediaService.java:56)
    at com.myapp.MediaService$uploadImage.call(Unknown Source)

日志会在抛出异常之前打印以下消息:

width = 768, height = 432, dim = 400, xCropBuffer = 184, yCropBuffer = 16

所以我传递了image.getSubimage(184, 416, 400, 400)个论点......这不应该没问题吗?!图像是768x432,因此(184,416)应该是其左上角的有效坐标,并且184 + 400< 768和416-400>所以这些参数应该映射到图像中有效的400x400矩形,对吗?

2 个答案:

答案 0 :(得分:2)

绘制图像与绘制文本不同,其中提升从基线到较小的y坐标。图像由其左上角指定,并向x和y两者的较大坐标延伸。因此,您不应为y坐标指定+ dim

BufferedImage oldImage = ImageIO.read(imageFile),
    newImage = oldImage.getSubimage(
        (oldImage.getWidth()-dim)/2, (oldImage.getHeight()-dim)/2, dim, dim);
ImageIO.write(newImage, "png", imageFile);

为了完整性,由于您在上一个问题中似乎存在一些混淆,这里有一些替代方法可以实现相同的图像转换,可以用作其他图像操作的模板:

  • 通过BufferedImageOp

    BufferedImage oldImage = ImageIO.read(imageFile),
        newImage = new BufferedImage(dim, dim, oldImage.getType());
    BufferedImageOp op = new AffineTransformOp(
        AffineTransform.getTranslateInstance(
            -(oldImage.getWidth()-dim)/2, -(oldImage.getHeight()-dim)/2),
        AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    op.filter(oldImage, newImage);
    ImageIO.write(newImage, "png", imageFile);
    
  • 通过Graphics

    BufferedImage oldImage = ImageIO.read(imageFile),
        newImage = new BufferedImage(dim, dim, oldImage.getType());
    Graphics2D gfx = newImage.createGraphics();
    gfx.drawImage(oldImage,
                  -(oldImage.getWidth()-dim)/2, -(oldImage.getHeight()-dim)/2, null);
    gfx.dispose();
    ImageIO.write(newImage, "png", imageFile);
    

在任何一种情况下,通过使目标图像小于原始图像来暗示裁剪到所需尺寸。 然后,源图像只需通过(-x,-y)转换以选择所需的细节矩形。

答案 1 :(得分:0)

这看起来很简单。高度为432,您将左上角指定为(182,416)。接下来,你要求它下降400像素。所以你得到432< 416 + 400表示您要选择的帧的底部大于图像的高度。