首页 > 解决方案 > 在c中使用bmp文件截屏?

问题描述

我正在尝试使用 c 创建一个 3D 游戏。

添加标志“--save”时,游戏会截取屏幕截图并保存。

所以要做到这一点(从游戏中截取屏幕截图)。我必须使用BMP 文件,所以我必须使用 c.

编码:

#include "../includes/cub3d.h"

t_screenshot        *ft_init_shot(t_mlx *mlx)
{
    t_screenshot    *takeshot;

    takeshot = malloc(1 * sizeof(t_screenshot));
    takeshot->width = w;
    takeshot->height = h;
    takeshot->bitcount = 24;
    takeshot->width_in_bytes = ((takeshot->width * takeshot->bitcount + 31) / 32) * 4;
    takeshot->imagesize = takeshot->width_in_bytes * takeshot->height;
    takeshot->filesize = 54 + takeshot->imagesize;
    return (takeshot);
}

unsigned char       *ft_bitheader(t_mlx *mlx)
{
    unsigned char    *header;
    uint32_t bisize;
    uint32_t bfoffbits;
    uint16_t biplanes;
    
    header =(unsigned char *)malloc(54 * sizeof(char));
    bisize = 40;
    bfoffbits = 54;
    biplanes = 1;
    memcpy(header, "BM", 2);
    memcpy(header + 2 , &mlx->shot->filesize, 4);
    memcpy(header + 10, &bfoffbits, 4);
    memcpy(header + 14, &bisize, 4);
    memcpy(header + 18, &mlx->shot->width, 4);
    memcpy(header + 22, &mlx->shot->height, 4);
    memcpy(header + 26, &biplanes, 2);
    memcpy(header + 28, &mlx->shot->bitcount, 2);
    memcpy(header + 34, &mlx->shot->imagesize, 4);
    return (header);
}

void                screen_shot(t_mlx *mlx)
{
    ft_move(mlx);
    ft_update(mlx, YES);
    mlx->shot = ft_init_shot(mlx);
    mlx->shot->header = ft_bitheader(mlx);
    screno(mlx);
}
 
void                screno(t_mlx *mlx)
{
    int x ;
    int y ;
    int row;
    int col;

    x = 0;
    y = 0;
    row = mlx->shot->height - 1;
    col = 0;
    unsigned char* buf = malloc(mlx->shot->imagesize);
    while (row >= 0)
    {
        y = 0;
        col = 0;
        while (col < mlx->shot->width)
        {
            int red = (mlx->tex.img_data[x * w + y] >> 16) & 0xFF;
            int green = (mlx->tex.img_data[x * w + y] >> 8) & 0xFF;
            int blue = mlx->tex.img_data[x * w + y] & 0xFF;
            buf[row * mlx->shot->width_in_bytes + col * 3 + 0] = blue;
            buf[row * mlx->shot->width_in_bytes + col * 3 + 1] = green;
            buf[row * mlx->shot->width_in_bytes + col * 3 + 2] = red;
            col++;
            y++;
        }
        row--;
        x++;
    }
    ft_printf("Taking ScreenShoot....\n");
    FILE *image = fopen("screenshot.bmp", "wb");
    ft_printf("ScreenShot Has been saved under The name 'screenshot.bmp']\n");
    fwrite(mlx->shot->header, 1, 54, image);
    fwrite((char*)buf, 1, mlx->shot->imagesize, image);
    fclose(image);
    free(buf);
}

问题是当我编译此代码时,图像有时会出现,有时会出现此错误:

截图看看我得到的错误

感谢您的帮助。

标签: cbmp

解决方案


推荐阅读