C #: Equivalent to HTML5 Canvas in C #

My goal is to load PNG images with transparency via a URI, crop them and draw on a canvas, and then save the canvas images as a png file.

In javascript it will look like this:

var canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');

var img = new Image();
img.src = "a.png";


//drawing more images...



How can I do this in C # Visual Studios 2013? What's the closest thing to this JS code?

I don't mind using WPF or Winforms. I don't need to display the image. I only need to save it.


source to share

2 answers

One way to do this is with GDI + (assumed using System.Drawing;


using (var b = new Bitmap()) {            // This is your canvas
    Graphics g = Graphics.FromImage(b);   // This is your graphics context

                new Rectangle(30, 30, 10, 10), 10, 10, 20, 20,

    // Do something with b (e.g. b.Save(…))


If you want the same data URI, it's (assumed using System.Drawing.Imaging;


using (var ms = new MemoryStream()) {
    using (var b = new Bitmap()) {
        // …

        b.Save(ms, ImageFormat.Png);

    string base64 = Convert.ToBase64String(ms.ToArray());
    something("data:image/png;base64," + base64);




You can use WPF as your image generator.

Required namespaces:

using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;


And a sample code snippet to run:

DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();

// Let draw a rectangle!
var gradientBrush = new LinearGradientBrush();
gradientBrush.GradientStops.Add(new GradientStop(Colors.Azure, 0.0));
gradientBrush.GradientStops.Add(new GradientStop(Colors.SteelBlue, 1.0));
drawingContext.DrawRectangle(gradientBrush, null, new Rect(0, 0, _imageWidth, _imageHeight));


// Now to save it
RenderTargetBitmap bmp = new RenderTargetBitmap(_imageWidth, _imageHeight, 96, 96, PixelFormats.Pbgra32);

PngBitmapEncoder png = new PngBitmapEncoder();

byte[] imageBinary = null;
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
    imageBinary = memoryStream.GetBuffer();




All Articles