How can i create local file thumbnail with ASP.net?

I am creating a tool that will allow a user to upload an image and it will be added to a database.  I would like to create a file based thumbnail based on the original file.

Normally I would do this on the fly, but I expect a fair amount of traffic on the thumbnails and in past (classic ASP) sites it was a huge hit on the processor scaling 3000px+ images down to 150px or so.

See the pseudo code below for an example:


protected int createthumb( string strPath, string strFilename )
{
     // create thumbnail of 'strFilename'
     // save thumbnail as 'tn_' + strFilename
 
     return (error_code) 
}

Open in new window

swabeuiAsked:
Who is Participating?
 
Juan_BarreraConnect With a Mentor Commented:
Hi swabeui,
Try the following code, I don't think you should have performance issues with this, but, of course, it depends on your horsepower and usage scenario.

Using image As Drawing.Image = Drawing.Image.FromFile(strPath)
   Using thumbnail As Drawing.Image = image.GetThumbnailImage(150, 150, Nothing, System.IntPtr.Zero)
       thumbnail.Save("tn" & strFileName)
   End Using
End Using

Open in new window

0
 
swabeuiAuthor Commented:
Hi Juan,

Sorry for the delay.  I was able to use this to create a thumbnail but realized I wasn't specific enough in my first post.  When the thumbnail is created, it should keep the aspect ratio of the image intact.  So if an image is 1000x500 the resulting image would be 150x75.  Could you tweak the example above to calculate the dimensions?

Thanks,
John
0
 
Juan_BarreraCommented:
Hi John,
Here is a simple example of a ratio 10:1, you can tweak it to suit your needs:

 Using image As Drawing.Image = Drawing.Image.FromFile(strPath)
            Dim ratio As Integer = 10
            Using thumbnail As Drawing.Image = image.GetThumbnailImage(image.Size.Width / ratio, image.Size.Height / ratio, Nothing, System.IntPtr.Zero)
                thumbnail.Save("tn" & strFIleName)
            End Using
        End Using

Open in new window

0
 
swabeuiAuthor Commented:
Thanks for the help, I was able to get everything working how I needed it by calculating the ratio based off the dimensions of the existing image.  

John
int thumbX = 150;
int thumbY = 150;
float imgWidth = bigimage.Width;
float imgHeight = bigimage.Height;
 
// calculate aspect ratio thumbnail size
if (bigimage.Width > bigimage.Height)
{
    // thumbX alredy set to 150, calculate Y size
    thumbY = (int)((150 / imgWidth) * imgHeight);
} else if (bigimage.Width < bigimage.Height)   {
    // thumbY already set to 150, calculate X size
    thumbX = (int)((150 / imgHeight) * imgWidth);
}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.