Contact   •   Articles   •   Products   •   Search

Rick Strahl's Web Log

Wind, waves, code and everything in between...
ASP.NET • C# • HTML5 • JavaScript • AngularJs

Creating Thumbnail Images on the fly with ASP.Net


One frequent task is to take images and convert them into thumbnails. This is certainly nothing new, but seeing this question is so frequently asked on newsgroups and message boards bears reviewing this topic here again.

 

I was getting tired of constantly repeating this code for specific situations, so I created a generic page in my apps to handle resizing images from the current site dynamically in a page called CreateThumbnail. You call this page with a relative image name from the Web site on the querystring and it returns the image as a thumbnail.

 

An example of how this might work looks like this:

 

http://www.west-wind.com/wwStore/demos/CreateThumbnail.aspx?image=images/WebStoreLogo_big.jpg&size=400

 

Size is an optional second parameter – it defaults to 120.

 

Here’s what the implementation of this generic page looks like:

 

using System.Drawing;

using System.Drawing.Imaging;

 

public class CreateThumbNail : System.Web.UI.Page

{

private void Page_Load(object sender, System.EventArgs e)

      {

            string Image = Request.QueryString["Image"];

            if (Image == null) 

            {

                  this.ErrorResult();

                  return;

            }

 

            string sSize = Request["Size"];

            int Size = 120;

            if (sSize != null)

                  Size = Int32.Parse(sSize);

 

            string Path = Server.MapPath(Request.ApplicationPath) + "\\" + Image;

            Bitmap bmp = CreateThumbnail(Path,Size,Size);

 

            if (bmp == null)

            {

                  this.ErrorResult();

                  return;

            }

 

            string OutputFilename = null;

            OutputFilename = Request.QueryString["OutputFilename"];

 

            if (OutputFilename != null)

            {

                  if (this.User.Identity.Name == "") 

                  {

                        // *** Custom error display here

                        bmp.Dispose();

                        this.ErrorResult();

                  }

                  try

                  {

                        bmp.Save(OutputFilename);

                  }

                  catch(Exception ex)

                  {

                        bmp.Dispose();

                        this.ErrorResult();

                        return;

                  }

            }

 

            // Put user code to initialize the page here

            Response.ContentType = "image/jpeg";

            bmp.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);

            bmp.Dispose();

      }

 

      private void ErrorResult()

      {

            Response.Clear();

            Response.StatusCode = 404;

            Response.End();

      }

 

      ///

      /// Creates a resized bitmap from an existing image on disk.

      /// Call Dispose on the returned Bitmap object

      ///

      ///

      ///

      ///

      /// Bitmap or null

      public static Bitmap CreateThumbnail(string lcFilename,int lnWidth, int lnHeight)

      {

     

            System.Drawing.Bitmap bmpOut = null;

            try

            {

                  Bitmap loBMP = new Bitmap(lcFilename);

                  ImageFormat loFormat = loBMP.RawFormat;

 

                  decimal lnRatio;

                  int lnNewWidth = 0;

                  int lnNewHeight = 0;

 

                  //*** If the image is smaller than a thumbnail just return it

                  if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)

                        return loBMP;

           

 

                  if (loBMP.Width > loBMP.Height)

                  {

                        lnRatio = (decimal) lnWidth / loBMP.Width;

                        lnNewWidth = lnWidth;

                        decimal lnTemp = loBMP.Height * lnRatio;

                        lnNewHeight = (int)lnTemp;

                  }

                  else

                  {

                        lnRatio = (decimal) lnHeight / loBMP.Height;

                        lnNewHeight = lnHeight;

                        decimal lnTemp = loBMP.Width * lnRatio;

                        lnNewWidth = (int) lnTemp;

                  }

 

                  // System.Drawing.Image imgOut =

                  //      loBMP.GetThumbnailImage(lnNewWidth,lnNewHeight,

                  //                              null,IntPtr.Zero);

                 

                  // *** This code creates cleaner (though bigger) thumbnails and properly

                  // *** and handles GIF files better by generating a white background for

                  // *** transparent images (as opposed to black)

                  bmpOut = new Bitmap(lnNewWidth, lnNewHeight);

                  Graphics g = Graphics.FromImage(bmpOut);

                  g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                  g.FillRectangle( Brushes.White,0,0,lnNewWidth,lnNewHeight);

                  g.DrawImage(loBMP,0,0,lnNewWidth,lnNewHeight);

 

                  loBMP.Dispose();

            }

            catch

            {

                  return null;

            }

     

            return bmpOut;

      }

 

}

 

This code doesn’t use the CreateThumbnail method of GDI+ because it doesn’t properly convert transparent GIF images as it draws the background color black. The code above compensates for this by first drawing the canvas white then loading the GIF image on top of it. Transparency is lost – unfortunately GDI+ does not handle transparency automatically and keeping Transparency intact requires manipulating the palette of the image which is beyond this demonstration.

 

The Bitmap object is returned as the result. You can choose what to do with this object. In this example it’s directly streamed in the ASP. Net Output stream by default. If you specify another query string value of OutputFilename you can also force the file to be written to disk *if* you are logged in. This is definitely not something that you want to allow just ANY user access to as anything that writes to disk is potentially dangerous in terms of overloading your disk space. Writing files out in this fashion also requires that the ASPNET or NETWORK SERVICE or whatever account the ASP. Net app runs under has rights to write the file in the specified directory.  I’ve provided this here as an example, but it’s probably best to stick file output functionality into some other more isolated component or page that is more secure.

 

Notice also that all errors return a 404 file not found error. This is so that images act on failure just as if an image file is not available which gives the browser an X’d out image to display. Realistically this doesn’t matter – browsers display the X anyway even if you send back an HTML error message, but this is the expected response the browser would expect.

 

In my West Wind Web Store I have several admin routines that allow to resize images on the fly and display them in a preview window. It’s nice to preview them before writing them out to disk optionally. You can also do this live in an application *if* the number of images isn’t very large and you’re not pushing your server to its limits already. Image creation on the fly is always slower than static images on disk. However, ASP. Net can be pretty damn efficient using Caching and this scenario is made for it. You can specify:

<%@ OutputCache duration="10000" varybyparam="Image;Size" %>

 

in the ASPX page to force images to cache once they’ve been generated. This will work well, but keep in mind that bitmap images can be memory intensive and caching them can add up quickly especially if you have large numbers of them.

 

If you create images dynamically frequently you might also consider using an HTTP Handler to perform this task since raw Handlers have less overhead than the ASP.Net Page handler. For example, the Whidbey Dynamic Image control relies on an internal handler that provides image presentation 'dynamically' without having to save files to disk first.

 

Make Donation

The Voices of Reason


 

Joe Brinkman
April 28, 2004

# re: Creating Thumbnail Images on the fly with ASP.Net

Finally. Someone who doesn't rely on the 'buggy' CreateThumbnail method. I have used a similar routine, but always had problems with the transparency issue. Now I have a solution ;) Thanks

