需要一个示例 png 将图像位图映射到内存 - stbi

问题描述 投票:0回答:1

我正在编写一个将 png 图像转换为位图的示例代码。这是大项目的一部分,先尝试一下示例。

使用下面的代码一切正常。唯一的问题是我需要将转换后的数据保存到内存中而不是写入磁盘。但我没有找到任何函数调用来转换为位图并给我转换后的数据。我只有写入磁盘的方法。

这是 stbi_load_from_memory 的工作示例并将转换后的图像写入磁盘

int main() {
    // Specify the file path
    const char* file_path = "img1.png";
    long file_size;
    int width, height, channels,result;
    unsigned char *file_data, *image_data;
    unsigned int bytes_read;

    // Open the file in binary mode
    FILE* file = fopen(file_path, "rb");
    if (file == NULL) {
        fprintf(stderr, "Error opening file: %s\n", file_path);
        return 1;
    }

    // Determine the size of the file
    fseek(file, 0, SEEK_END);
    file_size = ftell(file);
    fseek(file, 0, SEEK_SET);

    // Allocate memory for the file content
    file_data = (unsigned char*)malloc(file_size);
    if (file_data == NULL) {
        fprintf(stderr, "Memory allocation error\n");
        fclose(file);
        return 1;
    }

    // Read the file content into memory
    bytes_read = fread(file_data, 1, file_size, file);
    fclose(file);

    if (bytes_read != file_size) {
        fprintf(stderr, "Error reading file: %s\n", file_path);
        free(file_data);
        return 1;
    }

    // Load image data from memory
    
    image_data = stbi_load_from_memory(file_data, file_size, &width, &height, &channels, 0);

    if (image_data != NULL) {
        // Image loading was successful

        // You can now use the 'image_data', 'width', 'height', and 'channels' variables as needed.

        // For example, print some information about the image:
        printf("Image Width: %d\n", width);
        printf("Image Height: %d\n", height);
        printf("Number of Channels: %d\n", channels);

        // Save the image as a BMP file
        result = stbi_write_bmp("sampleres.bmp", width, height, channels, image_data);

        if (result != 0) {
            printf("BMP file saved successfully: %s\n", "sampleres.bmp");
        } else {
            printf("Error saving BMP file: %s\n", "sampleres.bmp");
        }

        // Clean up the allocated image data when done
        stbi_image_free(image_data);
    } else {
        // Image loading failed
        printf("Error loading image from memory.\n");
    }

    return 0;
}

编辑: 我还尝试将图像数据转储到磁盘上。没成功

// Write the data to the file
    bytes_written = fwrite(image_data, 1, file_size, file);

    if (bytes_written != file_size) {
        fprintf(stderr, "Error writing to file:");
    }

    // Close the file
    fclose(file);
    }

有人有一个可以转换为位图的示例,并为我提供变量或内存结构中转换后的数据吗?

c png
1个回答
0
投票

image_data
处的字节是位图。那里有
height
*
width
*
channels
个字节,按从最高维度到最低维度的顺序排列。所以它以
channels
字节开始,每行重复
width
次,有
height
行。完成。

© www.soinside.com 2019 - 2024. All rights reserved.