1 module gfm.sdl2.sdlimage; 2 3 import std..string; 4 5 import derelict.util.exception, 6 derelict.sdl2.sdl, 7 derelict.sdl2.image; 8 9 static if( __VERSION__ >= 2067 ) 10 import std.experimental.logger; 11 else 12 import std.historical.logger; 13 14 import gfm.sdl2.sdl, 15 gfm.sdl2.surface; 16 17 /// Load images using SDL_image, a SDL companion library able to load various image formats. 18 final class SDLImage 19 { 20 public 21 { 22 /// Loads the SDL_image library. 23 /// SDL must be already initialized. 24 /// Throws: $(D SDL2Exception) on error. 25 this(SDL2 sdl2, int flags = IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF | IMG_INIT_WEBP) 26 { 27 _sdl2 = sdl2; // force loading of SDL first 28 _logger = sdl2._logger; 29 _SDLImageInitialized = false; 30 31 try 32 { 33 DerelictSDL2Image.load(); 34 } 35 catch(DerelictException e) 36 { 37 throw new SDL2Exception(e.msg); 38 } 39 40 int inited = IMG_Init(flags); 41 _SDLImageInitialized = true; 42 } 43 44 /// Releases the SDL resource. 45 ~this() 46 { 47 if (_SDLImageInitialized) 48 { 49 debug ensureNotInGC("SDLImage"); 50 _SDLImageInitialized = false; 51 IMG_Quit(); 52 } 53 } 54 deprecated("Use .destroy instead") void close(){} 55 56 /// Load an image. 57 /// Returns: A SDL surface with loaded content. 58 /// Throws: $(D SDL2Exception) on error. 59 SDL2Surface load(string path) 60 { 61 immutable(char)* pathz = toStringz(path); 62 SDL_Surface* surface = IMG_Load(pathz); 63 if (surface is null) 64 throwSDL2ImageException("IMG_Load"); 65 66 return new SDL2Surface(_sdl2, surface, SDL2Surface.Owned.YES); 67 } 68 } 69 70 private 71 { 72 Logger _logger; 73 SDL2 _sdl2; 74 bool _SDLImageInitialized; 75 76 void throwSDL2ImageException(string callThatFailed) 77 { 78 string message = format("%s failed: %s", callThatFailed, getErrorString()); 79 throw new SDL2Exception(message); 80 } 81 82 const(char)[] getErrorString() 83 { 84 return fromStringz(IMG_GetError()); 85 } 86 } 87 }