首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在C中裁剪.ppm文件

在C语言中,裁剪.ppm文件通常涉及到图像处理和文件操作。.ppm文件是一种图像文件格式,用于存储矩阵形式的图像数据。以下是一个简单的示例,展示了如何在C语言中裁剪.ppm文件:

代码语言:c
复制
#include<stdio.h>
#include <stdlib.h>
#include<string.h>

#define MAX_COMMENT_LENGTH 70
#define MAX_LINE_LENGTH 70

typedef struct {
    int width;
    int height;
    int max_color_value;
    char comment[MAX_COMMENT_LENGTH + 1];
    unsigned char *pixels;
} PPMImage;

void read_ppm_header(FILE *file, PPMImage *image) {
    char line[MAX_LINE_LENGTH + 1];
    fgets(line, MAX_LINE_LENGTH + 1, file);
    if (strcmp(line, "P6\n") != 0) {
        fprintf(stderr, "Error: Invalid PPM file format.\n");
        exit(1);
    }

    fgets(line, MAX_LINE_LENGTH + 1, file);
    sscanf(line, "%d %d\n", &image->width, &image->height);

    fgets(line, MAX_LINE_LENGTH + 1, file);
    sscanf(line, "%d\n", &image->max_color_value);

    fgets(line, MAX_LINE_LENGTH + 1, file);
    strncpy(image->comment, line, MAX_COMMENT_LENGTH);
    image->comment[MAX_COMMENT_LENGTH] = '\0';
}

PPMImage *read_ppm_image(const char *filename) {
    FILE *file = fopen(filename, "rb");
    if (file == NULL) {
        fprintf(stderr, "Error: Cannot open file %s.\n", filename);
        exit(1);
    }

    PPMImage *image = (PPMImage *)malloc(sizeof(PPMImage));
    read_ppm_header(file, image);

    int pixel_count = image->width * image->height;
    image->pixels = (unsigned char *)malloc(pixel_count * 3);
    fread(image->pixels, 1, pixel_count * 3, file);

    fclose(file);
    return image;
}

void write_ppm_image(const char *filename, PPMImage *image) {
    FILE *file = fopen(filename, "wb");
    if (file == NULL) {
        fprintf(stderr, "Error: Cannot open file %s.\n", filename);
        exit(1);
    }

    fprintf(file, "P6\n");
    fprintf(file, "%d %d\n", image->width, image->height);
    fprintf(file, "%d\n", image->max_color_value);
    fprintf(file, "%s", image->comment);

    int pixel_count = image->width * image->height;
    fwrite(image->pixels, 1, pixel_count * 3, file);

    fclose(file);
}

void crop_ppm_image(PPMImage *image, int x, int y, int width, int height) {
    unsigned char *cropped_pixels = (unsigned char *)malloc(width * height * 3);
    int src_row_stride = image->width * 3;
    int dst_row_stride = width * 3;

    for (int i = 0; i< height; i++) {
        memcpy(cropped_pixels + i * dst_row_stride,
               image->pixels + (y + i) * src_row_stride + x * 3,
               width * 3);
    }

    free(image->pixels);
    image->pixels = cropped_pixels;
    image->width = width;
    image->height = height;
}

int main() {
    PPMImage *image = read_ppm_image("input.ppm");
    crop_ppm_image(image, 10, 10, 100, 100);
    write_ppm_image("output.ppm", image);
    free(image->pixels);
    free(image);
    return 0;
}

这个示例代码包含了读取.ppm文件、裁剪.ppm文件和写入.ppm文件的功能。在main函数中,我们首先读取一个名为input.ppm的.ppm文件,然后裁剪它,最后将裁剪后的图像写入一个名为output.ppm的文件。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券