MVC dynamically create and return image from Controller

I've found that I have a need to create an image dynamically (or read from a file) and return it directly from a controller. We can do that pretty easily.

First add this method to a controller:
public class ImageController : Controller
     public void Generate()  
         //when we create a pixel we need to make it a random color  
         Random randomGen = new Random();  
         Bitmap image = new Bitmap( width, height );  
         // create the graphics drawing tool  
         using ( Graphics gfx = Graphics.FromImage( image ) )  
         // create a solid brush to draw the image, I'm using random colors  
         using ( SolidBrush brush = new SolidBrush( Color.FromArgb( randomGen.Next( 255 ), 
                                                    randomGen.Next( 255 ),
                                                    randomGen.Next( 255 ) ) ) )  
           gfx.FillRectangle( brush, 0, 0, width, height );  

         // save the image to a memory stream  
         MemoryStream ms = new MemoryStream();  
         pixel.Image.Save( ms, ImageFormat.Jpeg );  
         ms.Position = 0;  

         // send the image back  
         return new FileStreamResult( ms, "image/jpeg" );  

       catch(Exception ex)  
         Console.WriteLine( ex.ToString() );  

Now you in an image tag set the src property to your controllers action as follows:

  img src="@Url.Content("~/ImageController/Generate")" 


Popular posts from this blog

C# Form Application in Kiosk Mode/Fullscreen

C# using a transaction with ODBC

Notify Icon Text vs BalloonTipText