public static void LoadImage(string file, out int width, out int height, out byte[] data) { if (!File.Exists(file)) { throw new FileNotFoundException("Texture file not found.", file); } IntPtr surfaceID = SDL_image.IMG_Load(file); // If image load fails, generate a default pink error texture if (surfaceID == IntPtr.Zero) { //throw new FileNotFoundException($"TextureDataFromStream: {SDL_GetError()}", file); surfaceID = SDL_CreateRGBSurfaceWithFormat(0, 32, 32, 0, SDL_PIXELFORMAT_ABGR8888); unsafe { SDL_Surface * surfacePtr = (SDL_Surface *)surfaceID; SDL_PixelFormat *pixelFormatPtr = (SDL_PixelFormat *)surfacePtr->format; SDL_FillRect(surfaceID, IntPtr.Zero, SDL_MapRGB((IntPtr)pixelFormatPtr, 255, 20, 147)); } } surfaceID = ConvertSurfaceFormat(surfaceID); unsafe { SDL_Surface *surface = (SDL_Surface *)surfaceID; width = surface->w; height = surface->h; data = new byte[width * height * 4]; Marshal.Copy(surface->pixels, data, 0, data.Length); } SDL_FreeSurface(surfaceID); // Enforce alpha for (int i = 0; i < data.Length; i += 4) { if (data[i + 3] == 0) { data[i] = 0; data[i + 1] = 0; data[i + 2] = 0; } } data = FlipImageData(width, height, 4, data); }
private static unsafe IntPtr ConvertSurfaceFormat(IntPtr surface) { IntPtr result = surface; unsafe { SDL_Surface * surPtr = (SDL_Surface *)surface; SDL_PixelFormat *pixelFormatPtr = (SDL_PixelFormat *)surPtr->format; // SurfaceFormat.Color is SDL_PIXELFORMAT_ABGR8888 if (pixelFormatPtr->format != SDL_PIXELFORMAT_ABGR8888) { // Create a properly formatted copy, free the old surface result = SDL_ConvertSurfaceFormat(surface, SDL_PIXELFORMAT_ABGR8888, 0); SDL_FreeSurface(surface); } } return(result); }
public static extern SDL_Surface *SDL_ConvertSurface(SDL_Surface *src, SDL_PixelFormat *fmt, uint flags);