java图像裁剪 [英] java image crop

查看:118
本文介绍了java图像裁剪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 BufferedImage.getSubimage 然而,它无法处理小于抛出异常的裁剪尺寸的裁剪图像:

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

java.awt.image.RasterFormatException: (y + height) is outside raster

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

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?

谢谢

推荐答案

您无法裁剪更大的图像,只能缩小图像。所以,你从目标维度开始,比方说100x100。你的 BufferedImage bi ),比方说150x50。

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.

创建一个目标矩形:

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());

现在,clip对应于 bi 中符合你目标的部分。在这种情况下为100 x50。

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

现在使用剪辑的值获取 subImage

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

创建一个新的 BufferedImage bi2 ),目标的大小

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

填写它用白色(或你选择的任何bg颜色):

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);

这篇关于java图像裁剪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