Search code examples
cfile-ioimage-manipulationimage-scaling

image scaling with C


I'm trying to read an image file and scale it by multiplying each byte by a scale its pixel levels by some absolute factor. I'm not sure I'm doing it right, though -

void scale_file(char *infile, char *outfile, float scale)
{
    // open files for reading
    FILE *infile_p = fopen(infile, 'r');
    FILE *outfile_p = fopen(outfile, 'w');

    // init data holders
    char *data;
    char *scaled_data;

    // read each byte, scale and write back
    while ( fread(&data, 1, 1, infile_p) != EOF )
    {
        *scaled_data = (*data) * scale;
        fwrite(&scaled_data, 1, 1, outfile);
    }

    // close files
    fclose(infile_p);
    fclose(outfile_p);
}

What gets me is how to do each byte multiplication (scale is 0-1.0 float) - I'm pretty sure I'm either reading it wrong or missing something big. Also, data is assumed to be unsigned (0-255). Please don't judge my poor code :)

thanks


Solution

    1. change char *scaled_data; to char scaled_data;
    2. change *scaled_data = (*data) * scale; to scaled_data = (*data) * scale;

    That would get you code that would do what you are trying to do, but ....

    This could only possibly work on an image file of your own custom format. There is no standard image format that just dumps pixels in bytes in a file in sequential order. Image files need to know more information, like

    1. The height and width of the image
    2. How pixels are represented (1 byte gray, 3 bytes color, etc)
    3. If pixels are represented as an index into a palette, they have the palette
    4. All kinds of other information (GPS coordinates, the software that created it, the date it was created, etc)
    5. The method of compression used for the pixels

    All of this is called Meta-data

    In addition (as alluded to by #5), pixel data is usually compressed.