调整图片大小 - ReSize
函数简介
调整图片的尺寸大小。此函数可以将图片缩放到指定的宽度和高度,支持等比例缩放和自由缩放。缩放过程使用高质量的插值算法,以保证缩放后的图片质量。常用于图片预处理、缩略图生成、界面适配等场景。
接口名称
ReSize
DLL调用
long ReSize(long ola, long image_ptr, int new_width, int new_height)
参数定义:
ola
(长整型数): OLAPlug对象的指针,由 CreateCOLAPlugInterFace 接口生成。image_ptr
(长整型数): 要调整大小的图片句柄。new_width
(整型数): 目标宽度,单位为像素。new_height
(整型数): 目标高度,单位为像素。
示例:
// 加载原图并获取尺寸
long image = LoadImage(ola, "D:\\test\\source.png");
if (image != 0) {
int width, height;
GetImageSize(ola, image, &width, &height);
printf("原图大小:%d x %d\n", width, height);
// 缩小到50%
long small_image = ReSize(ola, image, width/2, height/2);
if (small_image != 0) {
printf("图片缩小成功\n");
SaveImageFromPtr(ola, small_image, "D:\\test\\small.png");
FreeImagePtr(ola, small_image);
}
// 放大到200%
long large_image = ReSize(ola, image, width*2, height*2);
if (large_image != 0) {
printf("图片放大成功\n");
SaveImageFromPtr(ola, large_image, "D:\\test\\large.png");
FreeImagePtr(ola, large_image);
}
// 等比例缩放到指定宽度
int target_width = 800;
float scale = (float)target_width / width;
int target_height = (整型数)(height * scale);
long scaled_image = ReSize(ola, image, target_width, target_height);
if (scaled_image != 0) {
printf("等比例缩放成功\n");
SaveImageFromPtr(ola, scaled_image, "D:\\test\\scaled.png");
FreeImagePtr(ola, scaled_image);
}
FreeImagePtr(ola, image);
}
// 批量处理图片尺寸
const int MAX_WIDTH = 1024;
const int MAX_HEIGHT = 768;
void ProcessImage(const char* input_path, const char* output_path) {
long image = LoadImage(ola, input_path);
if (image != 0) {
int width, height;
GetImageSize(ola, image, &width, &height);
// 如果图片超过最大尺寸,进行等比例缩放
if (width > MAX_WIDTH || height > MAX_HEIGHT) {
float scale_w = (float)MAX_WIDTH / width;
float scale_h = (float)MAX_HEIGHT / height;
float scale = scale_w < scale_h ? scale_w : scale_h;
int new_width = (整型数)(width * scale);
int new_height = (整型数)(height * scale);
long resized = ReSize(ola, image, new_width, new_height);
if (resized != 0) {
SaveImageFromPtr(ola, resized, output_path);
FreeImagePtr(ola, resized);
}
} else {
// 直接保存原图
SaveImageFromPtr(ola, image, output_path);
}
FreeImagePtr(ola, image);
}
}
返回值
长整型数:
- 0: 调整失败
- 非0: 调整成功,返回新图片的句柄
注意事项
- 调整后会返回新的图片句柄,原图片不会被修改
- 新图片句柄使用完后需要调用 FreeImagePtr 释放内存
- 缩小图片通常不会损失太多质量,但过度放大可能会导致图片模糊
- 为保持图片比例,建议使用等比例缩放
- 如果需要更高级的缩放选项(如指定插值算法),可以使用 ScalePixels 函数