Jason Sebring
May 11, 2004

# re: Creating Thumbnail Images on the fly with ASP.Net

Thanks for the code, dude. Nice of you.

Bob
June 01, 2004

# re: Creating Thumbnail Images on the fly with ASP.Net

Nice! Finally a thumb generator that doesn't output fuzzy jpeg.

I can't seem to get an output file though, I used the OutputFilename querystring, the page showed blank, but the file's not in the directory.

Is the file somewhere else?

Rick Strahl
June 02, 2004

# re: Creating Thumbnail Images on the fly with ASP.Net

Bob, you need the proper permissions in order to write the file. Specifically ASPNET or NETWORK SERVICE (IIS6) or whatever account is running your Web app needs WRITE access in order to create the output file.

Bob
June 02, 2004

# re: Creating Thumbnail Images on the fly with ASP.Net

I set write and modify permissions fo ASPNET for the folder "test", but I still can't find the file.

I tried to save to a filestream before and they worked.

Bob
June 02, 2004

# re: Creating Thumbnail Images on the fly with ASP.Net

I commented out these code in Page_Load and it worked. What does it do?

if (this.User.Identity.Name == "") {
bmp.Dispose();
this.ErrorResult();
}

Rick Strahl
June 03, 2004

# re: Creating Thumbnail Images on the fly with ASP.Net

This code is in there to prevent writing of the file if you're not logged in. You don't want to allow this as an open access feature since it creates files on your local disk. If you're not worried about this then you can take out that code...

Rick Strahl's WebLog
June 24, 2004

# GDI InterpolationMode

Resizing images can cause images to loose some of their quality as the images are resampled. You can control the algorithms used for the resize resampling by using the Graphics object's InterpolationMode property.

Rick Strahl
June 30, 2004

# re: Creating Thumbnail Images on the fly with ASP.Net

Write to Cache based on the Image Url and use something like this:

byte[] BitmapBytes = app.Context.Cache[FileName] as byte[];
if (BitmapBytes != null)
{
Response.ContentType = "image/jpeg";
Response.BinaryWrite( BitmapBytes ); Response.End();
}

otherwise gen the image and write it out to the cache:

app.Context.Cache.Add(FileName,
ms.GetBuffer(),null,
DateTime.Now.AddMinutes(10),
TimeSpan.Zero,
System.Web.Caching.CacheItemPriority.Normal,
null);


Chad
July 02, 2004

# re: Creating Thumbnail Images on the fly with ASP.Net

Does anyone know how to do this with a regular web page (i.e. a snapshot of the entire web page). I need to be able to take a live "snapshot" of a web page and display it. I don't want to buy/use 3rd party components.

Thanks for any help, you can also contact me at ChadBeckner@ProspectiveLink.com

Chad

Jason Salas' WebLog
July 30, 2004

# Emulating PhotoShop Actions programmatically in ASP.NET with GDI


Rick Strahl
October 10, 2004

# re: Creating Thumbnail Images on the fly with ASP.Net

If you're interested in resizing images, make sure you play around with the Image Interpolation mode which can have a dramatic effect on image quality when resizing images. More info in this entry:

http://west-wind.com/weblog/posts/283.aspx

Knazo
October 11, 2004

# re: Creating Thumbnail Images on the fly with ASP.Net

For those who desperately need to maintain transparency on gif thumbnail images:

unsafe Bitmap GetThumbnail(Bitmap src, int width, int height)
{

// preserve source-image aspect ratio

float src_t = (float)src.Height / (float)src.Width;

if (src_t > ((float)height / (float)width))
width = (int)(height / src_t);
else
height = (int)(width * src_t);

// end of preserve source-image aspect ratio



if (src.PixelFormat == PixelFormat.Format8bppIndexed)
{
// do it yourself

Bitmap dst = new Bitmap(width, height, src.PixelFormat);
dst.Palette = src.Palette;

BitmapData dstbd =
dst.LockBits
(
new Rectangle(0, 0, dst.Width, dst.Height),
ImageLockMode.WriteOnly,
dst.PixelFormat
);
try
{
BitmapData srcbd =
src.LockBits
(
new Rectangle(0, 0, src.Width, src.Height),
ImageLockMode.ReadOnly,
src.PixelFormat
);
try
{
byte *srcp;
byte *dstp;

float m = (float)src.Width / (float)dst.Width;


for (int r = 0; r < dst.Height; ++r)
{
dstp = (byte *)dstbd.Scan0;
dstp += dstbd.Stride * r;

for (int c = 0; c < dst.Width; ++c)
{
srcp = (byte *)srcbd.Scan0;
srcp += srcbd.Stride * (int)(r * m);
srcp += (int)(c * m);

*dstp++ = *srcp;
}
}

}
finally
{
src.UnlockBits(srcbd);
}
}
finally
{
dst.UnlockBits(dstbd);
}

return dst;
}
else
{
// rely on microsoft guy

return (Bitmap) src.GetThumbnailImage(width, height, null, IntPtr.Zero);
}
}

Jari
November 17, 2004

# re: Creating Thumbnail Images on the fly with ASP.Net

Hi!
Fine code to create thumbnails!!
How do you add link to thumbnail to the larger image?
Is it possible to view images int the table?

-jari

Frank
December 05, 2004

# re: Creating Thumbnail Images on the fly with ASP.Net

Nice and extremily helpfull, thanks.

Nitpick:
As far as I can tell, this line:
ImageFormat loFormat = loBMP.RawFormat;
is not required.

Thanks,
Frank

Sunil
December 06, 2004

# re: Creating Thumbnail Images on the fly with ASP.Net

Hi,

Very good code to create thumbnails.
Need some help on making the generated images more sharper (Present code generates thumbnails in glossy mode)
I am comparing images created with above code and images created with the help of ASPJPEG (www.aspjpeg.com)

Thanks,
Sunil

Rick Strahl
January 08, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

All you do is change the output filename to one of the supported extensions. .Thumb isn't supported by GDI+ so that won't work, but .png, .tif, .gif etc. should work.

guoqi
January 22, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

Ja, right, do you know a VB.NET version somewhere?

Allen
January 22, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Image As String = Request.QueryString("Image")
If Image = String.Empty Then
Me.ErrorResult()
Return
End If

Dim sSize = Request("Size")
Dim Size As Integer = 120

If Not sSize = String.Empty Then
Size = Int32.Parse(sSize)
End If

Dim Path As String = Server.MapPath(Request.ApplicationPath) + "\" + Image

Dim bmp As Bitmap = CreateThumbnail(Path, Size, Size)

If bmp Is String.Empty Then
Me.ErrorResult()
Return
End If

Dim OutputFilename As String = String.Empty
OutputFilename = Request.QueryString("OutputFilename")

If Not OutputFilename = String.Empty Then
If Me.User.Identity.Name = String.Empty Then
bmp.Dispose()
Me.ErrorResult()
End If

Try
bmp.Save(OutputFilename)
Catch ex As Exception
bmp.Dispose()
Me.ErrorResult()
Return
End Try
End If

