gpt4 book ai didi

C - 调整/放大图像

转载 作者:行者123 更新时间:2023-11-30 19:36:12 31 4
gpt4 key购买 nike

我只是想说,我是 C 语言的新手。好吧,除此之外,我在圣诞假期的任务是编写一个以各种方式操作 PNG 图像的程序。我已经完成了大部分事情,但是在尝试编写放大图像的程序时遇到了问题。我已经尝试过了,并且取得了一些成果。虽然我很确定这都是错的......

    void enlargeImage(Image plain, char *imageInput[])
{

Image tempImage;
Pixel** pixels;

int scale = 2;

pixels = malloc(plain.height * sizeof(Pixel*) *scale);

for (int i = 0; i < plain.height; i++)
{
pixels[i] = malloc(plain.width * sizeof(Pixel*) * scale);
}

tempImage.pixels = pixels;
tempImage.height = plain.height * scale; //Can I even do this?? Or is it completely wrong?
tempImage.width = plain.width * scale;

// I've tried a few variations of this code
for (int height = 0; height < plain.height; height++)
{

for (int width = 0; width < plain.width; width++)
{

tempImage.pixels[height][width] = plain.pixels[height][width];

}
}



writeImage(imageInput, &tempImage); //This is a function written by my teachers. This is also where I get an error. I'm suspecting it's because I've doubled the size of tempImage ??

free(tempImage.pixels);
}

如果有人能帮助我,我将非常感激^^
谢谢!

最佳答案

1.分配应该是这样的:

tempImage.height = plain.height * scale;
tempImage.width = plain.width * scale;

pixels = malloc(tempImage.height * sizeof(Pixel*));
if (pixels == NULL) return;

for (int i = 0; i < tempImage.height; i++)
{
pixels[i] = malloc(tempImage.width * sizeof(Pixel));
if (pixels[i] == NULL)
{
for (int j = 0; j < i; j++) free(pixels[j]);
free(pixels);
return;
}
}

tempImage.pixels = pixels;

要点是:

  • 在进行分配之前,通过计算 tempImage.heighttempImage.width 避免进行两次成对乘法。
  • 虽然 sizeof(char) 被定义为 1,因此乘以它并没有什么害处,但它似乎会产生困惑并使阅读程序变得更加困难。
  • pixels[i] 的元素类型为 Pixel。因此,在第二个 malloc() 中,应乘以 sizeof(Pixel) 而不是 sizeof(Pixel*)
  • 为所有行分配内存。您的程序仅分配了前半行。
  • 应检查 malloc() 的返回值,以避免取消引用 NULL,该值是在失败时从 malloc() 返回的,并调用未定义的行为

2.转换应该是这样的:

for (int height = 0; height < tempImage.height; height++)
{
for (int width = 0; width < tempImage.width; width++)
{
tempImage.pixels[height][width] = plain.pixels[height / scale][width / scale];
}
}

要点是:

  • 设置目标图像 (tempImage) 的所有像素的值。通过 malloc() 分配的缓冲区的初始值是不确定的,使用它们将调用未定义的行为
  • 小心不要访问(不读取或写入)超出范围的数组,否则您将调用未定义的行为

3.您可以通过 free(tempImage.pixels); 释放行列表,但您应该通过添加

来释放每行的数据
for (int i = 0; i < tempImage.height; i++)
{
free(tempImage.pixels[i]);
}

就在free(tempImage.pixels);行之前。请注意,tempImage.pixelspixels 指向同一个数组,因此您不必(也不得)使用 free() 对于两者:仅对其中之一使用 free()

4.不知道 writeImage 的实际签名,说服

void enlargeImage(Image plain, char *imageInput[])

writeImage(imageInput, &tempImage);

看起来很奇怪。您确定 writeImage 的第一个参数应该是指向字符的指针,而不是指向诸如 char *imageInput 之类的字符的指针吗?

关于C - 调整/放大图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41487285/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com