C语言显示jpg图片,正常的代码
时间: 2024-02-12 20:08:57 浏览: 95
以下是一份使用 SDL_image 库加载和显示 JPG 图片的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
int main(int argc, char *argv[])
{
// 初始化 SDL2
if (SDL_Init(SDL_INIT_VIDEO) != 0) {
fprintf(stderr, "Failed to initialize SDL2: %s\n", SDL_GetError());
return 1;
}
// 初始化 SDL_image
if ((IMG_Init(IMG_INIT_JPG) & IMG_INIT_JPG) != IMG_INIT_JPG) {
fprintf(stderr, "Failed to initialize SDL_image: %s\n", IMG_GetError());
SDL_Quit();
return 1;
}
// 加载 JPG 图片
SDL_Surface *image_surface = IMG_Load("test.jpg");
if (!image_surface) {
fprintf(stderr, "Failed to load image: %s\n", IMG_GetError());
IMG_Quit();
SDL_Quit();
return 1;
}
// 创建窗口和渲染器
SDL_Window *window = SDL_CreateWindow("JPG Image Viewer",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
image_surface->w,
image_surface->h,
SDL_WINDOW_SHOWN);
if (!window) {
fprintf(stderr, "Failed to create window: %s\n", SDL_GetError());
SDL_FreeSurface(image_surface);
IMG_Quit();
SDL_Quit();
return 1;
}
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (!renderer) {
fprintf(stderr, "Failed to create renderer: %s\n", SDL_GetError());
SDL_DestroyWindow(window);
SDL_FreeSurface(image_surface);
IMG_Quit();
SDL_Quit();
return 1;
}
// 将图像渲染到屏幕上
SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, image_surface);
if (!texture) {
fprintf(stderr, "Failed to create texture: %s\n", SDL_GetError());
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_FreeSurface(image_surface);
IMG_Quit();
SDL_Quit();
return 1;
}
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
// 等待窗口关闭
SDL_Event event;
while (1) {
if (SDL_WaitEvent(&event) != 0 && event.type == SDL_QUIT)
break;
}
// 释放资源
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_FreeSurface(image_surface);
IMG_Quit();
SDL_Quit();
return 0;
}
```
这个代码使用了 SDL2 和 SDL_image 库来加载和显示 JPG 图片。它通过使用 SDL_CreateWindow() 和 SDL_CreateRenderer() 创建了一个窗口和一个渲染器,并使用 SDL_CreateTextureFromSurface() 将图像渲染到屏幕上。最后,它使用 SDL_WaitEvent() 等待窗口关闭事件,然后释放了所有使用的资源。
阅读全文