Response.ContentType = "image/jpeg"
bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
'bmp.Save(Server.MapPath(Request.ApplicationPath) + "/images/foobar.jpg", ImageFormat.Jpeg)
bmp.Dispose()

End Sub

Kurt
January 28, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

big help! Your example gave me the ideas i needed to create the solution i needed. IOU1
kes

Chris
February 13, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

I resize via the same mechanism as you, but for some reason, if the original photo (jpg) is in portrait mode, the quality degrades alot more than phots shot in landscape... wondering if you had any thoughts. (using HighQualityBicubic )


Nice turorial, I picked up a couple ideas.

Chris

geedubb
February 14, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

Hi Rick. Nice work.

I am interested in getting the images to cache properly. I can see where you have suggested modifications to get this to work, but don't fully understand the instructions.

Is there any chance you can list the full script with caching enabled?

Thanks in advance

Søren Hansen
February 25, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

Hi

I'm a rookie in programming ASP.
Is it posible to get a copy of the file
http://www.west-wind.com/wwStore/demos/CreateThumbnail.aspx

I tryed to copy the code to an thumbs.aspx and put it on my website but i get an "Server Error in '/' Application."

I gues its the format of the file i made

SRH@person.dk

Jon
March 03, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

That works a treat after converting it to VB, thanks!

Does anyone know how to create a thumbnail image of a frame from a video file (mpg, avi, qt, etc)?

I'd like to use one as an ImageButton to load a video clip.

Cheers!

J'son
March 03, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

Mr. Strahl,

How do you get your example to scale in size without losing any detail at all? I am using your example with both gif and jpegs and scaling down causes noticable loss of quality. Is there something special about your web store logo (size, quality-wise) ?

One thing I am doing differently is saving the result bit array to a SQL database image field but that shouldn't affect quality.

Rick Strahl
March 03, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

Jason, make sure you use the InterpolationMode flag as it is vital to making smooth transitions (at least with Jpgs). I think the reason the Web Store logo shrinks well is because it is pretty big and also fairly straight layout. Smaller images - especially Gifs that are optimized will not have the detail to scale either up or down.

Rick Strahl
March 08, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

Antuan, make sure you URLEncode any values you put on the URL. Those characters are not legal and some browsers don't automatically fix them up.

Digidodo
March 09, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

Did you notice that the line:
<%@ OutputCache duration="10000" varybyparam="Image;Size" %>
Where you mention the cache-possibility, is not displayed?

Sandi
March 16, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

Can memory stream or byte data be used instead of an actual file?

Rick Strahl
March 16, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

The sample doesn't use an actual file except if you decide to save. The bitmap object can be streamed into any stream object.

Sandi
March 16, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

In the line that says:
Bitmap bmp = CreateThumbnail(Path,Size,Size);
Refers you to the CreateThumbnail procedure which asks for a filename in the form of a string, correct? Here's the thing: I have some files to be uploaded to a site to be saved to an SQL binary field. Then I want to display thumbnails of these files as a group of images using regular <asp:image> controls on a page without saving them anywhere. I would then link to a page display the full size or optionally resize the image on the same page. Does that make any sense to you?
(Pardon me. I am a beginner so VB is easier to understand for me.)

Flávio
April 01, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

Hey, thanks a lot man !!!
very nice !!

Tussen
April 15, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

If i want to stream a generated transparent PNG with BinaryWrite like
<img src="http://xxx/image.aspx?trans=y&headline=Investor"> it doesn't work in ie. Even if i use pngbehavior.htc or .js
If i save the image instead
<img src="http://xxx/investor.png"> it works and is transparent.
It's the same code with the only differnce is that instead of stream it i save it and the show it.
The response has exactly the same headers. It doesn't work with "save img --> server.transfer(img)" either. Does someone know why?

elango
May 26, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

In the line that says:
Bitmap bmp = CreateThumbnail(Path,Size,Size);
Refers you to the CreateThumbnail procedure which asks for a filename in the form of a string, correct? Here's the thing: I have some files to be uploaded to a site to be saved to an SQL binary field. Then I want to display thumbnails of these files as a group of images using regular <asp:image> controls on a page without saving them anywhere. I would then link to a page display the full size or optionally resize the image on the same page. Does that make any sense to you?
(Pardon me. I am a beginner so VB is easier to understand for me.)


Rick Strahl
May 27, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

The bitmap object can accept a stream of data or a byte array. The sample uses a file to read from but you can read a bitmap in many different ways. Take a look at the Bitmap class in the documentation.

dave
June 12, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

It's already said a lot, but let me say again...AWESOME! Thanks for providing a way without using CreateThumbnail

Dominic
June 23, 2005

# Creating Thumbnail Images on the fly with ASP.Net

Hi, i'm really a beginner at asp.net
i'm currently working on some sort of a image search application but i'm not sure how to work with url instead of relative paths? Please help me. many thanks.

Also, are there any good way to get asp.net working? i've tried several books, most of them don't make sense to me, save the one by the "for dummies" people, but it's too slow, i know i'm not suppose to take short cuts, but are there any faster way of learning?
Please help.

Thanks in advance.
Dominic

Dirk
July 03, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

@Knazo: Do you have a vb.net version of your script to maintain transparency on gif thumbnail images? I tried to translate it to vb.net but I can't get those lines work in vb.net:

byte *srcp;
byte *dstp;

for (int c = 0; c < dst.Width; ++c)
{
srcp = (byte *)srcbd.Scan0;
srcp += srcbd.Stride * (int)(r * m);
srcp += (int)(c * m);

*dstp++ = *srcp;
}

The Problem are the '*', i don't know what you are doing there. Could you please help me?

Greets Dirk


Jay Dubal
July 12, 2005

# Overlapping Images

Hi,

Is it possible to overlap two images using GDI, I have one full image and other image (like frame), I want to overlap the second one on first, so that it looks like my picture is in a Photo Frame (the frame will have center portion transparent)

Any hints, I tried draw image, but it gives exception of indexed format!!

Thanks
Jay

dave
July 14, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

this is very good, but not as good as photoshop resizing... has anybody have any idea how to achieve PS quality..?

Mike Grimm
August 08, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

GDI+ will handle transparancy and opacity just fine. It is it's native format. So it can easily presearve transparancy in gif images.

Instead of painting the image white set the CompositionMode to SourceCopy. This means that rather than blending the transpacency with the contents of the Graphics object (default black) it will be over written by the contents of the image.

The reason why GetThumbnail does poorly on larger sizes than 120 x 90 on some images is beacause those image files have a preview embedded in the file such as jpeg or tiff and it uses that instead. It actually tries to up scale the preview image in these cases instead of downsample the the real image.

The following code snippet should work for most purposes. I have noticed that GetThumbnail does do a better job of smoothing. Maybe someone could add a mosaic blur to this but in my case that would take too much cpu.

