简体   繁体   English

尝试在 C 中将图像作为字节数组读写

[英]Trying to read and write image as byte array in C

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.该文件仅使用字节数组加载并保存为图像,但结果已损坏。 在此处输入图像描述

I wonder what could be wrong here.我想知道这里可能出了什么问题。

On windows you need to call fopen() with the 'b' flag to read and write binary files.在 windows 上,您需要使用 'b' 标志调用fopen()以读取和写入二进制文件。 You don't need memset() (and if you did, prefer calloc() instead).您不需要memset() (如果需要,则更喜欢calloc() )。 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.如果您的输入文件很大,您可能会看到一次写入 4k 或 8k 的类似性能,并消除 memory 耗尽的错误情况。 In either case I recommend you check the return value from fread() and fread() and wrap the read/write operation in a loop.无论哪种情况,我都建议您检查fread()fread()的返回值,并将读/写操作包装在一个循环中。

#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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM