问题是您的源图像不完全是二次的。当您使用 实现 AffineTransform 旋转时at.rotate(-rad, width/2, height/2);
,它与以下内容相同:
at.translate(width/2,height/2);
at.rotate(rads);
at.translate(-width/2,-height/2);
因此,当它执行最后一行时,它会转换为原点。如果宽度大于 y(反之亦然),则变换的原点将被转换为比长度更大的一侧更小的距离。
例如,如果您的宽度为 30,高度为 60,则原点将设置为 (-15,-30),从原来的变换设置。所以,当你翻译它时,比如说,90度,图像最终会得到“宽度”60和“高度”30,但是根据原点,图像原始底部将被绘制在(-30,0),所以它在 X 轴上溢出了 -15 的 AffineTransform。然后这部分图像将被剪切。
要更正此问题,您可以改用以下代码:
double degreesToRotate = 90;
double locationX =bufferedImage.getWidth() / 2;
double locationY = bufferedImage.getHeight() / 2;
double diff = Math.abs(bufferedImage.getWidth() - bufferedImage.getHeight());
//To correct the set of origin point and the overflow
double rotationRequired = Math.toRadians(degreesToRotate);
double unitX = Math.abs(Math.cos(rotationRequired));
double unitY = Math.abs(Math.sin(rotationRequired));
double correctUx = unitX;
double correctUy = unitY;
//if the height is greater than the width, so you have to 'change' the axis to correct the overflow
if(bufferedImage.getWidth() < bufferedImage.getHeight()){
correctUx = unitY;
correctUy = unitX;
}
int posAffineTransformOpX = posX-(int)(locationX)-(int)(correctUx*diff);
int posAffineTransformOpY = posY-(int)(locationY)-(int)(correctUy*diff);
//translate the image center to same diff that dislocates the origin, to correct its point set
AffineTransform objTrans = new AffineTransform();
objTrans.translate(correctUx*diff, correctUy*diff);
objTrans.rotate(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(objTrans, AffineTransformOp.TYPE_BILINEAR);
// Drawing the rotated image at the required drawing locations
graphic2dObj.drawImage(op.filter(bufferedImage, null), posAffineTransformOpX, posAffineTransformOpY, null);
希望它有所帮助。