旋转图像的Java程序
问题陈述是将图像顺时针旋转 90 度,在这里我们将使用 BufferedImage 类和 Color c 的一些内置方法
执行操作所需的类如下:
- 读取和写入 图像文件我们必须导入 File 类。此类通常表示文件和目录路径名。
- 为了处理错误,我们使用 IOException 类。
- 为了保存图像,我们使用 BufferedImage 类创建了 BufferedImage 对象。该对象用于在 RAM 中存储图像。
- 为了执行图像读写操作,我们将导入 ImageIO 类。此类具有读取和写入图像的静态方法。
- 此 Graphics2D 类扩展了 Graphics 类,以提供对几何、坐标转换、颜色管理和文本布局的更复杂的控制。这是在Java(tm) 平台上呈现二维形状、文本和图像的基本类。
例子:
Java
// Java program to rotate image by 90 degrees clockwise
// Importing classes from java.awt package for
// painting graphics and images
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
// Importing input output classes
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
// Main class
public class GFG {
// Method 1
// To return rotated image
public static BufferedImage rotate(BufferedImage img)
{
// Getting Dimensions of image
int width = img.getWidth();
int height = img.getHeight();
// Creating a new buffered image
BufferedImage newImage = new BufferedImage(
img.getWidth(), img.getHeight(), img.getType());
// creating Graphics in buffered image
Graphics2D g2 = newImage.createGraphics();
// Rotating image by degrees using toradians()
// method
// and setting new dimension t it
g2.rotate(Math.toRadians(90), width / 2,
height / 2);
g2.drawImage(img, null, 0, 0);
// Return rotated buffer image
return newImage;
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// try block to check for exceptions
try {
// Reading orignal image
BufferedImage orignalImg = ImageIO.read(
new File("D:/test/Image.jpeg"));
// Getting and Printing dimensions of orignal
// image
System.out.println("Orignal Image Dimension: "
+ orignalImg.getWidth() + "x"
+ orignalImg.getHeight());
// Creating a subimage of given dimensions
BufferedImage SubImg = rotate(orignalImg);
// Printing Dimensions of new image created
// (Rotated image)
System.out.println("Cropped Image Dimension: "
+ SubImg.getWidth() + "x"
+ SubImg.getHeight());
// Creating new file for rotated image
File outputfile
= new File("D:/test/ImageRotated.jpeg");
// Writing image in new file created
ImageIO.write(SubImg, "jpg", outputfile);
// Printing executed message
System.out.println(
"Image rotated successfully: "
+ outputfile.getPath());
}
// Catch block to handle the exception
catch (IOException e) {
// Print the line number where exception
// occurred
e.printStackTrace();
}
}
}
输出:执行程序后,控制台将显示尺寸和执行消息,并在输入的路径上创建一个新的旋转图像,如下所示: