我有一个图像,我必须旋转45度,90度,135度,180度。我在做什么:
try {
BufferedImage src = ImageIO.read(new File("src.png"));
double ang = Math.toRadians(90);
AffineTransform t = new AffineTransform();
t.setToRotation(ang, src.getWidth() / 2, src.getHeight() / 2);
AffineTransformOp op = new AffineTransformOp(t, null);
BufferedImage dst = new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
op.filter(src, dst);
ImageIO.write(dst, "png", new File("output.png"));
} catch(Exception ex) { ex.printStackTrace();
}
问题在于图像会改变其位置并超出目标图像的范围:
The problem http://img32.imageshack.us/img32/3328/resultcs.png
我已经用Google搜索并在此问题中找到了解决方案:AffineTransform truncates image, what do I wrong?但我完全不理解它,它仅适用于象限。我试图将目标的宽度和高度相乘两倍,但它失败了:
Another fail http://img401.imageshack.us/img401/2417/result2a.png
如何解决这个问题?目标图像不应该有任何额外的(对角旋转所需的除外)空白或截断区域。角度问题(0 == 180或顺时针方向)并不重要。
感谢您的帮助。
答案 0 :(得分:4)
编辑:现在适用于一般情况。
围绕中心执行旋转,中心位于目标图像中与源图像中相同的位置(正确行为)。
我修改了你的代码来转换源图像矩形,这样我们就可以轻松获得新的尺寸/图像偏移量。这用于构建正确尺寸的目标BufferedImage
,并将翻译附加到AffineTransform
,以便将图像中心放置在目标图像的中心。
BufferedImage src = ImageIO.read(new File(INPUT));
int w = src.getWidth();
int h = src.getHeight();
AffineTransform t = new AffineTransform();
double ang = Math.toRadians(35);
t.setToRotation(ang, w / 2d, h / 2d);
// source image rectangle
Point[] points = {
new Point(0, 0),
new Point(w, 0),
new Point(w, h),
new Point(0, h)
};
// transform to destination rectangle
t.transform(points, 0, points, 0, 4);
// get destination rectangle bounding box
Point min = new Point(points[0]);
Point max = new Point(points[0]);
for (int i = 1, n = points.length; i < n; i ++) {
Point p = points[i];
double pX = p.getX(), pY = p.getY();
// update min/max x
if (pX < min.getX()) min.setLocation(pX, min.getY());
if (pX > max.getX()) max.setLocation(pX, max.getY());
// update min/max y
if (pY < min.getY()) min.setLocation(min.getX(), pY);
if (pY > max.getY()) max.setLocation(max.getX(), pY);
}
// determine new width, height
w = (int) (max.getX() - min.getX());
h = (int) (max.getY() - min.getY());
// determine required translation
double tx = min.getX();
double ty = min.getY();
// append required translation
AffineTransform translation = new AffineTransform();
translation.translate(-tx, -ty);
t.preConcatenate(translation);
AffineTransformOp op = new AffineTransformOp(t, null);
BufferedImage dst = new BufferedImage(w, h, src.getType());
op.filter(src, dst);
ImageIO.write(dst, "png", new File(OUTPUT));
答案 1 :(得分:0)
我建议更换
AffineTransformOp op = new AffineTransformOp(t, null);
与
AffineTransformOp op = new AffineTransformOp(t, AffineTransformOp.TYPE_BILINEAR);
它将大大提高输出质量。