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";
ctx.drawImage(img,10,10,20,20,30,30,10,10);
//drawing more images...
something(canvas.toDataURL('image/png'));
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.
+3
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
g.DrawImage(Image.FromFile("a.png"),
new Rectangle(30, 30, 10, 10), 10, 10, 20, 20,
GraphicsUnit.Pixel);
// 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);
}
+5
source to share
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));
drawingContext.Close();
// Now to save it
RenderTargetBitmap bmp = new RenderTargetBitmap(_imageWidth, _imageHeight, 96, 96, PixelFormats.Pbgra32);
bmp.Render(drawingVisual);
PngBitmapEncoder png = new PngBitmapEncoder();
png.Frames.Add(BitmapFrame.Create(bmp));
byte[] imageBinary = null;
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
png.Save(memoryStream);
imageBinary = memoryStream.GetBuffer();
}
0
source to share