/******************************************************************
* image:指向图像数据的指针,以RGBA顺序存储为无符号字符的1D数组
* width:图像的宽度(以像素为单位)
* height:图像的高度(以像素为单位)
* angle:将图像旋转的角度,以度为单位
* center_x:旋转中心x
* center_y:旋转中心y
*******************************************************************/
void rotate_image(unsigned char *image, int width, int height, int angle, int center_x, int center_y)
{
int x, y, i;
double radians = angle * M_PI / 180.0;
unsigned char *rotated = malloc(width * height * 4);
for (y = 0; y < height; y++)
{
for (x = 0; x < width; x++)
{
int new_x = (x - center_x) * cos(radians) - (y - center_y) * sin(radians) + center_x;
int new_y = (x - center_x) * sin(radians) + (y - center_y) * cos(radians) + center_y;
if (new_x >= 0 && new_x < width && new_y >= 0 && new_y < height)
{
for (i = 0; i < 4; i++)
{
rotated[(y * width + x) * 4 + i] = image[(new_y * width + new_x) * 4 + i];
}
}
}
}
memcpy(image, rotated, width * height * 4);
free(rotated);
}
实际使用的话需要考虑不破坏原图,否则连续使用函数会严重失真。
该代码定义了一个函数`rotate_image`,用于按指定角度旋转图像。它以图像数据指针、宽度、高度、旋转角度及中心点坐标作为参数,使用了旋转矩阵进行计算。为了避免对原图的破坏,它创建了一个新缓冲区来存储旋转后的图像,最后再复制回原图像内存。连续使用该函数会导致失真,需注意保存原始数据。
1318





