GithubHelp home page GithubHelp logo

smourier / wicnet Goto Github PK

View Code? Open in Web Editor NEW
24.0 4.0 4.0 34.26 MB

.NET interop classes for WIC (Windows Imaging Component), Direct2D and DirectWrite

License: MIT License

C# 99.95% Batchfile 0.05%
wic imaging direct2d dotnet dwrite winui3

wicnet's Introduction

WicNet

.NET interop classes for WIC (Windows Imaging Component) Direct2D, and DirectWrite, based on netstandard 2.0, with zero dependency (except for DirectN https://www.nuget.org/packages/DirectNStandard/)

Nuget Package is available here: https://www.nuget.org/packages/WicNet

Work in still progress, however most operations should work. Create an issue if something's not working or feature is missing.

Simple use case is load & save:

using (var bmp = WicBitmapSource.Load(@"myJpegFile.jpg"))
{
    bmp.Save("myHeicFile.heic");
}

Draw ellipse over an image and save (uses D2D):

using (var bmp = WicBitmapSource.Load("MyImag.jpg"))
{
    bmp.ConvertTo(WicPixelFormat.GUID_WICPixelFormat32bppBGR);  // needed to be able to work with Direct2D
    var width = 200;
    var height = width * bmp.Height / bmp.Width;
    using (var memBmp = new WicBitmapSource(width, height, WicPixelFormat.GUID_WICPixelFormat32bppPRGBA))
    using (var rt = memBmp.CreateDeviceContext())
    using (var dbmp = rt.CreateBitmapFromWicBitmap(bmp.ComObject))
    using (var brush = rt.CreateSolidColorBrush(_D3DCOLORVALUE.Red))
    {
        rt.BeginDraw();
        rt.DrawBitmap(dbmp, destinationRectangle: new D2D_RECT_F(new D2D_SIZE_F(memBmp.Size)));
        rt.DrawEllipse(new D2D1_ELLIPSE(width / 2, height / 2, Math.Min(width, height) / 2), brush, 4);
        rt.EndDraw();
        memBmp.Save("ellipse.jpg");
    }
}

Rotate image, convert to grayscale and save (uses Direct2D effects):

static void RotateAndGrayscale()
{
    using (var bmp = WicBitmapSource.Load("MyImage.jpg"))
    {
        bmp.Rotate(WICBitmapTransformOptions.WICBitmapTransformRotate90);
        bmp.ConvertTo(WicPixelFormat.GUID_WICPixelFormat32bppBGR); // needed to be able to work with Direct2D
        using (var newBmp = new WicBitmapSource(bmp.Width, bmp.Height, WicPixelFormat.GUID_WICPixelFormat32bppPRGBA))
        using (var rt = newBmp.CreateDeviceContext())
        using (var fx = rt.CreateEffect(Direct2DEffects.CLSID_D2D1Grayscale))
        using (var cb = rt.CreateBitmapFromWicBitmap(bmp.ComObject))
        {
            fx.SetInput(0, cb);
            rt.BeginDraw();
            rt.DrawImage(fx);
            rt.EndDraw();
            newBmp.Save("gray.jpg");
        }
    }
}

WicNetExplorer

WicNetExplorer is a GUI sample program that demonstrates how to use WicNet, it's capable of loading and saving images and shows WIC information:

image

WicNetExplorer demonstrates two Windows technologies for the WIC display surface:

WinUI3/WinRT interop

The WinUI3Tests program demonstrates WicNet (and therefore WIC) interop with WinRT's SoftwareBitmap and WinUI3:

private static SoftwareBitmap GetSoftwareBitmap(string filePath)
{
    using var bmp = WicBitmapSource.Load(filePath);

    // note: software bitmap doesn't seem to support color contexts
    // so we must transform it ourselves, building one using pixels after color transformation
    // this is the moral equivalent to WinRT's BitmapDecoder.GetPixelDataAsync (which uses Wic underneath...)
    // https://learn.microsoft.com/en-us/uwp/api/windows.graphics.imaging.bitmapdecoder.getpixeldataasync
    var ctx = bmp.GetColorContexts();
    if (ctx.Count > 0)
    {
        using var transformed = GetTransformed(bmp);
        if (transformed != null)
        {
            // get pixels as an array of bytes
            var bytes = transformed.CopyPixels();

            // get WinRT SoftwareBitmap
            var softwareBitmap = new SoftwareBitmap(
                BitmapPixelFormat.Bgra8,
                bmp.Width,
                bmp.Height,
                BitmapAlphaMode.Premultiplied);
            softwareBitmap.CopyFromBuffer(bytes.AsBuffer());
            return softwareBitmap;
        }
    }

    // software bitmap doesn't support all formats
    // https://learn.microsoft.com/en-us/uwp/api/windows.graphics.imaging.bitmappixelformat
    // and SoftwareBitmapSource only support Bgra8...
    bmp.ConvertTo(WicPixelFormat.GUID_WICPixelFormat32bppPBGRA);

    // software bitmap doesn't support "raw" IWicBitmapSource, it wants an IWicBitmap
    using var clone = bmp.Clone();
    return clone.WithSoftwareBitmap(true, ptr => SoftwareBitmap.FromAbi(ptr));
}

wicnet's People

Contributors

smourier avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

wicnet's Issues

`ID2D1Bitmap1.Map()` only returns 1 row of pixel data

Hi @smourier,

As my post from smourier/DirectN#34, I modified the function a bit to load all pixel data into a DataGridView.

public void LoadPixelDataIntoDataGrid()
{
    var bmpProps = new D2D1_BITMAP_PROPERTIES1()
    {
        bitmapOptions = D2D1_BITMAP_OPTIONS.D2D1_BITMAP_OPTIONS_CANNOT_DRAW | D2D1_BITMAP_OPTIONS.D2D1_BITMAP_OPTIONS_CPU_READ,
        pixelFormat = new D2D1_PIXEL_FORMAT()
        {
            alphaMode = D2D1_ALPHA_MODE.D2D1_ALPHA_MODE_PREMULTIPLIED,
            format = DXGI_FORMAT.DXGI_FORMAT_B8G8R8A8_UNORM,
        },
        dpiX = 96.0f,
        dpiY = 96.0f,
    };

    var size = _imageD2D.GetSize().ToD2D_SIZE_U();
    using var bitmap1 = _device.CreateBitmap<ID2D1Bitmap1>(size, bmpProps);
    bitmap1.CopyFromBitmap(_imageD2D);

    var map = bitmap1.Map(D2D1_MAP_OPTIONS.D2D1_MAP_OPTIONS_READ);
    var dataSize = (int)(size.width * size.height * 4);

    var bytes = new byte[dataSize];
    Marshal.Copy(map.bits, bytes, 0, dataSize);
    bitmap1.Unmap();

    // load all pixel data into data grid view
    dt.DataSource = bytes.Select((i, index) => new
    {
        Index = index,
        Value = i.ToString(),
    }).ToList();
}

The problem

It only returns the first row of the pixel data; the rest values are just 0!
In the demo, I used 4x4 PNG image with alpha pixels, and draw 100X onto the window.

image

Full source code:

WinFormsApp1.zip

`IDWriteTextFormat` argument in `ID2D1DeviceContext.DrawText(string, IDWriteTextFormat, ...)`

Hi, I managed to draw almost everything using this library, except text. There are functions for drawing text in ID2D1RenderTargetExtensions but it requires IDWriteTextFormat which is not found in WicNet.

ID2D1HwndRenderTarget _renderTarget;
ID2D1DeviceContext _context;
IComObject<ID2D1Factory> _factory = D2D1Functions.D2D1CreateFactory(D2D1_FACTORY_TYPE.D2D1_FACTORY_TYPE_SINGLE_THREADED);


var hwndRenderTargetProps = new D2D1_HWND_RENDER_TARGET_PROPERTIES()
{
    hwnd = this.Handle,
    pixelSize = new D2D_SIZE_U((uint)Width, (uint)Height),
};

_factory.Object.CreateHwndRenderTarget(new D2D1_RENDER_TARGET_PROPERTIES(), hwndRenderTargetProps, out _renderTarget)
    .ThrowOnError();
_renderTarget.Resize(new(ClientSize.Width, ClientSize.Height));
_renderTarget.SetDpi(96.0f, 96.0f);
_context = (ID2D1DeviceContext)_renderTarget;


// start drawing
_context.BeginDraw();

D2D_RECT_F rect = new(0, 0, 200, 100);
var brush = ...

_context.DrawText("hello world", <IDWriteTextFormat??>, rect, brush);


_context.EndDraw();

This is the extension function in ID2D1RenderTargetExtensions:

// in ID2D1RenderTargetExtensions
public static void DrawText(this ID2D1RenderTarget renderTarget,
  string text,
  IDWriteTextFormat format,
  D2D_RECT_F rect,
  ID2D1Brush brush,
  D2D1_DRAW_TEXT_OPTIONS options = D2D1_DRAW_TEXT_OPTIONS.D2D1_DRAW_TEXT_OPTIONS_NONE,
  DWRITE_MEASURING_MODE measuringMode = DWRITE_MEASURING_MODE.DWRITE_MEASURING_MODE_NATURAL)
{
    // ...
}

Thank you!

How to pass `System.Windows.Media.Imaging.BitmapSource` to `WicBitmapSource.FromSource()`

Hi, I'm playing around with this library on .NET 6
I use Magick.NET to read the image, then convert it to System.Windows.Media.Imaging.BitmapSource.

using var imgM = new MagickImage("photo.png");
System.Windows.Media.Imaging.BitmapSource src = imgM.ToBitmapSource();


using var bmp = WicBitmapSource.FromSource(src); // ERROR!

image

Is there any way to convert System.Windows.Media.Imaging.BitmapSource to WicNet.WicBitmapSource?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.