java如何利用rotate旋转图片_如何在Java中旋转图形

I have drawn some Graphics in a JPanel, like circles, rectangles, etc.

But I want to draw some Graphics rotated a specific degree amount, like a rotated ellipse. What should I do?

解决方案

If you are using plain Graphics, cast to Graphics2D first:

Graphics2D g2d = (Graphics2D)g;

To rotate an entire Graphics2D:

g2d.rotate(Math.toRadians(degrees));

//draw shape/image (will be rotated)

To reset the rotation (so you only rotate one thing):

AffineTransform old = g2d.getTransform();

g2d.rotate(Math.toRadians(degrees));

//draw shape/image (will be rotated)

g2d.setTransform(old);

//things you draw after here will not be rotated

Example:

class MyPanel extends JPanel {

@Override

public void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2d = (Graphics2D)g;

AffineTransform old = g2d.getTransform();

g2d.rotate(Math.toRadians(degrees));

//draw shape/image (will be rotated)

g2d.setTransform(old);

//things you draw after here will not be rotated

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以通过读取图片的EXIF信息来判断图片的朝向,并进行旋转。EXIF是指嵌入在图片的元数据,其包含了拍摄设备、拍摄时间、拍摄参数等信息。 以下是获取图片朝向并旋转Java代码示例: ```java import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javaxt.io.Image; public class ImageOrientation { public static void main(String[] args) throws IOException { File file = new File("image.jpg"); BufferedImage image = ImageIO.read(file); // 获取图片的EXIF信息 Image.Orientation orientation = new Image(file).getOrientation(); // 根据图片朝向进行旋转 switch (orientation) { case TOP_LEFT: break; case TOP_RIGHT: image = rotate(image, 180); break; case BOTTOM_RIGHT: image = rotate(image, 180); break; case BOTTOM_LEFT: image = rotate(image, 180); break; case LEFT_TOP: image = rotate(image, 90); break; case RIGHT_TOP: image = rotate(image, -90); break; case RIGHT_BOTTOM: image = rotate(image, 90); break; case LEFT_BOTTOM: image = rotate(image, -90); break; } // 保存旋转后的图片 ImageIO.write(image, "jpg", new File("rotated_image.jpg")); } // 旋转图片 public static BufferedImage rotate(BufferedImage image, int degree) { int w = image.getWidth(); int h = image.getHeight(); int type = image.getColorModel().getTransparency(); BufferedImage result = new BufferedImage(w, h, type); Graphics2D graphics = result.createGraphics(); graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics.rotate(Math.toRadians(degree), w / 2, h / 2); graphics.drawImage(image, 0, 0, null); graphics.dispose(); return result; } } ``` 该代码,首先读取图片文件并获取其EXIF信息,然后根据其朝向进行旋转,最后保存旋转后的图片。其,`javaxt.io.Image`是一个第三方库,用于获取图片的EXIF信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值