1

我有不同尺寸的文档图像,我希望能够以以下方式有效地缩放和旋转它们(标准“旋转”和“缩放”逻辑)。我该怎么做?

图像高 H 像素,宽 W 像素。最初,它应该缩放到 600 像素宽。每次旋转时,面板的宽度和高度应交换,缩放后的图像应旋转 90 度。在每次缩放时,图像应按“比例”因子缩放。

这是我迄今为止尝试过的BufferedImage img……结果 BufferedImage 缩放和旋转但不平移(旋转 90 度后在面板顶部居中):

double scale = zoom * 600.0 / img.getWidth();
rotation = (rotation + degrees) % 360;
int scaledWidth = (int)(scale * img.getWidth());
int scaledHeight = (int)(scale * img.getHeight());
BufferedImage bufferedImage = new BufferedImage(scaledWidth, scaledHeight, img.getType());
if (rotation % 180 == 0)
    bufferedImage = new BufferedImage(scaledWidth, scaledHeight, img.getType());
else
    bufferedImage = new BufferedImage(scaledHeight, scaledWidth, img.getType());

AffineTransform transform = AffineTransform.getRotateInstance(Math.toRadians(rotation), scaledWidth/2, scaledHeight/2);
transform.scale(scale, scale);
AffineTransformOp operation = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);
scaledImage = operation.filter(img, bufferedImage);
imagePanel.setPreferredSize(new Dimension(bufferedImage.getWidth(), bufferedImage.getHeight()));
4

1 回答 1

1

啊哈!关键(JavaDoc 令人困惑)是意识到 onAffineTransformrotate()其他方法转换矩阵,而不是图像!以下代码自动运行!

/**
 * Transforms the image efficiently without losing image quality.
 * Scales the image to a width of (600 * scale) pixels, rotates the image,
 * and translates (moves) the image to recenter it if rotated 90 or 270 degrees.
 */
protected BufferedImage transformImage(BufferedImage image)
{
    int scaledWidth = (int)(scale * image.getWidth());
    int scaledHeight = (int)(scale * image.getHeight());

    // Methods AffineTransform.rotate(), AffineTransform.scale() and AffineTransform.translate()
    // transform AffineTransform's transformation matrix to multiply with the buffered image.
    // Therefore those methods are called in a counterintuitive sequence.
    AffineTransform transform;
    if (rotation % 180 == 0)
    {
        // First scale and second rotate image
        transform = AffineTransform.getRotateInstance(Math.toRadians(rotation), scaledWidth/2, scaledHeight/2);
        transform.scale(scale, scale);
    }
    else
    {
        // First scale, second rotate, and third translate image
        transform = AffineTransform.getTranslateInstance((scaledHeight-scaledWidth)/2, (scaledWidth-scaledHeight)/2);
        transform.rotate(Math.toRadians(rotation), scaledWidth/2, scaledHeight/2);
        transform.scale(scale, scale);
    }
    AffineTransformOp operation = new AffineTransformOp(transform, AffineTransformOp.TYPE_BICUBIC);
    BufferedImage transformedImage = operation.createCompatibleDestImage(image, image.getColorModel());
    return operation.filter(image, transformedImage);
}
于 2013-11-08T01:34:56.027 回答