图片查看器java注解,有旋转功能
时间: 2024-04-30 10:20:22 浏览: 69
以下是一个使用Java注解实现图片旋转功能的示例代码:
```java
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class ImageRotator {
private static final int ROTATION_ANGLE = 90;
public static void main(String[] args) throws IOException {
File file = new File("image.jpg");
BufferedImage image = ImageIO.read(file);
BufferedImage rotatedImage = rotate(image, ROTATION_ANGLE);
displayImage(rotatedImage);
}
@ImageRotation(angle = ROTATION_ANGLE)
private static BufferedImage rotate(BufferedImage image, int angle) {
double radians = Math.toRadians(angle);
int width = image.getWidth();
int height = image.getHeight();
int rotatedWidth = (int) Math.round(width * Math.abs(Math.cos(radians)) + height * Math.abs(Math.sin(radians)));
int rotatedHeight = (int) Math.round(height * Math.abs(Math.cos(radians)) + width * Math.abs(Math.sin(radians)));
BufferedImage rotatedImage = new BufferedImage(rotatedWidth, rotatedHeight, image.getType());
Graphics2D graphics = rotatedImage.createGraphics();
graphics.setTransform(getTransform(width, height, angle));
graphics.drawImage(image, 0, 0, null);
graphics.dispose();
return rotatedImage;
}
private static AffineTransform getTransform(int width, int height, int angle) {
AffineTransform transform = new AffineTransform();
transform.translate(width / 2, height / 2);
transform.rotate(Math.toRadians(angle));
transform.translate(-height / 2, -width / 2);
return transform;
}
private static void displayImage(BufferedImage image) {
JFrame frame = new JFrame();
JLabel label = new JLabel(new ImageIcon(image), SwingConstants.CENTER);
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface ImageRotation {
int angle();
}
```
在上面的示例中,我们定义了一个名为`ImageRotation`的注解,该注解可以应用于`rotate`方法上,用于指定旋转角度。当我们调用`rotate`方法时,程序会检查该方法上是否有`ImageRotation`注解,如果有,则从注解中获取旋转角度。程序使用Java的内置`AffineTransform`类来执行图像旋转操作,然后将旋转后的图像显示在窗口中。
阅读全文