Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Core Generate Image file dynamically

How is it possible to generate an image all in the controller and return it as an image file? For example if link is:

www.test.com/generate?width=100&height=50&color=red

This shall generate 100x50 red image and return it, and if I set this link as a source of Image View on front, it shall draw that image. It shall work as a service which does not have any connection to UI either HTML or other platforms like iOS UIImageView and Android ImageView.

like image 830
mister_giga Avatar asked Dec 13 '22 19:12

mister_giga


1 Answers

I managed to draw using System.Drawing and System.Drawing.Drawing2D - Graphics class

Bitmap bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

Graphics graphics = Graphics.FromImage(bitmap);

var pen = new Pen(lineColor, widthLine);

graphics.FillRectangle(new SolidBrush(bgColor), new Rectangle(0, 0, width, height));

and graphics has all necessary methods for drawing, after drawing finished use the bitmap to create image file and return HttpResponseMessage from ASP net action

using (MemoryStream ms = new MemoryStream())
{
    bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new ByteArrayContent(ms.ToArray());
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
    return result;
}

This was all I wanted and not the useless down votes :)

like image 138
mister_giga Avatar answered Dec 23 '22 22:12

mister_giga