I wrote a function to replace color in a bitmap image. For beginners in image processing, it could be exclusively useful, since they could use it to replace the entire gamma of a color or to replace a color with gradient/abstract lines, following the function's logic.
The main problem of the function, according to performance, is that it isn't fast enough. For larger images/replacing more then one color, this could take a minute or even more. I am sure there is a huge room for improvement of this function, therefore speed-optimized.
#include <stdio.h>
#include <stdlib.h>
#define IMAGE_WIDTH 500
#define IMAGE_OFFSET_SIZE 2
#define IMAGE_OFFSET_PIXELS 54
typedef unsigned char byte;
typedef unsigned long dword;
int main (int argc, char *argv[])
{
dword bitmap_color_replace (char *, byte, byte, byte, byte, byte, byte);
printf("Pixels successfully replaced: %i\n",
bitmap_color_replace("sample.bmp", 255, 255, 255, 0, 200, 255));
return EXIT_SUCCESS;
}
/**************************************************************************/
dword
bitmap_color_replace
(char *file_name, byte old_r, byte old_g, byte old_b, byte new_r, byte new_g, byte new_b)
{
dword fp_height = 0;
dword fp_size;
FILE* fp = fopen(file_name, "r+b");
dword i, pixels_replaced = 0;
byte new_color[3];
new_color[0] = new_b;
new_color[1] = new_g;
new_color[2] = new_r;
fseek(fp, IMAGE_OFFSET_SIZE, SEEK_SET);
fp_size = fgetc(fp) + fgetc(fp)*256 + fgetc(fp)*(256*256) + fgetc(fp)*(256*256*256);
for(i = IMAGE_OFFSET_PIXELS; i < fp_size; i += sizeof(new_color))
{
byte current_r, current_g, current_b;
fseek(fp, i, SEEK_SET);
if(i == IMAGE_OFFSET_PIXELS + (IMAGE_WIDTH * (fp_height+1))) // skip padding
{
fp_height++;
i += IMAGE_WIDTH % 4;
fseek(fp, IMAGE_WIDTH % 4, SEEK_CUR);
}
current_b = fgetc(fp);
current_g = fgetc(fp);
current_r = fgetc(fp);
if(current_b == old_b && current_g == old_g && current_r == old_r)
{
fseek(fp, i, SEEK_SET);
fwrite(new_color, sizeof(new_color), 1, fp);
pixels_replaced++;
}
}
fclose(fp);
return pixels_replaced;
}
fwrite
andfgetc
are both buffered so I don't see the difference. You could use 'mmap' instead of file io if you care about memory usage. I think the main thing is that you didn't list all your requirements in the question. You only stated that you wanted your code to run faster. I'm still not clear on what you are "securing" against. Are multiple processes operating on these files? Are you afraid of running out of memory? – JS1 Nov 15 '14 at 21:26