#region BetterThumbnail
public static Bitmap BetterThumbnail(Bitmap inputImage, int width, int height)
{
Bitmap outputImage = new Bitmap(width, height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(outputImage);
g.CompositingMode = CompositingMode.SourceCopy;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle destRect = new Rectangle(0, 0, width, height);
g.DrawImage(inputImage, destRect, 0, 0, inputImage.Width, inputImage.Height, GraphicsUnit.Pixel);
g.Dispose();
return outputImage;
}
#endregion

deni
August 31, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

Need help. I read am image from a database into a bitmap object, edit it. Now i need a way to display edited bitmap in a <asp:image> WITHOUT saving it to the disk nor in the database. The idea is the usesr to see the result and if he/she likes it, then save it in the database.
Regards to all
Deni

justpassingby
September 13, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

Store it in a session and then cast it out to display. If they like it then write the session to the db.

marshall
September 19, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

thanks for the code. makes life a bit easier.

Ian
September 22, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

Good Code!!!!

Teebo
October 08, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

Hi.
Thank's a lot for your code :-)
Have a good day
Teebo from France

campbell
October 20, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

I'm working to retain GIF transparency which is showing up completely black. I've gotten this far:

bmpOut = New Bitmap(newWidth, newHeight, PixelFormat.Format32bppArgb)
gr = Graphics.FromImage(bmpOut)
gr.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
gr.CompositingMode = Drawing2D.CompositingMode.SourceCopy
Dim rect As New Rectangle(0, 0, newWidth, newHeight)
gr.DrawImage(src, rect, 0, 0, newWidth, newHeight, GraphicsUnit.Pixel)

however bmpout hasn't been resized from the src bitmap but the background is now black instead of transparent. Can someone point out the error please?

Thanks

jhack
November 17, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

Im working on rotating jpg images. i have got been able to rotate them however im left with a black background. i would like the background to be trasparent.

this is what iv got so far :


int rot =1;

int temp= ((lnNewHeight*lnNewHeight)+(lnNewWidth*lnNewWidth));

temp = (int) Math.Sqrt(temp);

int imageh = lnNewHeight+200;
int imagew = lnNewWidth+200 ;

bmpOut = new Bitmap(imagew, imageh);


Graphics g = Graphics.FromImage(bmpOut);

g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;



//g.FillRectangle( Brushes.White,0,0,imagew,imageh);




g.TranslateTransform((imagew/2),(imageh/2));
g.RotateTransform(rot);

g.DrawImage(loBMP,(lnNewWidth/2)*-1,(lnNewHeight/2)*-1,lnNewWidth,lnNewHeight);
g.RotateTransform(-rot);

Thanks in advance.
jhack

kaushik
December 12, 2005

# re: Problem in rotate image in vb.net web application

Hi
In my application, I have to rotate the image.

To rotate image i am using

Dim fullSizeImg As System.Drawing.Image
fullSizeImg = System.Drawing.Image.FromFile(Server.MapPath("../UserUploadedImages/" & FolderName & "/") + filenewnameTemp)
fullSizeImg.RotateFlip(RotateFlipType.Rotate90FlipNone)

It's working fine. But when I am saving the image after rotating. The size of the image become larger than it's previous size.

How will i stop it?













Ryan J
December 16, 2005

# re: Creating Thumbnail Images on the fly with ASP.Net

Thank you for doing this Rick.. I've been looking for an example like this for quite some time.

Just one note, there is something missing from your example code, in order for the following piece of code to work, you must include the system namespace.

Code that errors out (with .NET 2.0):
Size = Int32.Parse(sSize);

Fix - place this at the top of your code:
using System;

sefo
January 05, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

Hi,

I used to use the same code as in the article and it worked great on the version of .NET before 2.0

The error I get now is:

XML Parsing Error: no element found
Location: http://xxx.com/Axxx/CreateThumbnail.aspx?image=/img/products/4017.jpg&size=100

I haven't modified anything, the image exists.
I only moved to .NET 2.0 (which might be a mistake in itself)

And the fix RianJ proposes doesn't work.
Well, if you don't put "using System", you will get an error anyway on any version of .NET

Any idea?

Jonathan
February 15, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

I'm using the exact code supplied by Rick above and am getting the following error:

Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1513: } expected

Source Error:



Line 7: using System.Drawing.Imaging;
Line 8:
Line 9: ...
Line 10:
Line 11:


yoni
March 19, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

Hi,
In the following line:
g.FillRectangle( Brushes.White,0,0,lnNewWidth,lnNewHeight);

If you replace White with a more complex color (e.g LightGreen) it looks pretty bad.
Have you tried anything like that before? If so, do you have any solutions?

Thanks.

Zyad
March 30, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

Will this code work fine with jpeg images also, because I get a black effect before the image is loaded ?

Tim
March 30, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

Your code works great thank you.

Netflash
May 02, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

This doesn't work anymore on asp.net 2.0.

Does anyone has a fixed version for it?

Rick Strahl
May 02, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

Sure it does... I use this code all the time...

Netflash
May 02, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

do you have a sample of a working example in asp.net 2.0? My sample its not working anymore and i dont know why because there are no errors. The imagem just doesnt appear.

if you can send me a simple sample in asp,net 2.0 , my email is pub01@netcabo.pt.

Thank you.

Netflash
May 02, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

Forget what i said. It works perfectly. I made a basic mistake! I had a Response.Write lost somewhere and it was sending info. That's way the image didn't appear. Problem solved.

Tell me something. Why didn't you implement this solution has an HttpHandler? Do you have any new version of this code working as an Http Handler?

Thank you.

camike
May 12, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

I just get a blank screen when I go directly to the file and an x when I call it in a page. Maybe I'm not calling it right. I have a createthumb.aspx page that runs createthumb.aspx.cs as it's source? Is that correct?

Mathivanan
May 17, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

Excellent example

Mark
June 07, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

I cant seem to get this working using asp.net 2.0 with vb.net. If anyone has a working fully example it would be great to see!

Thanks

Erol Kutuk
June 15, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

Thnx Men
Good job,
Excellent,

Mojo
June 18, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net


Roshan
June 27, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

Thanks for sharing this code Rick! It's helping heaps with designing my website to display my holiday photos.

Chris
July 06, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

Hi Rick, I tried to get this to work with TIFF's but received the "An generic error occurred in the GDI+."

I changed the MIME types in your code to:

Response.ContentType = "image/tiff";
bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Tiff);
bmp.Dispose();

I verified that the MIME type is correct. I don't want to save the file, just view the thumbnail of a TIFF that I have.

btw... This is nice work as I've got this to work with JPG/GIF images

Rick Strahl
July 06, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

You can't save some image types directly into the Response stream. Instead create a binary array then use BinaryWrite() to output it explicitly.

Dusty
August 11, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

Nice work Rick. Your code works great. I have one question though. I created an aspx page, called PhotoHandler.aspx, that has a code behind page. This code behind page has exactly the same code you have listed above.

