In this article I will explain with an example, how to resize image on the fly and maintain (keep) its Aspect Ratio while resizing in ASP.Net.
HTML Markup
The following HTML Markup consists of 2 ASP.Net Image Controls of which one displays the original image while other displays the Thumbnail of the original image. Also there is an ASP.Net Button control which generates the Thumbnail.
<form id="form1" runat="server">
<asp:Image ID="Image1" runat="server" ImageUrl = "~/Jellyfish.jpg" Height = "400px" Width = "400px"/>
<br />
<asp:Button ID="btnGenerate" OnClick = "GenerateThumbnail" runat="server" Text="Generate Thumbnail" />
<hr />
<asp:Image ID="Image2" runat="server" Visible = "false"/>
</form>
Namespaces
You will need to import the following namespace.
C#
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
VB.Net
Imports System.IO
Imports System.Drawing
Imports System.Drawing.Imaging
Resizing Image and Generating Thumbnail
Below is the code that dynamically resizes the picture and generates the Thumbnail and also displays it in Image Control.
C#
protected void GenerateThumbnail(object sender, EventArgs e)
{
string path = Server.MapPath("~/Jellyfish.jpg");
System.Drawing.Image image = System.Drawing.Image.FromFile(path);
using (System.Drawing.Image thumbnail = image.GetThumbnailImage(100, 100, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
{
using (MemoryStream memoryStream = new MemoryStream())
{
thumbnail.Save(memoryStream, ImageFormat.Png);
Byte[] bytes = new Byte[memoryStream.Length];
memoryStream.Position = 0;
memoryStream.Read(bytes, 0, (int)bytes.Length);
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
Image2.ImageUrl = "data:image/png;base64," + base64String;
Image2.Visible = true;
}
}
}
public bool ThumbnailCallback()
{
return false;
}
VB.Net
Protected Sub GenerateThumbnail(sender As Object, e As EventArgs)
Dim path As String = Server.MapPath("~/Jellyfish.jpg")
Dim image As System.Drawing.Image = System.Drawing.Image.FromFile(path)
Using thumbnail As System.Drawing.Image = image.GetThumbnailImage(100, 100, New System.Drawing.Image.GetThumbnailImageAbort(AddressOf ThumbnailCallback), IntPtr.Zero)
Using memoryStream As New MemoryStream()
thumbnail.Save(memoryStream, ImageFormat.Png)
Dim bytes As [Byte]() = New [Byte](memoryStream.Length - 1) {}
memoryStream.Position = 0
memoryStream.Read(bytes, 0, CInt(bytes.Length))
Dim base64String As String = Convert.ToBase64String(bytes, 0, bytes.Length)
Image2.ImageUrl = "data:image/png;base64," & base64String
Image2.Visible = True
End Using
End Using
End Sub
Public Function ThumbnailCallback() As Boolean
Return False
End Function
Demo
Downloads