Search code examples
imagesharp

Load and Save opaque 8 bit PNG Files using ImageSharp


I am trying to Load -> Manipulate byte array directly -> Save an 8 bit png image.

I would like to use ImageSharp to compare its speeds to my current library, however in their code example they require the pixel type to be defined (they use Rgba32):

using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;

// Image.Load(string path) is a shortcut for our default type. 
// Other pixel formats use Image.Load<TPixel>(string path))
using (Image<Rgba32> image = Image.Load("foo.jpg"))
{
    image.Mutate(x => x
         .Resize(image.Width / 2, image.Height / 2)
         .Grayscale());
    image.Save("bar.jpg"); // Automatic encoder selected based on extension.
}

I looked through the pixel types: https://github.com/SixLabors/ImageSharp/tree/master/src/ImageSharp/PixelFormats

But there is no grayscale 8 bit pixel type.


Solution

  • As of 1.0.0-beta0005 There's no Gray8 pixel format because we couldn't decide what color model to use when converting from Rgb (We need that internally). ITU-R Recommendation BT.709 seems like the sensible solution because that is what png supports and what we use when saving an image as an 8bit grayscale png so it's on my TODO list.

    https://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale

    So... currently you need to use either Rgb24 or Rgba32 when decoding the images.

    Update.

    As of 1.0.0-dev002094 this is now possible! We have two new pixel formats. Gray8 and Gray16 that carry only the luminance component of a pixel.

    using (Image<Gray8> image = Image.Load<Gray8>("foo.png"))
    {
        image.Mutate(x => x
             .Resize(image.Width / 2, image.Height / 2));
    
        image.Save("bar.png");
    }
    

    Note. The png encoder by default will save the image in the input color type and bit depth. If you want to encode the image in a different color type you will need to new up an PngEncoder instance with the ColorType and BitDepth properties set.