It works perfectly when I go direclty to PhotoHandler.aspx, but I am trying to create a page that displays other information in a DetailsView along with the picture. I am storing the image name in a database and one of my DetailsView ItemTemplates grabs the image name and should display the image as a thumbnail. So what I have done is the following.

<ItemTemplate>
<a href="PhotoHandler.aspx?Image=<%# Eval("photo") %>&Size=300" target="_blank" >
<img src="PhotoHandler.ashx?Image=<%# Eval("photo") %>&Size=120" alt='<%# Eval("photo") %>' /></a>
</ItemTemplate>

The ItemTemplate is displaying X photo.jpg (it acts like it cannot find the image). If I click on it, the image is diplayed correclty in a seperate page.

Any Ideas?

Thanks,

Dusty

Dusty
August 11, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

Rick,

Please disregard the last post. I should pay more attention to what I put in my code. It works just fine if you type the correct name of the aspx file.

<ItemTemplate>
<a href="PhotoHandler.aspx?Image=<%# Eval("photo") %>&Size=300" target="_blank" >
<img src="PhotoHandler.ashx?Image=<%# Eval("photo") %>&Size=120" alt='<%# Eval("photo") %>' /></a>
</ItemTemplate>

PhotoHandler.ashx should be PhotoHandler.aspx.

Sorry.

Thanks,

Dusty

fernando
August 13, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

its works with .net 2 framework?

Error 1 'ASP.createthumbnail_aspx.GetTypeHashCode()': no suitable method found to override c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\upload\7d1a9899\15aed5ad\App_Web___kghg--.2.cs 289

Error 2 'ASP.createthumbnail_aspx.ProcessRequest(System.Web.HttpContext)': no suitable method found to override c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\upload\7d1a9899\15aed5ad\App_Web___kghg--.2.cs 293

Error 3 'ASP.createthumbnail_aspx' does not implement interface member 'System.Web.IHttpHandler.IsReusable' c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\upload\7d1a9899\15aed5ad\App_Web___kghg--.2.cs 129

Error 4 Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct base class (e.g. Page or UserControl). D:\.NET\upload\createThumbnail.aspx.cs 1 33 D:\.NET\upload\






Arjen
August 22, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

@Rick Strahl or someone else...

With you code I resize .jpg files but the interpolation s*cks! All thumbs have bad borders.

What can I do about this?
(If tried all the interpolation modes)

Second, I also tried to use these lines in your code...
// System.Drawing.Image imgOut =
// loBMP.GetThumbnailImage(lnNewWidth,lnNewHeight,
// null,IntPtr.Zero);

I tried to uncomment these lines and commented the lines below, results are errors...

How can I use this funtion?

Thanks!!!

Rick Strahl
August 22, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

What do you mean bad borders? The code just uses standard GDI+ image resizing and resizing will work better on some types of images than others. Things like line drawings and text necessarily are probably going to look bad because those require special image filters for proper reduction in size. The generic code like this here will work best on highly diffuse images like pictures...

Chris
September 14, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

thanks for the awesome code!

Jeff
September 22, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

I didn't see a response to Jons question about creating a thumbnail image of a frame from a video file. Can this be done? Thank you!
Jeff


Web Forms
September 30, 2006

# ASP.NET Forums - Thumbnail Problem


System.Drawing/GDI+
October 02, 2006

# ASP.NET Forums - How to Resize an Image in ASP.NET?


cpt.oneeye
October 03, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

I have a problem when using this code.

When i am resizing jpg's the quality is very good. but i always have a white thin border on the bottom and right side of the image.

does anyone have the same effect?

greetings

System.Drawing/GDI+
October 05, 2006

# ASP.NET Forums - Thumbnail images


Mustafa
October 05, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

well the code runs fine, but the thumbnail which is saved is not viewable through internet explorer.. can anybody tell me whats the reason behind that and is there any remedy.

Web Forms
October 09, 2006

# ASP.NET Forums - image load times, should I use thumbnails?


julia
October 10, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

Hi ,

Thanks for ur code!
I would like to show the thumbnail image in htmlImage control/Asp:Image control.
How should I do that?
In ur sample code, it shows in the page itselft.
I want to show the thumnail in the image control.
Thanks.

Rick Strahl's Web Log
October 24, 2006

# GDI+ InterpolationMode - Rick Strahl's Web Log

Resizing images can cause images to loose some of their quality as the images are resampled. You can control the algorithms used for the resize resampling by using the Graphics object's InterpolationMode property.

Data Presentation Controls
October 31, 2006

# ASP.NET Forums - Problem with creating Thumbnail Image within the Datalist?


Cute Editor for .NET
November 09, 2006

# Support forums - Thumbnails

ASP.NET Chat, web messenger, ASP.NET HTML Editor and Live Support

System.Drawing/GDI+
November 16, 2006

# ASP.NET Forums - Why the thumbnail is blurry?


System.Drawing/GDI+
November 17, 2006

# ASP.NET Forums - Scale BMP Image to Smaller Size


Getting Started
November 20, 2006

# ASP.NET Forums - How to save a thumbnail while uploading images

# Snitz Forums 2000 - Creating thumbnails?


ahmednaxim
December 08, 2006

# ahmednaxim: Dynamic image resizing and caching in ASP .NET


ainey
December 10, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

hai....im new in this asp.net....and posting stuff too... =)

dear dusty and everyone else... = )
i saw ur code that you've posted....
it is similar with what ive done...
it shows the image in different page right?
what if i want to show it in the same page for example at the bottom of the page?
ive been trying to do it by using frames but it didnt work...
plz help....
my code is similar to yours...

<ItemTemplate>
<a href="getImg.aspx??mdi_id=" %><%# DataBinder.Eval(Container, "DataItem.MDI_ID")%>'>
<img src="getImg.aspx??mdi_id=" %><%# DataBinder.Eval(Container, "DataItem.MDI_ID")%>' /></a>
</ItemTemplate>

John
December 29, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

I would like to save an uploaded image in jpg-format and set the jpg-quality to 80 (1-100)
A jpg-image in acceptable quality 400x300pix shod be around 50kb.
Is that possible?

By the way.
Mustafa ”… but the thumbnail which is saved is not viewable through internet explorer”
Is the jpg file saved in CMYK? You must use RGB for use in web browsers.

Mike Clark
December 30, 2006

# re: Creating Thumbnail Images on the fly with ASP.Net

Your scaling function is a bit flawed.

It checks which is bigger, the new width or height, and calculates the scale from that. You should find which scale (width or height) is larger proportionally, and use that.

