8

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.

1
  • 1
    @Mat thanks but the question seems ok for me and I answered my question, and when someone googles same problem, he may find this 'downvoted' question useful Commented Dec 31, 2017 at 10:39

1 Answer 1

14

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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

In a new .net core web app, I also had to install System.Drawing.Common Also, don't forget to dispose of all those resources (Bitmap, Graphics, Pen, SolidBrush)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.