To display images in C language, you can use the SDL2 library: initialize the SDL2 library; create a window; create a renderer; load an image; create an image texture; clear the renderer; render an image; update the display; main loop; destroy resource.
Display pictures in C language
In C language, you can use the SDL2 library (Simple DirectMedia Layer) to display image. The following steps describe how to use SDL2 to display images in C language:
1. Initialize the SDL2 library
<code class="c">#include <stdio.h> #include <SDL2/SDL.h> int main() { if (SDL_Init(SDL_INIT_VIDEO) != 0) { fprintf(stderr, "SDL_Init Error: %s\n", SDL_GetError()); return 1; }</code>
2. Create a window
<code class="c"> SDL_Window *window = SDL_CreateWindow("Image Viewer", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_SHOWN); if (window == NULL) { fprintf(stderr, "SDL_CreateWindow Error: %s\n", SDL_GetError()); SDL_Quit(); return 1; }</code>
3. Create a renderer
<code class="c"> SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (renderer == NULL) { fprintf(stderr, "SDL_CreateRenderer Error: %s\n", SDL_GetError()); SDL_DestroyWindow(window); SDL_Quit(); return 1; }</code>
4. Load an image
<code class="c"> SDL_Surface *image = SDL_LoadBMP("image.bmp"); if (image == NULL) { fprintf(stderr, "SDL_LoadBMP Error: %s\n", SDL_GetError()); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 1; }</code>
5. Create an image texture
<code class="c"> SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, image); SDL_FreeSurface(image); if (texture == NULL) { fprintf(stderr, "SDL_CreateTextureFromSurface Error: %s\n", SDL_GetError()); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 1; }</code>
6. Clear renderer
<code class="c"> SDL_RenderClear(renderer);</code>
7. Render image
<code class="c"> int w, h; SDL_QueryTexture(texture, NULL, NULL, &w, &h); SDL_Rect dstrect = { 0, 0, w, h }; SDL_RenderCopy(renderer, texture, NULL, &dstrect);</code>
8. Update Display
<code class="c"> SDL_RenderPresent(renderer);</code>
9. Main loop
<code class="c"> SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { break; } }</code>
10. Destroy resources
<code class="c"> SDL_DestroyTexture(texture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0; }</code>
The above is the detailed content of How to display pictures in C language code. For more information, please follow other related articles on the PHP Chinese website!