Fix:-
//      if (loBMP.Width > loBMP.Height)
//      {
//        lnRatio = (decimal)lnWidth / loBMP.Width;
//        lnNewWidth = lnWidth;
//        decimal lnTemp = loBMP.Height * lnRatio;
//        lnNewHeight = (int)lnTemp;
//      }
//      else
//      {
//        lnRatio = (decimal)lnHeight / loBMP.Height;
//        lnNewHeight = lnHeight;
//        decimal lnTemp = loBMP.Width * lnRatio;
//        lnNewWidth = (int)lnTemp;
//      }

      // Calculate scale (to divide the image by)
      Decimal decScale;

      if (((Decimal)loBMP.Width / (Decimal)lnWidth) > ((Decimal)loBMP.Height / (Decimal)lnHeight))
        decScale = (Decimal)loBMP.Width / (Decimal)lnWidth;
      else
        decScale = (Decimal)loBMP.Height / (Decimal)lnHeight;

      lnNewHeight = (int)((Decimal)loBMP.Height / decScale);
      lnNewWidth = (int)((Decimal)loBMP.Width / decScale);

Dave Bouwman
January 03, 2007

# Dave Bouwman - Moving the site to ASP.NET 2.0: Part 2

Software Development :: .NET - GIS - ESRI

# Snitz Forums 2000 - Adding transparent pixels to images


Mark Ismail
January 21, 2007

# re: Creating Thumbnail Images on the fly with ASP.Net

Sounds great, can you tell us how can i display a small part of the thumbnailed image?

Shan Plourde
February 08, 2007

# re: Creating Thumbnail Images on the fly with ASP.Net

Hi Rick, somewhat related, I created a reusable dynamic email address / text generator, useful for rendering email addresses on web pages. The image output quality is pretty good, pretty usable. http://shan-tech.blogspot.com/2007/02/aspnet-20-mask-your-email-addresses.html

Shan-Tech
February 08, 2007

# Shan-Tech: ASP.NET 2.0 Mask Your Email Addresses With Dynamically Generated Images


Martin Cook
February 15, 2007

# re: Creating Thumbnail Images on the fly with ASP.Net

Exactly what I needed.

Thanks a lot!
Martin

Ray B
February 21, 2007

# re: Creating Thumbnail Images on the fly with ASP.Net

Thanks Rick...

The code works very well, and indeed the thumbnail is very clear... but like others... I'm trying to pull this image into an asp/image control... ie; if I want to display thumbnails of several scanned images at the bottom of my asp.net page... how do I accomplish this? I guess the image could be saved to a temp dir and called using imageurl = ... but is there some way so I don't have to junk up the server with temp files...

Thanks!
Ray B

Getting Started
February 26, 2007

# ASP.NET Forums - thumbnail images?


mike
March 12, 2007

# re: Creating Thumbnail Images on the fly with ASP.Net

I'm fairly new to asp.net and I was wondering if someone can give me the actuall aspx page. I'm having a problem using this code.

Shawn "jitterjepp"Jeppesen
March 18, 2007

# re: Creating Thumbnail Images on the fly with ASP.Net

re: Creating Thumbnail Images on the fly with ASP.Net Feb 21, 2007 12:17 Ray B

I'm trying to pull this image into an asp/image control... ie; if I want to display thumbnails of several scanned images at the bottom of my asp.net page... how do I accomplish this? I guess the image could be saved to a temp dir and called using imageurl = ... but is there some way so I don't have to junk up the server with temp files...

Thanks!
Ray B

This is what I did and I don't know if it answers you question or not....

I used the code above (Ricks Code) for a page ThumbImages.aspx

Then in the page where I have an asp image control I made the Image url that page and passed the image file as a paramater like this but I'm not passing the size. I set the image to a specific size in Ricks code. However it's probably better to pass the size as well for reusability for images that may not be the size I set in the file. I also believe I changed the name of the Parameter to "Image" from whatever it was that Rick had for the image file name.

Dim myImageFile as string = (image file name is passed from an sql table)
Image1.ImageUrl = "ThumbImage.aspx?Image=" & "../MyImages/" & myImageFile

I have multiple image controls calling the ThumbImage.aspx file from the same page and I don't see any problems. I generally don't do this type of programming so I can't say if this is the best solution but it is working and changing 2 meg image files to 6.7k.

steven
March 27, 2007

# re: Creating Thumbnail Images on the fly with ASP.Net

I have a weird problem... I implemented the code in VB.NET (1.1) and it worked great locally (Windows XP Sp2).
When the code was moved to our Dev server (Windows 2003), it started giving problems. When viewing the page in IE, it would freeze it for about a minute, and some images would come through on the page, while others would give red X (even though they exist on disk and I can view them when going directly to the URL). I can't pinpoint the problem - all images are JPG, and I have tested alot of different ones - some come through, others give red X... After about a minute or two of load time, IE would "unfreeze" but at the status bar it would say "Downloading two items..." and it is obvious is trying to download some images it hasn't yet made into red X.
Can anyone help with please??? Desperate.

Thanks.

Souvik
May 17, 2007

# re: Creating Thumbnail Images on the fly with ASP.Net

Hi,

Thanx. Finally i get the right code. That's so nice of you.
Thanx again.

Bye

ASP.NET Forums
May 18, 2007

# thumbnail images? - ASP.NET Forums


ASP.NET Forums
May 18, 2007

# Thumbnail Problem - ASP.NET Forums


ASP.NET Forums
May 18, 2007

# How to Resize an Image in ASP.NET? - ASP.NET Forums


ASP.NET Forums
May 18, 2007

# Thumbnail images - ASP.NET Forums


ASP.NET Forums
May 23, 2007

# How to save a thumbnail while uploading images - ASP.NET Forums


ASP.NET Forums
May 23, 2007

# Why the thumbnail is blurry? - ASP.NET Forums


ASP.NET Forums
May 23, 2007

# Scale BMP Image to Smaller Size - ASP.NET Forums


ASP.NET Forums
May 28, 2007

# Problem with creating Thumbnail Image within the Datalist? - ASP.NET Forums


ASP.NET Forums
June 21, 2007

# image load times, should I use thumbnails? - ASP.NET Forums


Sameer
June 22, 2007

# re: Creating Thumbnail Images on the fly with ASP.Net

Very nice. Just a tip, a good practice is to use the System.IO.Path() class when putting together folders, such as :)

string folder = GetSomePathHere() + Path.DirectorySeparatorChar;


This could technically work even on Linux! Cuz it would put / instead of \
Here's a full article on it: http://haacked.com/archive/2007/06/13/the-most-useful-.net-utility-classes-developers-tend-to-reinvent.aspx

ASP.NET Forums
July 04, 2007

# How to restrict Image Size while upload? - ASP.NET Forums


eggheadcafe.com articles
July 17, 2007

# C# .NET displaying video/image thumbnails asp.net


ASP.NET Forums
July 18, 2007

# Generating dnamic Thumbnail and PNG support in IE6 - ASP.NET Forums


Pranav, Pawan
July 31, 2007

# re: Creating Thumbnail Images on the fly with ASP.Net

great code... really saved us a lot of time....
thanks

Bhushan
August 07, 2007

# re: Creating Thumbnail Images on the fly with ASP.Net

Hello,

I am using the code as you said but I am getting problem when I am trying to Create thumbnail of image of size around 2MB. It is saying out of memory can anyone tell why?
image is a .jpg image.

