您不能裁剪更大的图像,只能更小。所以,你从目标维度开始,比如说100x100。而你的BufferedImage
(bi
),比方说150x50。
创建你的目标矩形:
Rectangle goal = new Rectangle(100, 100);
然后用你的图像的尺寸交叉处:
Rectangle clip = goal.intersection(new Rectangle(bi.getWidth(), bi.getHeight());
现在,夹对应,将适合你的目标内的bi
部分。在这种情况下100 x50。
现在使用clip
的值得到subImage
。
BufferedImage clippedImg = bi.subImage(clip,1, clip.y, clip.width, clip.height);
创建的goal
新BufferedImage
(bi2
),尺寸:
BufferedImage bi2 = new BufferedImage(goal.width, goal.height);
用白色填充它(或者你选择的背景色):
Graphics2D big2 = bi2.getGraphics();
big2.setColor(Color.white);
big2.fillRect(0, 0, goal.width, goal.height);
,并绘制裁剪图像。
int x = goal.width - (clip.width/2);
int y = goal.height - (clip.height/2);
big2.drawImage(x, y, clippedImg, null);
你不应该需要中间图像'clippedImg'。只要做一个'big2.drawImage(bi,(bi2.getWidth() - bi.getWidth())/ 2,(bi2.getHeight() - bi.getHeight())/ 2,null);' – 2010-08-16 19:14:23
感兴趣的部分是左上角。如果要将原始图像的顶部或左侧边缘剪下,它将不起作用。但是,您可能可以通过使用setClip在没有中间件的情况下执行此操作。但是我不得不考虑如何计算x和y。 – 2010-08-17 15:53:21
@Devon_C_Miller它如何工作bi.subImage(clip,1,clip.y,clip.width,clip.height); ,subImage方法需要4个参数(全部是Integer)? – user2556079 2015-10-07 10:25:34