gpt4 book ai didi

Java 图像截断

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:23:43 24 4
gpt4 key购买 nike

与上次相同的问题,但我会提供更多细节。我目前正在使用以下方法旋转图像:

 int rotateNum //in main class

double rotationRequired = Math.toRadians(rotateNum);

double locationX = img.getWidth(this) / 2;
double locationY = img.getHeight(this) / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);


g2d.drawImage(op.filter((BufferedImage)img, null), imgX, imgY, null);

然后我实际上使用以下方法旋转图像:

double deltaX = (double)(imgY - otherImg.imgY);
double deltaY = (double)(imgX - otherImg.imgX);
rotateNum = (int)(180 * Math.atan2(deltaY, deltaX) / Math.PI);

我的图片大小不一。较小的图像不会被截断(意味着被空白截断),但较大的图像会在左侧或右侧截断。调整图像大小不起作用,我使用 GIMP.

示例图片:之前(忽略左边的灰色区域)

之后:看到侧面的切断

最佳答案

问题是您的源图像不是完全二次的。当您使用 at.rotate(-rad, width/2, height/2); 实现 AffineTransform 旋转时,它与:

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

希望对您有所帮助。

关于Java 图像截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8721312/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com