我的程序出现问题,无法正确调整图像大小

时间:2019-06-26 23:31:25

标签: c cs50

因此该代码假定采用3个参数,并输出按指定因子(介于1到100之间)缩放的图像,当前我得到的图像与预期输出不匹配 我要说的是问题出在循环中,或者可能在新文件大小中 即使因子设置为1,我也遇到了这些问题


    // set new height and width of BMP
    bi_New.biHeight = bi.biHeight * factor;
    bi_New.biWidth = bi.biWidth * factor;

    // calculate padding for old file and new file
    int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;
    int padding_New = (4 - (bi_New.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;

    // set the file size for the new file
    bf_New.bfSize = 54 + (bi_New.biWidth * sizeof(RGBTRIPLE) + padding_New) * abs(bi_New.biHeight);
    bi_New.biSizeImage = bf_New.bfSize - 54;


    // write outfile's BITMAPFILEHEADER
    fwrite(&bf_New, sizeof(BITMAPFILEHEADER), 1, outptr);

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

    // iterate over infile's scanlines
    for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++)
        {
        // iterate over pixels in scanline
        for (int j = 0; j < bi.biWidth; j++)
            {
            // intialise counter to print rows by amount of the factor
            int counter = 0;

            // while loop to keep continuing until factor is less than or equal to counter
            while (counter < factor)
                {
                // iterate over pixels in scanline
                for(int k = 0; k < bi.biWidth; k++)
                    {
                    // temporary storage
                    RGBTRIPLE triple;

                    // declare pixel counter
                    int pixel_counter = 0;

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

                    // write RGB triple to outfile and use a while loop to itterate the same pixel by factor times
                    while (pixel_counter < factor)
                        {
                        fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
                        pixel_counter++;
                        }
                    }
                // add new padding
                for (int l = 0; l < padding_New; l++)
                    {
                    fputc(0x00, outptr);
                    }

                // seek back to the beginning of row in input file, but not after iteration of printing
                if (counter < (factor - 1))
                    {
                    fseek(inptr, -(bi.biWidth * sizeof(RGBTRIPLE)), SEEK_CUR);
                    }
                counter++;
                }
            }

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

    // close infile
    fclose(inptr);

    // close outfile
    fclose(outptr);

    // success
    return 0;
    }

1 个答案:

答案 0 :(得分:0)

j循环是罪魁祸首。程序将处理每条扫描线width * factor次,而不是factor次。它为每个扫描线添加了额外的width迭代。