0

My code is following. Feel puzzled to generate wrong result..

``` #include #include "bmp.h" #include #include int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "Please enter two files name"); return 1; }

char *inputf = argv[1];
char *outputf = argv[2];

FILE *i = fopen(inputf,"r");
if (i == NULL)
{
    fprintf(stderr, "fail to access file: %s\n",inputf);
    fclose(i);
    return 2;
}
FILE *o = fopen(outputf,"w");
if (o == NULL)
{
    fprintf(stderr, "fail to creat file: %s\n",outputf);
    fclose(o);
    return 2;
}
//read fileheader
BITMAPFILEHEADER bf;
fread(&bf, sizeof(BITMAPFILEHEADER),1,i);
BITMAPINFOHEADER bi;
fread(&bi, sizeof(BITMAPINFOHEADER),1,i);

//check whther file is BMP
if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 ||
    bi.biBitCount != 24 || bi.biCompression != 0)
{
    fclose(i);
    fclose(o);
    fprintf(stderr, "Unsupported file format.\n");
}

// Write outfile
fwrite(&bf, sizeof(BITMAPFILEHEADER), 1, o);
fwrite(&bi, sizeof(BITMAPINFOHEADER), 1, o);

//consider padding
int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4 ) % 4;
for (int row = 0, biHeight = abs(bi.biHeight); row < biHeight; row++)
{
    for (int col = 0; col < bi.biWidth; col++)
    {
        RGBTRIPLE triple;
        fread(&triple, sizeof(RGBTRIPLE), 1, i);
        if (triple.rgbtRed == 0x0000ff)
        {
            triple.rgbtRed = 0x000000;
        }
        fwrite(&triple, sizeof(RGBTRIPLE), 1, o);

    }
    //
    fseek(i, padding, SEEK_CUR);
    for(int k = 0; k < padding; k++)
    {
        fputc(0x00, o);
    }
}

//close file
fclose(i);
fclose(o);
return 0;

} ```

1
  • I think Stack Exchange doesn't support triple backticks, but the editor has a {} button you can click after selecting the code, this indents by four bytes, or removes them if all selected lines had them.
    – Blauelf
    Commented Apr 20, 2018 at 15:20

1 Answer 1

0

Haven't tried the code, and you should have described what it does, or what it doesn't. Otherwise, it's a naked code drop as described in Why questions don't get answers or why people are ignored?

triple.rgbtRed is a single byte, not the value of the whole pixel. And 0xff doesn't require leading zeroes (they are ignored), it's the same as 255, an int that gets converted to uint8_t on assignment. Compiler might skip that conversion step and instantly work with bytes as long as it yields the same result ;-)

As I understand the code, this makes any white pixel (0xff, 0xff, 0xff) cyan (0xff, 0xff, 0x00) and any red pixel (0x00, 0x00, 0xff) black (0x00, 0x00, 0x00). Maybe you should instead try what the red plastic sheet does. It removes green and blue, on all the pixels. (You could replace them with the red value of the pixel instead). I'd experiment that way. Or maybe instead of lowering the red value, raise green and blue to make red pixels white.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .