java java图像裁剪

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3495566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:06:22  来源:igfitidea点击:

java image crop

javaimage-manipulation

提问by James moore

I am aware of BufferedImage.getSubimageHowever, it cant deal with cropping images that are smaller than the cropping size throwing the exception:

我知道BufferedImage.getSubimage但是,它无法处理小于引发异常的裁剪尺寸的裁剪图像:

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?

我希望能够将 PNG/JPG/GIF 裁剪为特定大小,但是如果图像小于裁剪区域在白色背景上的中心。有没有呼吁这样做?或者我是否需要手动创建图像以将图像居中,如果是这样,我将如何处理?

Thanks

谢谢

回答by Devon_C_Miller

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.

您不能将图像裁剪得更大,只能更小。所以,你从目标尺寸开始,比如 100x100。还有你的BufferedImage( bi),比如说 150x50。

Create a rectangle of your goal:

创建一个矩形的目标:

Rectangle goal = new Rectangle(100, 100);

Then intersect it with the dimensions of your image:

然后将其与图像的尺寸相交:

Rectangle clip = goal.intersection(new Rectangle(bi.getWidth(), bi.getHeight());

Now, clip corresponds to the portion of bithat will fit within your goal. In this case 100 x50.

现在,剪辑对应于bi适合您目标的部分。在本例中为 100 x50。

Now get the subImageusing the value of clip.

现在获取subImageusing 的值clip

BufferedImage clippedImg = bi.subImage(clip,1, clip.y, clip.width, clip.height);

Create a new BufferedImage(bi2), the size of goal:

创建一个新的BufferedImage( bi2),大小为goal

BufferedImage bi2 = new BufferedImage(goal.width, goal.height);

Fill it with white (or whatever bg color you choose):

用白色(或您选择的任何背景颜色)填充它:

Graphics2D big2 = bi2.getGraphics();
big2.setColor(Color.white);
big2.fillRect(0, 0, goal.width, goal.height);

and draw the clipped image onto it.

并将剪下的图像绘制到其上。

int x = goal.width - (clip.width / 2);
int y = goal.height - (clip.height / 2);
big2.drawImage(x, y, clippedImg, null);