vthunder70
asked on
resizing images
Hi guys,
I have a couple of functions to resize images for an image gallery. right now they are different sizes. I know I give it a 200px max on the larger side but I guess maybe what I need is some sort of crop.
basically I will all the thumbnails to be same size and keeping its proportional ratio. I understand that landscape and portraits will look different because they are differen orientation. So I would like all the portrait thumbnails to be the same size and all the landscape to be the same size.
Thank you,
if you go to the fallowing link is an example of my gallery and you can see how those pictures just dont' look the same.
http://www.sculptoratstrength.com/ourfacility.aspx?collectionid=1
I have a couple of functions to resize images for an image gallery. right now they are different sizes. I know I give it a 200px max on the larger side but I guess maybe what I need is some sort of crop.
basically I will all the thumbnails to be same size and keeping its proportional ratio. I understand that landscape and portraits will look different because they are differen orientation. So I would like all the portrait thumbnails to be the same size and all the landscape to be the same size.
Thank you,
if you go to the fallowing link is an example of my gallery and you can see how those pictures just dont' look the same.
http://www.sculptoratstrength.com/ourfacility.aspx?collectionid=1
Public Shared Function CreateResizedBitmap(ByVal inputBmp As System.Drawing.Image, ByVal sourceBmpWidth As Integer, ByVal sourceBmpHeight As Integer, ByVal newWidth As Integer, ByVal newHeight As Integer) As Bitmap
'Adapted (but mostly copied) from http://www.codeproject.com/cs/media/bitmapmanip.asp
'Create a new bitmap object based on the input
If inputBmp Is Nothing Then
Throw New ArgumentNullException("inputBmp")
End If
If sourceBmpWidth <= 0 Then
sourceBmpWidth = inputBmp.Size.Width
End If
If sourceBmpHeight <= 0 Then
sourceBmpHeight = inputBmp.Size.Height
End If
Dim xScaleFactor As Double = CSng(newWidth) / CSng(sourceBmpWidth)
Dim yScaleFactor As Double = CSng(newHeight) / CSng(sourceBmpHeight)
Dim calculatedNewWidth As Integer = CInt((sourceBmpWidth * xScaleFactor))
Dim calculatedNewHeight As Integer = CInt((sourceBmpHeight * yScaleFactor))
If calculatedNewWidth <= 0 Then
calculatedNewWidth = 1
' Make sure the value is at least 1.
xScaleFactor = CSng(calculatedNewWidth) / CSng(sourceBmpWidth)
' Update the scale factor to reflect the new width
End If
If calculatedNewHeight <= 0 Then
calculatedNewHeight = 1
' Make sure the value is at least 1.
yScaleFactor = CSng(calculatedNewHeight) / CSng(sourceBmpHeight)
' Update the scale factor to reflect the new height
End If
Dim newBmp As New Bitmap(calculatedNewWidth, calculatedNewHeight, PixelFormat.Format32bppRgb)
'Graphics.FromImage doesn't like Indexed pixel format
'Create a graphics object attached to the new bitmap
Using newBmpGraphics As Graphics = Graphics.FromImage(newBmp)
newBmpGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
' Make background white. Without this a think grey line is rendered along the top and left.
' See http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/2c9ac8d0-366c-4919-8f92-3a91c56f41e0/
newBmpGraphics.FillRectangle(Brushes.White, 0, 0, newBmp.Width, newBmp.Height)
newBmpGraphics.ScaleTransform(CSng(xScaleFactor), CSng(yScaleFactor))
'Draw the bitmap in the graphics object, which will apply the scale transform.
'Note that pixel units must be specified to ensure the framework doesn't attempt
'to compensate for varying horizontal resolutions in images by resizing; in this case,
'that's the opposite of what we want.
Dim drawRect As New Rectangle(0, 0, sourceBmpWidth, sourceBmpHeight)
SyncLock inputBmp
Try
newBmpGraphics.DrawImage(inputBmp, drawRect, drawRect, GraphicsUnit.Pixel)
Catch generatedExceptionName As OutOfMemoryException
' The garbage collector will automatically run to try to clean up memory, so let's wait for it to finish and
' try again. If it still doesn't work because the image is just too large and the system doesn't have enough
' memory, catch the OutOfMemoryException and throw one of our UnsupportedImageTypeException exceptions instead.
GC.WaitForPendingFinalizers()
newBmpGraphics.DrawImage(inputBmp, drawRect, drawRect, GraphicsUnit.Pixel)
End Try
End SyncLock
End Using
Return newBmp
End Function
''' <summary>
''' Calculate the required width and height of a thumbnail image while preserving the
''' aspect ratio of the original dimensions. If the autoEnlarge parameter is false, then preserve the original
''' dimensions if they are smaller than the user-specified thumbnail dimensions. If true, then ensure that at
''' least one of the out parameters (newWidth or newHeight) meets the user-specified thumbnail dimensions
''' (i.e. enlarge a small image if necessary). This method does not create a thumbnail image.
''' </summary>
''' <param name="originalWidth">An integer specifying the width, in pixels, of the source image.</param>
''' <param name="originalHeight">An integer specifying the height, in pixels, of the source image.</param>
''' <param name="newWidth">An integer specifying the width, in pixels, of a thumbnail image that preserves
''' the aspect ratio of the original's width and height.</param>
''' <param name="newHeight">An integer specifying the height, in pixels, of a thumbnail image that preserves
''' the aspect ratio of the original's width and height.</param>
''' <param name="autoEnlarge">A value indicating whether to enlarge images that are smaller than the
''' value specified in maxLength. If true, the new width and height will be increased if necessary
''' so that at least one of the values is larger than the maxLength value. If false, the original
''' width and height are returned when their dimensions are smaller than the maxLength value. This
''' parameter has no effect when maxLength is greater than both originalWidth and originalHeight.</param>
Public Shared Sub CalculateThumbnailWidthAndHeight(ByVal originalWidth As Integer, ByVal originalHeight As Integer, ByRef newWidth As Integer, ByRef newHeight As Integer, ByVal autoEnlarge As Boolean)
' Maximum length of the side of the image. Applies to either width or height depending on which is longer.
Const maxLength As Integer = 200
If Not autoEnlarge AndAlso (maxLength > originalWidth) AndAlso (maxLength > originalHeight) Then
' Bitmap is smaller than desired thumbnail dimensions but autoEnlarge = false. Don't enlarge thumbnail;
' just use original size.
newWidth = originalWidth
newHeight = originalHeight
ElseIf originalWidth > originalHeight Then
' Bitmap is in landscape format (width > height). The width will be the longest dimension.
newWidth = maxLength
newHeight = originalHeight * newWidth / originalWidth
Else
' Bitmap is in portrait format (height > width). The height will be the longest dimension.
newHeight = maxLength
newWidth = originalWidth * newHeight / originalHeight
End If
End Sub
Protected Sub Upload(ByVal sender As Object, ByVal e As System.EventArgs)
If FileUpload1.FileName <> "" Then
'thubnail creation and upload
Dim fileName As String = FileUpload1.FileName
Dim src As Bitmap = TryCast(Bitmap.FromStream(FileUpload1.PostedFile.InputStream), Bitmap)
'Dim resultThumb As Bitmap = CreateResizedBitmap(src, src.Size.Width, src.Size.Height, 200, 150)
Dim newWidth As Integer, newHeight As Integer
CalculateThumbnailWidthAndHeight(src.Size.Width, src.Size.Height, newWidth, newHeight, False)
Dim resultThumb As Bitmap = CreateResizedBitmap(src, src.Size.Width, src.Size.Height, newWidth, newHeight)
Dim saveName As String = Server.MapPath(savePath) + fileName
resultThumb.Save(saveName, ImageFormat.Jpeg)
ASKER
I would really like to keep as much as I can. I've put a lot of work on this and don't really want to start form scratch
thanks
thanks
I don't really understand what you want. I looked at your link, and the originals for all four pics all have different sizes (640x432, 640x430, 627x480, 640x434). What size do you *want* the thumbnails to be? You cannot make four identically sized thumbnails unless you crop parts of the images or distort the aspect ratio. The functions you posted (which I admit you got from me in the other thread) do neither of these things. I don't have any handy code to help you crop or distort, so hopefully someone else can step in.
ASKER
I know rdogmartin.. I just don't understand how there are image galleries out there that have all the thumbnails be the same size, am I wrong?
I guess cropping will do the trick, it just won't look really good to have a bunch thumbnails in a grid and all have differente sizes.
Thanks,
-r
I guess cropping will do the trick, it just won't look really good to have a bunch thumbnails in a grid and all have differente sizes.
Thanks,
-r
Try Image.GetThumbnailImage Method: http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage.aspx
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Image.GetThumbnailImage has worked for me in the past and is the subject of the link I provided from 4GuysFromRolla.
ASKER
Hi OmerFarukZ,
I'm trying to use your code and nothing really is happening, could you give some light into it please.
Thank you ver much
I'm trying to use your code and nothing really is happening, could you give some light into it please.
Thank you ver much
Imports System.Threading
Imports System.Data.SqlClient
Imports System.Data
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Drawing.Drawing2D
Partial Class admin_test
Inherits System.Web.UI.Page
Protected savePath As String = "~/thumbnails/"
Private Shared Function resizeImage(ByVal imgToResize As Image, ByVal size As Size) As Image
Dim sourceWidth As Integer = imgToResize.Width
Dim sourceHeight As Integer = imgToResize.Height
Dim nPercent As Single = 0
Dim nPercentW As Single = 0
Dim nPercentH As Single = 0
nPercentW = (CSng(size.Width) / CSng(sourceWidth))
nPercentH = (CSng(size.Height) / CSng(sourceHeight))
If nPercentH < nPercentW Then
nPercent = nPercentH
Else
nPercent = nPercentW
End If
Dim destWidth As Integer = CInt((sourceWidth * nPercent))
Dim destHeight As Integer = CInt((sourceHeight * nPercent))
Dim b As New Bitmap(destWidth, destHeight)
Dim g As Graphics = Graphics.FromImage(DirectCast(b, Image))
g.InterpolationMode = InterpolationMode.HighQualityBicubic
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight)
g.Dispose()
Return DirectCast(b, Image)
End Function
Protected Sub Upload(ByVal sender As Object, ByVal e As System.EventArgs)
If FileUpload1.FileName <> "" Then
'thubnail creation and upload
Dim fileName As String = FileUpload1.FileName
Dim src As Bitmap = TryCast(Bitmap.FromStream(FileUpload1.PostedFile.InputStream), Bitmap)
Dim resultThumb As Bitmap = resizeImage(src, src.Size)
Dim saveName As String = Server.MapPath(savePath) + fileName
resultThumb.Save(saveName, ImageFormat.Jpeg)
End If
End Sub
End Class
ASKER
Also guys,
I found this link and it looks pretty good but when I downloaded the code file I really don't knwo how to use it. I'm not very experience but I"m trying here and it's driving me crazy... thanks guys
I'll attach the code from the article, I just don't knwo how to make it work
http://www.codeproject.com/KB/GDI-plus/imageresize.aspx?fid=9263&tid=2519032
I found this link and it looks pretty good but when I downloaded the code file I really don't knwo how to use it. I'm not very experience but I"m trying here and it's driving me crazy... thanks guys
I'll attach the code from the article, I just don't knwo how to make it work
http://www.codeproject.com/KB/GDI-plus/imageresize.aspx?fid=9263&tid=2519032
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
namespace Tutorial
{
class ImageResize
{
enum Dimensions
{
Width,
Height
}
enum AnchorPosition
{
Top,
Center,
Bottom,
Left,
Right
}
[STAThread]
static void Main(string[] args)
{
//set a working directory
string WorkingDirectory = @"C:\Projects\Tutorials\ImageResize";
//create a image object containing a verticel photograph
Image imgPhotoVert = Image.FromFile(WorkingDirectory + @"\imageresize_vert.jpg");
Image imgPhotoHoriz = Image.FromFile(WorkingDirectory + @"\imageresize_horiz.jpg");
Image imgPhoto = null;
imgPhoto = ScaleByPercent(imgPhotoVert, 50);
imgPhoto.Save(WorkingDirectory + @"\images\imageresize_1.jpg", ImageFormat.Jpeg);
imgPhoto.Dispose();
imgPhoto = ConstrainProportions(imgPhotoVert, 200, Dimensions.Width);
imgPhoto.Save(WorkingDirectory + @"\images\imageresize_2.jpg", ImageFormat.Jpeg);
imgPhoto.Dispose();
imgPhoto = FixedSize(imgPhotoVert, 200, 200);
imgPhoto.Save(WorkingDirectory + @"\images\imageresize_3.jpg", ImageFormat.Jpeg);
imgPhoto.Dispose();
imgPhoto = Crop(imgPhotoVert, 200, 200, AnchorPosition.Center);
imgPhoto.Save(WorkingDirectory + @"\images\imageresize_4.jpg", ImageFormat.Jpeg);
imgPhoto.Dispose();
imgPhoto = Crop(imgPhotoHoriz, 200, 200, AnchorPosition.Center);
imgPhoto.Save(WorkingDirectory + @"\images\imageresize_5.jpg", ImageFormat.Jpeg);
imgPhoto.Dispose();
}
static Image ScaleByPercent(Image imgPhoto, int Percent)
{
float nPercent = ((float)Percent/100);
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX,destY,destWidth,destHeight),
new Rectangle(sourceX,sourceY,sourceWidth,sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
}
static Image ConstrainProportions(Image imgPhoto, int Size, Dimensions Dimension)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
float nPercent = 0;
switch(Dimension)
{
case Dimensions.Width:
nPercent = ((float)Size/(float)sourceWidth);
break;
default:
nPercent = ((float)Size/(float)sourceHeight);
break;
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX,destY,destWidth,destHeight),
new Rectangle(sourceX,sourceY,sourceWidth,sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
}
static Image FixedSize(Image imgPhoto, int Width, int Height)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)Width/(float)sourceWidth);
nPercentH = ((float)Height/(float)sourceHeight);
//if we have to pad the height pad both the top and the bottom
//with the difference between the scaled height and the desired height
if(nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = (int)((Width - (sourceWidth * nPercent))/2);
}
else
{
nPercent = nPercentW;
destY = (int)((Height - (sourceHeight * nPercent))/2);
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.Clear(Color.Red);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX,destY,destWidth,destHeight),
new Rectangle(sourceX,sourceY,sourceWidth,sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
}
static Image Crop(Image imgPhoto, int Width, int Height, AnchorPosition Anchor)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)Width/(float)sourceWidth);
nPercentH = ((float)Height/(float)sourceHeight);
if(nPercentH < nPercentW)
{
nPercent = nPercentW;
switch(Anchor)
{
case AnchorPosition.Top:
destY = 0;
break;
case AnchorPosition.Bottom:
destY = (int)(Height - (sourceHeight * nPercent));
break;
default:
destY = (int)((Height - (sourceHeight * nPercent))/2);
break;
}
}
else
{
nPercent = nPercentH;
switch(Anchor)
{
case AnchorPosition.Left:
destX = 0;
break;
case AnchorPosition.Right:
destX = (int)(Width - (sourceWidth * nPercent));
break;
default:
destX = (int)((Width - (sourceWidth * nPercent))/2);
break;
}
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX,destY,destWidth,destHeight),
new Rectangle(sourceX,sourceY,sourceWidth,sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
}
}
}
ASKER
HI guys,
so I got it to work with OmerFarukZ suggestion but if there is extra space it fills it in with black. is there anyway I can have the croped imagen center with a white background and maybe and outline around it.... kind of like framing it.
Basically I added OmerFarukZ function of cropping after the image gets resized down.
you can view it here:
http://www.sculptoratstrength.com/ourfacility.aspx?collectionid=1
and the code use below
thanks a lot guys
so I got it to work with OmerFarukZ suggestion but if there is extra space it fills it in with black. is there anyway I can have the croped imagen center with a white background and maybe and outline around it.... kind of like framing it.
Basically I added OmerFarukZ function of cropping after the image gets resized down.
you can view it here:
http://www.sculptoratstrength.com/ourfacility.aspx?collectionid=1
and the code use below
thanks a lot guys
Imports System.Threading
Imports System.Data.SqlClient
Imports System.Data
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Drawing.Drawing2D
Imports System.IO
Partial Class admin_addPhoto
Inherits System.Web.UI.Page
Protected savePath As String = "~/thumbnails/"
Public Shared Function CreateResizedBitmap(ByVal inputBmp As System.Drawing.Image, ByVal sourceBmpWidth As Integer, ByVal sourceBmpHeight As Integer, ByVal newWidth As Integer, ByVal newHeight As Integer) As Bitmap
'Adapted (but mostly copied) from http://www.codeproject.com/cs/media/bitmapmanip.asp
'Create a new bitmap object based on the input
If inputBmp Is Nothing Then
Throw New ArgumentNullException("inputBmp")
End If
If sourceBmpWidth <= 0 Then
sourceBmpWidth = inputBmp.Size.Width
End If
If sourceBmpHeight <= 0 Then
sourceBmpHeight = inputBmp.Size.Height
End If
Dim xScaleFactor As Double = CSng(newWidth) / CSng(sourceBmpWidth)
Dim yScaleFactor As Double = CSng(newHeight) / CSng(sourceBmpHeight)
Dim calculatedNewWidth As Integer = CInt((sourceBmpWidth * xScaleFactor))
Dim calculatedNewHeight As Integer = CInt((sourceBmpHeight * yScaleFactor))
If calculatedNewWidth <= 0 Then
calculatedNewWidth = 1
' Make sure the value is at least 1.
xScaleFactor = CSng(calculatedNewWidth) / CSng(sourceBmpWidth)
' Update the scale factor to reflect the new width
End If
If calculatedNewHeight <= 0 Then
calculatedNewHeight = 1
' Make sure the value is at least 1.
yScaleFactor = CSng(calculatedNewHeight) / CSng(sourceBmpHeight)
' Update the scale factor to reflect the new height
End If
Dim newBmp As New Bitmap(calculatedNewWidth, calculatedNewHeight, PixelFormat.Format32bppRgb)
'Graphics.FromImage doesn't like Indexed pixel format
'Create a graphics object attached to the new bitmap
Using newBmpGraphics As Graphics = Graphics.FromImage(newBmp)
newBmpGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
' Make background white. Without this a think grey line is rendered along the top and left.
' See http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/2c9ac8d0-366c-4919-8f92-3a91c56f41e0/
newBmpGraphics.FillRectangle(Brushes.White, 0, 0, newBmp.Width, newBmp.Height)
newBmpGraphics.ScaleTransform(CSng(xScaleFactor), CSng(yScaleFactor))
'Draw the bitmap in the graphics object, which will apply the scale transform.
'Note that pixel units must be specified to ensure the framework doesn't attempt
'to compensate for varying horizontal resolutions in images by resizing; in this case,
'that's the opposite of what we want.
Dim drawRect As New Rectangle(0, 0, sourceBmpWidth, sourceBmpHeight)
SyncLock inputBmp
Try
newBmpGraphics.DrawImage(inputBmp, drawRect, drawRect, GraphicsUnit.Pixel)
Catch generatedExceptionName As OutOfMemoryException
' The garbage collector will automatically run to try to clean up memory, so let's wait for it to finish and
' try again. If it still doesn't work because the image is just too large and the system doesn't have enough
' memory, catch the OutOfMemoryException and throw one of our UnsupportedImageTypeException exceptions instead.
GC.WaitForPendingFinalizers()
newBmpGraphics.DrawImage(inputBmp, drawRect, drawRect, GraphicsUnit.Pixel)
End Try
End SyncLock
End Using
Return newBmp
End Function
''' <summary>
''' Calculate the required width and height of a thumbnail image while preserving the
''' aspect ratio of the original dimensions. If the autoEnlarge parameter is false, then preserve the original
''' dimensions if they are smaller than the user-specified thumbnail dimensions. If true, then ensure that at
''' least one of the out parameters (newWidth or newHeight) meets the user-specified thumbnail dimensions
''' (i.e. enlarge a small image if necessary). This method does not create a thumbnail image.
''' </summary>
''' <param name="originalWidth">An integer specifying the width, in pixels, of the source image.</param>
''' <param name="originalHeight">An integer specifying the height, in pixels, of the source image.</param>
''' <param name="newWidth">An integer specifying the width, in pixels, of a thumbnail image that preserves
''' the aspect ratio of the original's width and height.</param>
''' <param name="newHeight">An integer specifying the height, in pixels, of a thumbnail image that preserves
''' the aspect ratio of the original's width and height.</param>
''' <param name="autoEnlarge">A value indicating whether to enlarge images that are smaller than the
''' value specified in maxLength. If true, the new width and height will be increased if necessary
''' so that at least one of the values is larger than the maxLength value. If false, the original
''' width and height are returned when their dimensions are smaller than the maxLength value. This
''' parameter has no effect when maxLength is greater than both originalWidth and originalHeight.</param>
Public Shared Sub CalculateThumbnailWidthAndHeight(ByVal originalWidth As Integer, ByVal originalHeight As Integer, ByRef newWidth As Integer, ByRef newHeight As Integer, ByVal autoEnlarge As Boolean)
' Maximum length of the side of the image. Applies to either width or height depending on which is longer.
Const maxLength As Integer = 200
If Not autoEnlarge AndAlso (maxLength > originalWidth) AndAlso (maxLength > originalHeight) Then
' Bitmap is smaller than desired thumbnail dimensions but autoEnlarge = false. Don't enlarge thumbnail;
' just use original size.
newWidth = originalWidth
newHeight = originalHeight
ElseIf originalWidth > originalHeight Then
' Bitmap is in landscape format (width > height). The width will be the longest dimension.
newWidth = maxLength
newHeight = originalHeight * newWidth / originalWidth
Else
' Bitmap is in portrait format (height > width). The height will be the longest dimension.
newHeight = maxLength
newWidth = originalWidth * newHeight / originalHeight
End If
End Sub
Private Shared Function resizeImage(ByVal imgToResize As Image, ByVal size As Size) As Image
Dim sourceWidth As Integer = imgToResize.Width
Dim sourceHeight As Integer = imgToResize.Height
Dim nPercent As Single = 0
Dim nPercentW As Single = 0
Dim nPercentH As Single = 0
nPercentW = (CSng(size.Width) / CSng(sourceWidth))
nPercentH = (CSng(size.Height) / CSng(sourceHeight))
If nPercentH < nPercentW Then
nPercent = nPercentH
Else
nPercent = nPercentW
End If
Dim destWidth As Integer = CInt((sourceWidth * nPercent))
Dim destHeight As Integer = CInt((sourceHeight * nPercent))
Dim b As New Bitmap(200, 125)
Dim g As Graphics = Graphics.FromImage(DirectCast(b, Image))
g.InterpolationMode = InterpolationMode.HighQualityBicubic
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight)
g.Dispose()
Return DirectCast(b, Image)
End Function
Protected Sub Upload(ByVal sender As Object, ByVal e As System.EventArgs)
If FileUpload1.FileName <> "" Then
'thubnail creation and upload
Dim fileName As String = FileUpload1.FileName
Dim src As Bitmap = TryCast(Bitmap.FromStream(FileUpload1.PostedFile.InputStream), Bitmap)
'Dim resultThumb As Bitmap = CreateResizedBitmap(src, src.Size.Width, src.Size.Height, 200, 150)
Dim newWidth As Integer, newHeight As Integer
CalculateThumbnailWidthAndHeight(src.Size.Width, src.Size.Height, newWidth, newHeight, False)
Dim resultThumb As Bitmap = CreateResizedBitmap(src, src.Size.Width, src.Size.Height, newWidth, newHeight)
Dim resultThumb2 As Bitmap = resizeImage(resultThumb, resultThumb.Size)
Dim saveName As String = Server.MapPath(savePath) + fileName
resultThumb2.Save(saveName, ImageFormat.Jpeg)
See if the above helps although looks like you have method already for creating the bitmap. I have done this a few times in the past, but don't have any of my code available as a sample; however, the gist of what I did was to use method like in link with a fixed thumbnail of 100 x 75. You could examine if height > width then use 75 x 100 or vice versa.