调整CS50的大小:不知道为什么填充更改,以及为什么代码不起作用

时间:2017-07-13 12:15:59

标签: c bmp bitmapimage cs50

我正在学习使用CS50 Harvard讲座进行编码。无法通过调整大小问题集。具体来说,我无法弄清楚如何垂直调整大小。这是代码:

int main(int argc, char *argv[])
{
    // ensure proper usage
    if (argc != 4)
    {
        fprintf(stderr, "Usage: ./resize f infile outfile\n");
        return 1;
    }

    // remember filenames
    char *infile = argv[2];
    char *outfile = argv[3];

    //check if f is float
    if (strcmp(argv[1], "0") == 0)
    {
        fprintf(stderr, "f cannot be 0\n");
        return 1;
    }

    float f = atof(argv[1]);
    if (f == 0)
    {
        fprintf(stderr, "error while reading float\n");
        return 1;
    }

    // open input file
    FILE *inptr = fopen(infile, "r");
    if (inptr == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", infile);
        return 1;
    }

    // open output file
    FILE *outptr = fopen(outfile, "w");
    if (outptr == NULL)
    {
        fclose(inptr);
        fprintf(stderr, "Could not create %s.\n", outfile);
        return 1;
    }


    // read infile's BITMAPFILEHEADER
    BITMAPFILEHEADER bf;
    fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr);

    // read infile's BITMAPINFOHEADER
    BITMAPINFOHEADER bi;
    fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr);

        // ensure infile is (likely) a 24-bit uncompressed BMP 4.0
    if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 ||
        bi.biBitCount != 24 || bi.biCompression != 0)
    {
        fclose(outptr);
        fclose(inptr);
        fprintf(stderr, "Unsupported file format.\n");
        return 4;
    }

    int inpad = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;

    //bi.biWidth *= f;
    bi.biHeight *= f;

    // determine outpad for scanlines
    int outpad = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;

    bi.biSizeImage = (((sizeof(RGBTRIPLE) * bi.biWidth) + inpad) * abs(bi.biHeight));
    bf.bfSize = bi.biSizeImage + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);

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

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


    for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++)
    {
        RGBTRIPLE triple;

        fread(&triple, sizeof(RGBTRIPLE), bi.biWidth, inptr);

        for (int j = 0; j < f; j++)
        {
            fwrite(&triple, sizeof(RGBTRIPLE), bi.biWidth, outptr);

            //add padding
            for (int k = 0; k < outpad; k++)
            {
                fputc(0x00, outptr);
            }
        }

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

    }

    // close infile
    fclose(inptr);

    // close outfile
    fclose(outptr);

    //test of success
    printf("inpad:%d\noutpad:%d\n", inpad, outpad);

    return 0;
}

读取infile的一行后,infile padding变为-1,outfile变为-256。

0 个答案:

没有答案