C语言旋转RGBα图片任意角度

该代码定义了一个函数`rotate_image`,用于按指定角度旋转图像。它以图像数据指针、宽度、高度、旋转角度及中心点坐标作为参数,使用了旋转矩阵进行计算。为了避免对原图的破坏,它创建了一个新缓冲区来存储旋转后的图像,最后再复制回原图像内存。连续使用该函数会导致失真,需注意保存原始数据。
/******************************************************************
* 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);
}

实际使用的话需要考虑不破坏原图,否则连续使用函数会严重失真。

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值