ASP.net 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()  
     {  
       try  
       {  
         //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")" 

Comments

Popular posts from this blog

String.Replace vs Regex.Replace

C# Producer Consumer using Rabbit MQ

C# Form Application in Kiosk Mode/Fullscreen