PROWAREtech

articles » archived » asp-net » mvc » image-creation-and-download

ASP.NET: MVC Bitmap Image Creation and Download

Create an Image from within the MVC controller and send it to the browser (.NET Framework).

Download any file type from a controller in ASP.NET MVC using FileContentResult.

This example creates a bitmap (jpeg) and sends it to the browser. The key is copying the output to a byte array.

See also: ASP.NET Core: MVC Bitmap Image Creation and Download

// Controller Method
public FileContentResult CreateBitmap()
{
	int height = 200;
	int width = 200;
	System.Random r = new System.Random();
	using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
	{
		using(System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmp))
		{
			g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
			g.Clear(System.Drawing.Color.LightGray);
			g.DrawRectangle(System.Drawing.Pens.White, 1, 1, width - 3, height - 3);
			g.DrawRectangle(System.Drawing.Pens.Gray, 2, 2, width - 3, height - 3);
			g.DrawRectangle(System.Drawing.Pens.Black, 0, 0, width, height);
			g.DrawString("Refresh Me!", new System.Drawing.Font("Arial", 10, System.Drawing.FontStyle.Bold),
				System.Drawing.SystemBrushes.WindowText, new System.Drawing.PointF(r.Next(50), r.Next(100)),
				new System.Drawing.StringFormat(System.Drawing.StringFormatFlags.DirectionVertical));
			g.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(r.Next(155), r.Next(255),
				r.Next(255), r.Next(255))), r.Next(width), r.Next(height), 100, 50);
			int x = r.Next(width);
			g.FillRectangle(new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Point(x, 0),
				new System.Drawing.Point(x + 75, 100), System.Drawing.Color.FromArgb(128, 0, 0, r.Next(255)),
				System.Drawing.Color.FromArgb(255, r.Next(192, 255), r.Next(192, 255), r.Next(255))), x, r.Next(height), 75, 50);
			string filename = Server.MapPath("/") + System.Guid.NewGuid().ToString("N");
			bmp.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg);
			byte[] bytes;
			using (System.IO.FileStream stream = new System.IO.FileStream(filename, System.IO.FileMode.Open))
			{
				bytes = new byte[stream.Length];
				stream.Read(bytes, 0, bytes.Length);
			}
			System.IO.File.Delete(filename);
			return new FileContentResult(bytes, "image/jpeg");
		}
	}
}

PROWAREtech

Hello there! How can I help you today?
Ask any question

PROWAREtech

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
ACCEPT REJECT