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:
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
///
///
///
///
///
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.
Other Posts you might also like
- Adding minimal OWIN Identity Authentication to an Existing ASP.NET MVC Application
- Resolving Paths To Server Relative Paths in .NET Code
- Map Physical Paths with an HttpContext.MapPath() Extension Method in ASP.NET
- Back to Basics: Rewriting a URL in ASP.NET Core
- Getting the Client IP Address in ASP.NET Core
The Voices of Reason
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
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?
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
I tried to save to a filestream before and they worked.
# re: Creating Thumbnail Images on the fly with ASP.Net
if (this.User.Identity.Name == "") {
bmp.Dispose();
this.ErrorResult();
}
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
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);
# re: Creating Thumbnail Images on the fly with ASP.Net
Thanks for any help, you can also contact me at ChadBeckner@ProspectiveLink.com
Chad
# re: Creating Thumbnail Images on the fly with ASP.Net
http://west-wind.com/weblog/posts/283.aspx
# re: Creating Thumbnail Images on the fly with ASP.Net
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);
}
}
# re: Creating Thumbnail Images on the fly with ASP.Net
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
# re: Creating Thumbnail Images on the fly with ASP.Net
Nitpick:
As far as I can tell, this line:
ImageFormat loFormat = loBMP.RawFormat;
is not required.
Thanks,
Frank
# re: Creating Thumbnail Images on the fly with ASP.Net
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
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
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
# re: Creating Thumbnail Images on the fly with ASP.Net
kes
# re: Creating Thumbnail Images on the fly with ASP.Net
Nice turorial, I picked up a couple ideas.
Chris
# re: Creating Thumbnail Images on the fly with ASP.Net
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
# re: Creating Thumbnail Images on the fly with ASP.Net
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
# re: Creating Thumbnail Images on the fly with ASP.Net
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!
# re: Creating Thumbnail Images on the fly with ASP.Net
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.
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
<%@ OutputCache duration="10000" varybyparam="Image;Size" %>
Where you mention the cache-possibility, is not displayed?
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
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.)
# re: Creating Thumbnail Images on the fly with ASP.Net
very nice !!
# re: Creating Thumbnail Images on the fly with ASP.Net
<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?
# re: Creating Thumbnail Images on the fly with ASP.Net
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.)
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
# Creating Thumbnail Images on the fly with 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
# re: Creating Thumbnail Images on the fly with ASP.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
# Overlapping Images
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
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
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
# re: Creating Thumbnail Images on the fly with ASP.Net
Regards to all
Deni
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
Thank's a lot for your code :-)
Have a good day
Teebo from France
# re: Creating Thumbnail Images on the fly with ASP.Net
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
# re: Creating Thumbnail Images on the fly with ASP.Net
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
# re: Problem in rotate image in vb.net web application
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?
# re: Creating Thumbnail Images on the fly with ASP.Net
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;
# re: Creating Thumbnail Images on the fly with ASP.Net
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?
# re: Creating Thumbnail Images on the fly with ASP.Net
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:
# re: Creating Thumbnail Images on the fly with ASP.Net
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.
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
Does anyone has a fixed version for it?
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
if you can send me a simple sample in asp,net 2.0 , my email is pub01@netcabo.pt.
Thank you.
# re: Creating Thumbnail Images on the fly with ASP.Net
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.
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
Thanks
# re: Creating Thumbnail Images on the fly with ASP.Net
Good job,
Excellent,
# re: Creating Thumbnail Images on the fly with ASP.Net
http://www.dotnet247.com/247reference/msgs/28/140382.aspx
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
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
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
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
# re: Creating Thumbnail Images on the fly with ASP.Net
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
# re: Creating Thumbnail Images on the fly with ASP.Net
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\
# re: Creating Thumbnail Images on the fly with ASP.Net
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!!!
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
Jeff
# re: Creating Thumbnail Images on the fly with ASP.Net
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
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
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.
# re: Creating Thumbnail Images on the fly with ASP.Net
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>
# re: Creating Thumbnail Images on the fly with ASP.Net
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.
# re: Creating Thumbnail Images on the fly with ASP.Net
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);
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
Thanks a lot!
Martin
# re: Creating Thumbnail Images on the fly with ASP.Net
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
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
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.
# re: Creating Thumbnail Images on the fly with ASP.Net
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.
# re: Creating Thumbnail Images on the fly with ASP.Net
Thanx. Finally i get the right code. That's so nice of you.
Thanx again.
Bye
# re: Creating Thumbnail Images on the fly with ASP.Net
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
# re: Creating Thumbnail Images on the fly with ASP.Net
thanks
# re: Creating Thumbnail Images on the fly with ASP.Net
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.
# re: Creating Thumbnail Images on the fly with ASP.Net
Jerry
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
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
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
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?
# re: Creating Thumbnail Images on the fly with ASP.Net
<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.
# re: Creating Thumbnail Images on the fly with ASP.Net
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.
# re: Creating Thumbnail Images on the fly with ASP.Net
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/
# re: Creating Thumbnail Images on the fly with ASP.Net
# Nice code - but you have forgotten 20% of the surfers
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...
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
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
# re: Creating Thumbnail Images on the fly with ASP.Net
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.
# How will convert imageUrl to image in Gridview
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
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
Its working fine..
# re: Creating Thumbnail Images on the fly with ASP.Net
# re: Creating Thumbnail Images on the fly with ASP.Net
Very straightforward and simple. Just like it should be.
# re: Creating Thumbnail Images on the fly with ASP.Net