StbImageSharp

repository·master·Indexed 43 days ago

https://github.com/stbsharp/stbimagesharp

A pure C# port of the stb_image.h C library providing high-performance image loading for JPG, PNG, BMP, TGA, PSD, GIF, and HDR formats without native binaries. It features the ImageResult class for standard formats, ImageResultFloat for HDR content, and specialized support for animated GIF frames via AnimatedFrameResult.

Tokens
2.2K
Snippets
10
Records
14
Agent score
55%

What's inside StbImageSharp

  1. Add reference to StbImageSharp

    master

    You can include StbImageSharp in your project using either NuGet or as a Git submodule.

    Option 1: NuGet

    Install via the NuGet package manager.

    Option 2: Git Submodule

    1. Add the submodule: git submodule add https://github.com/StbSharp/StbImageSharp.git
    2. Choose one of the following integration methods:
      • Add src/StbImageSharp.csproj directly to your solution.
      • Include the .cs files from the src folder directly in your project. If you choose this method, you may want to add the STBSHARP_INTERNAL build compilation symbol to your project to keep StbImageSharp classes internal.
    git submodule add https://github.com/StbSharp/StbImageSharp.git
  2. Use ColorComponents to specify required image channels

    master
    When calling ImageResultFloat.FromStream or ImageResultFloat.FromMemory, you can pass a ColorComponents value to specify the desired number of color channels in the output. If ColorComponents.Default is used, the library will use the components present in the source image.
  3. Convert ImageResult to WinForms Bitmap

    master

    To convert ImageResult bytes to a WinForms Bitmap, you may need to manually convert the pixel format (e.g., from RGBA to BGRA) before copying the data using Marshal.Copy and BitmapData.

    byte[] data = image.Data;
    // Convert rgba to bgra
    for (int i = 0; i < x*y; ++i)
    {
    	byte r = data[i*4];
    	byte g = data[i*4 + 1];
    	byte b = data[i*4 + 2];
    	byte a = data[i*4 + 3];
    
    	data[i*4] = b;
    	data[i*4 + 1] = g;
    	data[i*4 + 2] = r;
    	data[i*4 + 3] = a;
    }
    
    // Create Bitmap
    Bitmap bmp = new Bitmap(_loadedImage.Width, _loadedImage.Height, PixelFormat.Format32bppArgb);
    BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, _loadedImage.Width, _loadedImage.Height), ImageLockMode.WriteOnly, bmp.PixelFormat);
    
    Marshal.Copy(data, 0, bmpData.Scan0, bmpData.Stride*bmp.Height);
    bmp.UnlockBits(bmpData);
  4. Convert ImageResult to MonoGame Texture2D

    master

    To use a loaded ImageResult in a MonoGame application, create a new Texture2D with the image's dimensions and set its data using image.Data.

    Texture2D texture = new Texture2D(GraphicsDevice, image.Width, image.Height, false, SurfaceFormat.Color);
    texture.SetData(image.Data);
  5. Load images using ImageResult.FromStream and ImageResult.FromMemory

    master

    StbImageSharp provides utility classes to wrap the complex raw pointer API. The ImageResult class is the primary way to load standard image formats (JPG, PNG, BMP, TGA, PSD, GIF).

    • ImageResult.FromStream(stream, colorComponents): Loads an image from a Stream.
    • ImageResult.FromMemory(buffer, colorComponents): Loads an image from a byte[] array.

    Both methods will throw an exception if the image loading fails. You should specify the desired color components using ColorComponents (e.g., ColorComponents.RedGreenBlueAlpha).

    // From Stream
    using(var stream = File.OpenRead(path))
    {
      ImageResult image = ImageResult.FromStream(stream, ColorComponents.RedGreenBlueAlpha);
    }
    
    // From Memory
    byte[] buffer = File.ReadAllBytes(path);
    ImageResult image = ImageResult.FromMemory(buffer, ColorComponents.RedGreenBlueAlpha);
  6. Load animated GIF frames

    master

    To handle animated GIFs, use ImageResult.AnimatedGifFramesFromStream(stream). This returns an enumerable of AnimatedFrameResult objects, allowing you to iterate through every frame and its associated delay.

    foreach(AnimatedFrameResult frame in ImageResult.AnimatedGifFramesFromStream(stream))
    {
        // Do something with a frame
    }
  7. Get image metadata with ImageInfo

    master

    Use the ImageInfo class to retrieve image metadata (width, height, color components, etc.) without fully decoding the pixel data. ImageInfo.FromStream(stream) returns null if the image type is not supported.

    ImageInfo? info = ImageInfo.FromStream(imageStream);
  8. Extract animated GIF frames from a Stream

    master

    To handle animated formats like GIFs, use ImageResult.AnimatedGifFramesFromStream. This returns an IEnumerable<AnimatedFrameResult>, allowing you to iterate through each frame of the animation.

    using StbImageSharp;
    using System.IO;
    
    // ...
    using (var stream = File.OpenRead("animation.gif"))
    {
        var frames = ImageResult.AnimatedGifFramesFromStream(stream, ColorComponents.Rgba);
        foreach (var frame in frames)
        {
            // Process each AnimatedFrameResult
        }
    }
  9. Decode images to floating-point pixel data with ImageResultFloat

    master

    Use ImageResultFloat to decode image data into a format where pixel values are represented as float values. This is useful for high-precision image processing or HDR content. You can decode from a Stream or a byte[] array.

    Available methods:

    • FromStream(Stream stream, ColorComponents requiredComponents = ColorComponents.Default): Decodes an image from a stream.
    • FromMemory(byte[] data, ColorComponents requiredComponents = ColorComponents.Default): Decodes an image from a byte array.

    The resulting object contains the image dimensions, the source color components, the requested color components, and a flat float[] array containing the pixel data.

    // Example: Decoding from a byte array
    byte[] imageData = File.ReadAllBytes("image.png");
    var result = ImageResultFloat.FromMemory(imageData, ColorComponents.Rgba);
    
    int width = result.Width;
    int height = result.Height;
    float[] pixels = result.Data;
  10. Decode an image from a Stream

    master

    Use ImageResult.FromStream to decode an image from a System.IO.Stream. You can optionally specify the requiredComponents to request a specific color format (e.g., RGBA).

    using StbImageSharp;
    using System.IO;
    
    // ...
    using (var stream = File.OpenRead("image.png"))
    {
        ImageResult image = ImageResult.FromStream(stream, ColorComponents.Rgba);
        // Access image.Data, image.Width, image.Height, etc.
    }
  11. Decode an image from a byte array

    master

    Use ImageResult.FromMemory to decode an image directly from a byte[]. This is a convenience wrapper around FromStream using a MemoryStream.

    using StbImageSharp;
    
    // ...
    byte[] fileBytes = File.ReadAllBytes("image.jpg");
    ImageResult image = ImageResult.FromMemory(fileBytes, ColorComponents.Rgb);