-
图像旋转
图像的中心点是旋转中心
x0=x1cosa-y1sina
y0=x1sina+y1cosa
该代码输出图像和原图尺寸一致
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* 图像旋转
* 图像的中心点是旋转中心
* x0=x1*cosa-y1*sina
* y0=x1*sina+y1*cosa
* 该参考代码输出图像和原图尺寸一致
* 图像的旋转中心
* */
public class ch4_3 {
public static int BGCOLOR=0; //设置背景色,0表示黑色
public static void main(String[] args) throws Exception {
long t1=System.currentTimeMillis(); //获取程序运行前的时间,单位毫秒
BufferedImage bi=ImageIO.read(new File("1.jpg")); //读取图像
BufferedImage nbi=xuanzhuan(bi,60); //处理图像
ImageIO.write(nbi, "jpg", new File("1b.jpg")); //输出图像
long t2=System.currentTimeMillis(); //获取程序运行后的时间
System.out.println("程序运行"+(t2-t1)+"毫秒"); //程序结束后进行提示
}
/**
* 图像旋转
* @param BufferedImage bi 原始图像
* @param double angle 旋转角度
* @return BufferedImage 变换后图像
* */
public static BufferedImage xuanzhuan(BufferedImage bi, double angle) {
int w=bi.getWidth(); //得到图像的宽度
int h=bi.getHeight(); //得到图像的高度
angle=Math.PI*angle/180; //角度转换为弧度
double sina=Math.sin(angle); //用变量减少三角函数的计算量
double cosa=Math.cos(angle);
int cx=w/2; //计算图像的中心点
int cy=h/2;
BufferedImage nbi=new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR);
//创建新图像(临时图像变量)宽度和高度跟原图相同
//循环遍历每一个像素点
for(int y1=0;y1<h;y1++) {
for(int x1=0;x1<w;x1++) {
//计算输出图像坐标(x1,y1)所对应原图中的坐标(x0,y0)位置
int x0=(int)((x1-cx)*cosa-(y1-cy)*sina+cx);
int y0=(int)((x1-cx)*sina+(y1-cy)*cosa+cy);
int rgb=BGCOLOR; //默认像素值是背景色
if(x0>=0 && x0<w && y0>=0 && y0<h) { //原图坐标符合要求才赋值
rgb=bi.getRGB(x0, y0);
}
nbi.setRGB(x1, y1, rgb); //设置输出图像坐标为(x,y)的像素值
}
}
return nbi;
}
}