Search code examples
c#freeimage

How to create FreeImageBitmap from ushort[] making only one copy of the pixel data?


I'm using FreeImageNET for writing single-channel 16-bit PNGs under .NET, as this capability is not working with System.Drawing.Bitmap.

I get 16-bit data from a camera as ushort[]. I am saving this data to file as follows:

public void SavePngGray16(ushort[] data, string fname)
{
    // Create bitmap object to manage image: one 16-bit channel (true monochrome)
    Bitmap bmp16 = new Bitmap(ImageSize.Width, ImageSize.Height, PixelFormat.Format16bppGrayScale);

    // Copy received data into bitmap
    Rectangle rc = new Rectangle(Point.Empty, ImageSize);
    BitmapData data16 = bmp16.LockBits(rc, ImageLockMode.WriteOnly, bmp16.PixelFormat);
    // intermediary to enable casting in the Copy() call;
    // casting required because Copy() doesn't have a ushort[] flavor.
    Array ax = data;
    Marshal.Copy((short[])ax, 0, data16.Scan0, data.Length);
    bmp16.UnlockBits(data16);

    // 16-bit support, for real
    // Instantiate a FreeImage bitmap from the System.Drawing bitmap we just built
    //## this causes a full copy of the image data...
    //##   but FreeImageBitmap.LockBits() is UNIMPLEMENTED, so can't just build-and-fill
    //##   as above with a FreeImageBitmap instance
    FreeImageBitmap fbmp = new FreeImageBitmap(bmp16);
    // And save that as a 16-bit grayscale PNG
    fbmp.Save(fname, FREE_IMAGE_FORMAT.FIF_PNG, FREE_IMAGE_SAVE_FLAGS.PNG_Z_DEFAULT_COMPRESSION);
}

I would like to avoid copying the data twice (once to get the data into the Bitmap, once to get the data into the FreeImageBitmap). Is this possible?


Solution

  • You could use this constructor:

    public FreeImageBitmap(int width, int height, int stride, PixelFormat format, IntPtr scan0)
    

    You have width and height. stride you can put 0 (it is the padding between rows of an image). format is PixelFormat.Format16bppGrayScale. You obtain scan0 through pinning the ushort[] (if you look at the source file, in the end the array you pass will be pinned...)

    GCHandle handle = default(GCHandle);
    
    try
    {
        handle = GCHandle.Alloc(data, GCHandleType.Pinned);
        FreeImageBitmap fbmp = new FreeImageBitmap(width, height, 0, PixelFormat.Format16bppGrayScale, handle.AddrOfPinnedObject());
    }
    finally
    {
        if (handle.IsAllocated)
        {
            handle.Free();
        }
    }