我的功能正在获取图像,我正在尝试裁剪BMP图像 按尺寸:100 x 100、200 x 200、300 x 300、400 x 400(按像素), 我不知道该怎么办。请帮助我
图像的大小为int高度和int宽度,并且该函数知道以像素为单位的值。
这是我的代码:
void re_allocate_pixels(struct RGB_Image *image, int new_height, int new_width)
{
int org_height = image->height;
int org_width = image->width;
int org_size = image->size;
int i;
struct Pixel **pxls;
pxls = (struct Pixel **)malloc((org_height) * sizeof(struct Pixel *));
if (pxls == NULL)
{
printf("Memory allocation failed\n");
exit(1);
}
for (i = 0; i < org_height; i++)
{
pxls[i] = (struct Pixel *)malloc(org_width * sizeof(struct Pixel));
if (pxls[i] == NULL)
{
printf("Memory allocation failed\n");
exit(1);
}
}
//i have no idea what to do next to crop the image and pixecl
/*for (int j = 0; j < org_height; j++)
{
for (int k = 0; k < org_width; k++)
{
pxls[i][j] = pxls[k][j];
}
}*/
}
以下是结构数据:
struct Pixel
{
unsigned char red;
unsigned char green;
unsigned char blue;
};
struct RGB_Image
{
char file_name[MAX_FILE_NAME_SIZE];
long height;
long width;
long size;
struct Pixel **pixels;
};
这是该函数的调用方式
struct RGB_Image *rgb_img_ptr;
struct RGB_Image image;
rgb_img_ptr = ℑ
int image_load_ret_value = load_image(rgb_img_ptr);
re_allocate_pixels(rgb_img_ptr, 100,100); // here is calling
答案 0 :(得分:1)
您必须删除旧分配,并分配新的size
值。 size
通常是指“以字节为单位的宽度”乘以高度。
在这种情况下,“以字节为单位的宽度”的值应为“ width * 3”,并且应始终为4的倍数。
一次读取图像。使用mempcy
复制每一行。
请注意,位图通常是上下颠倒的。您可能需要将循环更改为for (int y = dst.height - 1; y >=0; y--){memcpy...}
void re_allocate_pixels(struct RGB_Image *image, int new_height, int new_width)
{
if(new_width > image->width) return;
if(new_height > image->height) return;
struct RGB_Image *src = image;
struct RGB_Image dst;
dst.width = new_width;
dst.height = new_height;
//allocate memory
dst.pixels = malloc(dst.height * sizeof(struct Pixel*));
for(int y = 0; y < dst.height; y++)
dst.pixels[y] = malloc(dst.width * sizeof(struct Pixel));
//copy from source to destination
for(int y = 0; y < dst.height; y++)
memcpy(dst.pixels[y], src->pixels[y], dst.width * sizeof(struct Pixel));
//free the old allocation
for(int y = 0; y < src->height; y++)
free(image->pixels[y]);
free(image->pixels);
//assing new allocation
image->pixels = dst.pixels;
//set the new width, height, size
image->width = dst.width;
image->height = dst.height;
int bitcount = 24;
int bytecount = 3; //<- same as sizeof(struct Pixel)
//calculate width in bytes
int width_in_bytes = ((dst.width * bitcount + 31) / 32) * 4;
image->size = width_in_bytes * dst.height;
}