c - 如何使用数组和 fwrite 垂直调整 bmp 文件大小?

标签 c

我正在编写代码来调整 BMP 文件的大小。有些文件的大小可以正确调整,但有些则不能。我的错误是什么?

我将原始 RGB 放入数组中,已经水平调整其大小,并尝试将数组写入“n”次以输出文件。另外,我放置了abs(biHeight),以防它为负数。

bi.biWidth*=n;
bi.biHeight*=n;
int padding1 = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;
bi.biSizeImage = (bi.biWidth* sizeof(RGBTRIPLE) + padding1) * abs(bi.biHeight);
bf.bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + (bi.biWidth * sizeof(RGBTRIPLE) + padding1) * abs(bi.biHeight);
int biWidth = bi.biWidth/n;
int biHeight =abs (bi.biHeight/n);
// write outfile's BITMAPFILEHEADER
fwrite(&bf, sizeof(BITMAPFILEHEADER), 1, outptr);

// write outfile's BITMAPINFOHEADER
fwrite(&bi, sizeof(BITMAPINFOHEADER), 1, outptr);

//arrey for pic
RGBTRIPLE pic[biWidth*n];
// determine padding for scanlines
int padding = (4 - (biWidth * sizeof(RGBTRIPLE)) % 4) % 4;


// iterate over infile's scanlines
for (int i = 0; i < biHeight; i++)
{
    int p=0;
    // iterate over pixels in scanline
    for (int j = 0; j < biWidth; j++)

    {
        // temporary storage
        RGBTRIPLE triple;


        // read RGB triple from infile
        fread(&triple, sizeof(RGBTRIPLE), 1, inptr);

        //conwerting to n pixels in scanlines
        for(int t=0;t<n;t++)
        {
            pic[p]=triple;
            p++;
        }
    }
    //writing pic for n
    for (int h=0;h<n;h++)
    fwrite(&pic,sizeof(pic),1,outptr);

    // skip over padding, if any
    fseek(inptr, padding, SEEK_CUR);

    // then add it back (to demonstrate how)
    for (int k = 0; k < padding1; k++)
    {
        fputc(0x00, outptr);
    }
}

我希望获得正确调整大小的输出文件图像,但它不适用于所有文件 :) resize.c 和 bmp.h 存在。

:) resize.c 编译。

:) 当 n 为 1 时不调整small.bmp 的大小

:(当n为2时正确调整small.bmp的大小

Byte 20 of pixel data doesn't match. Expected 0x00, not 0xff

:(当n为3时正确调整small.bmp的大小

Byte 29 of pixel data doesn't match. Expected 0x00, not 0xff

:) 当n为4时正确调整small.bmp的大小

:(当n为5时正确调整small.bmp的大小

Byte 47 of pixel data doesn't match. Expected 0x00, not 0xff

:) 当 n 为 2 时正确调整 large.bmp 的大小

:) 当 n 为 2 时正确调整 smiley.bmp 的大小

:) 当 n 为 3 时正确调整 smiley.bmp 的大小

最佳答案

//writing pic for n
for (int h = 0; h < n; h++)
{
    fwrite(&pic, sizeof(pic), 1, outptr);
    // then add it back (to demonstrate how)
    for (int k = 0; k < padding1; k++)
    {
        fputc(0x00, outptr);
    }
}
// skip over padding, if any
fseek(inptr, padding, SEEK_CUR);

}

关于c - 如何使用数组和 fwrite 垂直调整 bmp 文件大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56514005/

相关文章:

c - 我有c语言语法问题

c - 打开 MP 代码无法按预期使用数学函数

c - 奇数行反转矩阵转置

c - 在运行时修改结构体字段

c - 如何调试异常的 C 内存/堆栈问题

c - 如何使用写函数格式化字符串?

c - 嵌入式 C : AVR; variable in header cannot be evaluated in main

创建 atoi 函数

c - c指针中的大困惑

缓存命中、未命中和预测 - 对性能的影响