Home > Software design >  Trying to read and write image as byte array in C
Trying to read and write image as byte array in C

Time:11-30

The following code is supposed to load and save an image file (and not only) into a copy file:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    FILE* file = fopen("pexels.jpg", "r");
    if (!file) {
        perror("File opening failed");
        return EXIT_FAILURE;
    }


    fseek(file, 0, SEEK_END);
    long file_size = ftell(file);
    fseek(file, 0, SEEK_SET);

    void* data = malloc(file_size);
    memset(data, 0, file_size);
    fread(data, 1, file_size, file);
    fclose(file);

    FILE *copy = fopen("copy.jpg", "w");
    if (!copy) {
        perror("File opening failed");
        free(data);
        return EXIT_FAILURE;
    }
    fwrite(data, 1, file_size, copy);
    free(data);
    fclose(copy);
}

the file gets loaded and saved as an image using only array of bytes but the result gets corrupted. enter image description here

I wonder what could be wrong here.

CodePudding user response:

On windows you need to call fopen() with the 'b' flag to read and write binary files. You don't need memset() (and if you did prefer calloc() instead). You will probably see similar performance writing 4k or 8k at a time and eliminate the error case of running out of memory if your input file is huge. In either case I recommend you check the return value from fread() and fread() and wrap the read/write operation in a loop.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    FILE* file = fopen("pexels.jpg", "br");
    if (!file) {
        perror("File opening failed");
        return EXIT_FAILURE;
    }

    fseek(file, 0, SEEK_END);
    long file_size = ftell(file);
    fseek(file, 0, SEEK_SET);

    void* data = malloc(file_size);
    fread(data, 1, file_size, file);
    fclose(file);

    FILE *copy = fopen("copy.jpg", "bw");
    if (!copy) {
        perror("File opening failed");
        free(data);
        return EXIT_FAILURE;
    }
    fwrite(data, 1, file_size, copy);
    free(data);
    fclose(copy);
}
  • Related