Jerry
September 27, 2007

# re: Creating Thumbnail Images on the fly with ASP.Net

My back ground is more in industrial process control software. As I move over to this type of programing I find myself reading many articles to increase my knowledge. So here is my question. I am presently putting together a site. This site will have about 15-20 pictures on a dynamic page where the surfer can click on a picture and see the larger image. These pictures are about 480x640 (portrait) and 50-60K in size. To start with I just put them in an image control and set the width to 100px. works good but I know I have the overhead of loading the big picture just to display the smaller one. So I was thinking of creating a thumbnail in a seperate directory when the pictures are orginally placed on the web. Again takes up real estate. So what will this method gain me over the manner I load the pictures now, and how does it compare to using an IHttpHandler?

Jerry

Lance
November 21, 2007

# re: Creating Thumbnail Images on the fly with ASP.Net

Great article...gave me a great headstart with the topic. I always appreciate your articles and this one is no exception :).

Iqusan
December 09, 2007

# re: Creating Thumbnail Images on the fly with ASP.Net

The code was very complet ,tanx

Exterior Shutters
January 06, 2008

# re: Creating Thumbnail Images on the fly with ASP.Net

I ran across another great article that used an ashx file instead of a regular page class.

http://www.eggheadcafe.com/articles/20041104.asp

IMHO this seems like a better solution than using a page class and probably uses slightly less overhead. However, his solution didn't have a fix for the image tranparency issue (which I am sure to have), so I ended up making a hybrid of both.

I didn't put in the "save" functionality, although it is not difficult to add if you need it. Here is my solution in VB.NET:


<%@ WebHandler Language="VB" Class="ThumbnailHandler" %>

Imports System
Imports System.IO
Imports System.Web
Imports System.Drawing
Imports System.Drawing.Imaging


