Hi southern38spe...,
First you need to calculate the image height and width.
Then based on the height and width you want, calculate the aspect ratio.
Finally, using the aspect ratio calculate the final height and width of the image to be generated.
Refer below sample.
HTML
<asp:Image ID="Image1" runat="server" ImageUrl="~/Jellyfish.jpg" Height="200px" Width="200px" />
<br />
<br />
<asp:Button ID="btnGenerate" OnClick="GenerateThumbnail" runat="server" Text="Generate Thumbnail" />
<hr />
<asp:Image ID="Image2" runat="server" Visible="false" />
Namespaces
C#
using System.IO;
using System.Drawing.Imaging;
VB.Net
Imports System.IO
Imports System.Drawing.Imaging
Code
C#
protected void GenerateThumbnail(object sender, EventArgs e)
{
string path = Server.MapPath("~/Jellyfish.jpg");
System.Drawing.Image image = System.Drawing.Image.FromFile(path);
int height = image.Height;
int width = image.Width;
int maxHeight = 150;
int maxWidth = 150;
double x = maxHeight / height;
double y = maxWidth / width;
double ratio = Math.Min(x, y);
int newHeight = (int)(height * ratio);
int newWidth = (int)(width * ratio);
using (System.Drawing.Image thumbnail = image.GetThumbnailImage(newWidth, newHeight,
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)
Dim height As Integer = image.Height
Dim width As Integer = image.Width
Dim maxHeight As Integer = 150
Dim maxWidth As Integer = 150
Dim x As Double = maxHeight / height
Dim y As Double = maxWidth / width
Dim ratio As Double = Math.Min(x, y)
Dim newHeight As Integer = CInt((height * ratio))
Dim newWidth As Integer = CInt((width * ratio))
Using thumbnail As System.Drawing.Image = image.GetThumbnailImage(newWidth, newHeight,
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
Screenshot