Public Class ThumbnailHandler
    Implements IHttpHandler

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim path As String = [String].Empty
    
        Dim sSize As String = context.Request("size")
        Dim Size As Integer = 120
        If Not (sSize Is Nothing) Then
            Size = Int32.Parse(sSize)
        End If
    
        ' get path for 'no thumbnail' image if you want one
        Const NoThumbFile As [String] = "nothumb.jpg"
        Dim NoThumbPath As [String] = context.Request.MapPath((context.Request.ApplicationPath.TrimEnd("/"c) + "/images/" + NoThumbFile))

        Dim image As String = context.Request.QueryString("image")
        If Not image Is Nothing Then
            path = context.Server.MapPath(context.Request.ApplicationPath) + "\" + image
        Else
            path = NoThumbPath
        End If
    
        Dim thumbBitmap As Bitmap
        thumbBitmap = New Bitmap(path)
        If thumbBitmap Is Nothing Then
            thumbBitmap = New Bitmap(NoThumbPath)
        End If
  
        If Not (context.Request("thumb") Is Nothing) And context.Request("thumb") = "no" Then
            context.Response.ContentType = "image/Jpeg"
            thumbBitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
        Else
            thumbBitmap = CreateThumbnail(path, Size, Size)
            context.Response.ContentType = "image/Jpeg"
            thumbBitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
        End If
    End Sub 'ProcessRequest

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return True
        End Get
    End Property

    ''' <summary>
    ''' Creates a resized bitmap from an existing image on disk. 
    ''' Call Dispose on the returned Bitmap object
    ''' </summary>
    ''' <param name="lcFilename"></param>
    ''' <param name="lnWidth"></param>
    ''' <param name="lnHeight"></param>
    ''' <returns>Bitmap or null</returns>
    ''' <remarks></remarks>
    Private Shared Function CreateThumbnail(ByVal lcFilename As String, ByVal lnWidth As Integer, ByVal lnHeight As Integer) As Bitmap

        Dim bmpOut As System.Drawing.Bitmap = Nothing
        Try
            Dim loBMP As New Bitmap(lcFilename)
            Dim loFormat As ImageFormat = loBMP.RawFormat

            Dim lnRatio As Decimal
            Dim lnNewWidth As Integer = 0
            Dim lnNewHeight As Integer = 0

            '*** If the image is smaller than a thumbnail just return it
            If loBMP.Width < lnWidth And loBMP.Height < lnHeight Then
                Return loBMP
            End If

            If loBMP.Width > loBMP.Height Then
                lnRatio = CDec(lnWidth) / loBMP.Width
                lnNewWidth = lnWidth
                Dim lnTemp As Decimal = loBMP.Height * lnRatio
                lnNewHeight = CInt(lnTemp)
            Else
                lnRatio = CDec(lnHeight) / loBMP.Height
                lnNewHeight = lnHeight
                Dim lnTemp As Decimal = loBMP.Width * lnRatio
                lnNewWidth = CInt(lnTemp)
            End If

            ' System.Drawing.Image imgOut = 
            '      loBMP.GetThumbnailImage(lnNewWidth,lnNewHeight,
            '                              null,IntPtr.Zero);


            ' *** This code creates cleaner (though bigger) thumbnails and properly
            ' *** and handles GIF files better by generating a white background for
            ' *** transparent images (as opposed to black)
            bmpOut = New Bitmap(lnNewWidth, lnNewHeight)
            Dim g As Graphics = Graphics.FromImage(bmpOut)
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
            g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight)
            g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight)

            loBMP.Dispose()
        Catch
        End Try

        Return bmpOut
    End Function 'CreateThumbnail 

End Class 'ThumbnailHandler

Gus G.
April 08, 2008

# re: Creating Thumbnail Images on the fly with ASP.Net

I finnally found what I was looking for, your code is clean and easy to understand. Good job

Joe
April 17, 2008

# re: Creating Thumbnail Images on the fly with ASP.Net

Thanks for a clean solution. GetThumbnail... was driving me CRAZY!

Buddika
June 02, 2008

# re: Creating Thumbnail Images on the fly with ASP.Net

thanks a lot for valuble solution. good job. thanks again.

Ben
June 05, 2008

# re: Creating Thumbnail Images on the fly with ASP.Net

Great Job! Worked on the first try!

One thing I noticed that surprised me is the file size of the resized jpeg when saved to disk using the OutputFileName was nearly twice the size of the original file even thought the resized file was smaller in terms of pixel dimensions.

Anyone know what gives with that? Does something with the color depth or some other image properties get reset when the image is saved?

Alfredo
June 09, 2008

# re: Creating Thumbnail Images on the fly with ASP.Net

Hi, i'm trying to integrate your code on my website, but the file MakeThumb.aspx does not even executes. I set a break point on the load event of MakeThumb.aspx and it never pases through. I was making some tests in order to find the problem, so i tryed your code on a single website and it worked, but not on my site... i supposed it was something on my web.config. At the end of my tests i realized that if i use :
<pages styleSheetTheme="Default" theme="Default"></pages>
on my web.config file the thumb will never work, i wonder if you have an idea why. Thanks for your help.

Arsalan
July 23, 2008

# re: Creating Thumbnail Images on the fly with ASP.Net

Hi,
very nice code. I am into one problem > This code works fine as fars as we try to generate thumbnail of smaller size then that of original Image . For example if original image is of 100X100 and we try to generate thumbnail of 200X200(greater then that of original image ) then //*** If the image is smaller than a thumbnail just return it

if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)

return loBMP;
returns original image. However I want to generate evern bigger image from original image . Please help if possible. I need it badly.

Nathanael Jones
August 06, 2008

# re: Creating Thumbnail Images on the fly with ASP.Net

Thanks Rick! I used this article about 2 years ago when I was building my image resizing system.

There is a downside of using a .aspx or .ashx handler and accepting the path through the query string... it could be used to access protected images...

I opted for a integrated approach, so you just can add a querystring to the image like so:

image.jpg?thumbnail=png&width=200

That way the URL authorization still applies.

You also really need disk caching before you using image resizing in a production system. For really busy servers, persistent caching is a must.

You can download my code here
http://nathanaeljones.com/products/asp-net-image-resizer/

Dan
October 10, 2008

# re: Creating Thumbnail Images on the fly with ASP.Net

I must be a fool., I can't seem to get this to work. I simply get a blank white page. I've tried to include the outputfilename as well and still nothing. can you advise

Henko
October 17, 2008

# Nice code - but you have forgotten 20% of the surfers

Hello

Nice code - gonna check it out! Allthough - you should really check the page so that it atleast works well in FF besides IE. Now - parts of the code gets underneath som div tags - kind of hard to read...

Nikola
November 17, 2008

# re: Creating Thumbnail Images on the fly with ASP.Net

Great code! Thanks! :)

David Cox
December 23, 2008

# re: Creating Thumbnail Images on the fly with ASP.Net

Firstly many thanks for sharing this code:

I am using it in an application but with a slight difference, having images in portrait and landscape I wanted to have a transparent background with the image "scaled and centered", I created a small free standalone application for SlideShowPro which can be downloaded from my site and the images on the link were created with this code:

http://www.adeptris.co.uk/SlideShow/Gallery/tabid/143/Default.aspx

The newX and newY centre the Image

 Private Shared Function CreateThumbnail(ByVal lcFilename As String, ByVal lnWidth As Integer, ByVal lnHeight As Integer) As Bitmap
        Dim bmpOut As System.Drawing.Bitmap = Nothing
        Try
            Dim loBMP As New Bitmap(lcFilename)
            Dim loFormat As ImageFormat = loBMP.RawFormat

            Dim lnRatio As Decimal
            Dim lnNewWidth As Integer = 0
            Dim lnNewHeight As Integer = 0

            '*** If the image is smaller than a thumbnail just return it
            If loBMP.Width < lnWidth And loBMP.Height < lnHeight Then
                Return loBMP
            End If

            If loBMP.Width > loBMP.Height Then
                lnRatio = CDec(lnWidth) / loBMP.Width
                lnNewWidth = lnWidth
                Dim lnTemp As Decimal = loBMP.Height * lnRatio
                lnNewHeight = CInt(lnTemp)
            Else
                lnRatio = CDec(lnHeight) / loBMP.Height
                lnNewHeight = lnHeight
                Dim lnTemp As Decimal = loBMP.Width * lnRatio
                lnNewWidth = CInt(lnTemp)
            End If

            Dim newX As Integer = 0
            Dim newY As Integer = 0
            If lnNewWidth < lnWidth Then
                newX = CInt(((lnWidth) - lnNewWidth) / 2)
            End If
            If lnNewHeight < lnHeight Then
                newY = CInt((lnHeight - lnNewHeight) / 2)
            End If
            bmpOut = New Bitmap(lnWidth, lnHeight)
            Dim g As Graphics = Graphics.FromImage(bmpOut)
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
            g.FillRectangle(System.Drawing.Brushes.Transparent, 0, 0, lnWidth, lnHeight)
            g.DrawImage(loBMP, newX, newY, lnNewWidth, lnNewHeight)
            loBMP.Dispose()
        Catch
        End Try
        Return bmpOut
    End Function 'CreateThumbnail


David

reza zamanian
September 22, 2009

# re: Creating Thumbnail Images on the fly with ASP.Net

i am not professional in english language
this code worked fine.
thanks alot.
for completing your code you can add this option to your code
1- add a watermark text such as copyright text or my web site name on the image
2-add a arm (graphic image) on the image with different opacity
3-programmer can change location of arm and watermarked text for example top-right ,top-left,top-center,center-left,center-center,center-right,buttom-left,buttom-center,button-right
4-programmer can change opacity of watermarked text and image
5-add a comment for image types that your code support for example png? ,jpg?,gif?,psd?,tiff?,...
6-if type of file is gif it convert source image to gif and if type of file is png it convert source image to png and ...
7-font size of watermarked text can automatically increace such that the best font size can selected by code
8-if font size for watermark is too small it can divid into two line

you can view this article in code project that implements watermarked text and image

http://www.codeproject.com/KB/GDI-plus/watermark.aspx
http://www.codeproject.com/KB/GDI-plus/watermark.aspx
http://www.codeproject.com/KB/GDI-plus/watermark.aspx

thanks alot .
if you complete this option please mail me for aware of competion
thanks.

Sunil Prasad
February 19, 2010

# How will convert imageUrl to image in Gridview

Hi,
I stored the images Url in database . I want to display all images url in GridView without any hyperlink in ASP.net.
Can u help me guys......


-----
Sunil Prasad,
Contact ;- 9970925075

Dotnet Sizzler
April 04, 2010

# Generating Thumbnail Image in ASP.NET

Generating Thumbnail Image in ASP.NET

Vigirtheeswaran
April 13, 2010

# re: Creating Thumbnail Images on the fly with ASP.Net

Thanks a ton!!!!! This is what i am searched for long term.............. and ends here...! What a technique. Simple but powerful!!!!

Robert Hyatt
April 27, 2010

# re: Creating Thumbnail Images on the fly with ASP.Net

Thanks. This was exactly what I was hoping to find creating thumbnails. Well done.

Murthy
June 11, 2010

# re: Creating Thumbnail Images on the fly with ASP.Net

i found a free dll to resizeImages at http://aspspider.net/deeven/
Its working fine..

Man
July 21, 2010

# re: Creating Thumbnail Images on the fly with ASP.Net

The code works fine, but the resized(smaller size) image has a larger size than the orginal image.

Oleg
July 27, 2010

# re: Creating Thumbnail Images on the fly with ASP.Net

Thanks man.
Very straightforward and simple. Just like it should be.

Dotnet Sizzler
August 01, 2010

# Generating Thumbnail Image in ASP.NET

Generating Thumbnail Image in ASP.NET

Noel
March 14, 2011

# re: Creating Thumbnail Images on the fly with ASP.Net

Great! Thanks. I've seen this solution along time ago but I made it work just today. Thanks. I like the fact that it keeps its ration proportion. Thank you very much.
 


West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2015