Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create thumbnail image

I want to display thumbnail image in a gridview from file location. How to generate that of .jpeg file? I am using C# language with asp.net.

like image 354
Red Swan Avatar asked May 11 '10 07:05

Red Swan


2 Answers

You have to use GetThumbnailImage method in the Image class:

https://msdn.microsoft.com/en-us/library/8t23aykb%28v=vs.110%29.aspx

Here's a rough example that takes an image file and makes a thumbnail image from it, then saves it back to disk.

Image image = Image.FromFile(fileName); Image thumb = image.GetThumbnailImage(120, 120, ()=>false, IntPtr.Zero); thumb.Save(Path.ChangeExtension(fileName, "thumb")); 

It is in the System.Drawing namespace (in System.Drawing.dll).

Behavior:

If the Image contains an embedded thumbnail image, this method retrieves the embedded thumbnail and scales it to the requested size. If the Image does not contain an embedded thumbnail image, this method creates a thumbnail image by scaling the main image.


Important: the remarks section of the Microsoft link above warns of certain potential problems:

The GetThumbnailImage method works well when the requested thumbnail image has a size of about 120 x 120 pixels. If you request a large thumbnail image (for example, 300 x 300) from an Image that has an embedded thumbnail, there could be a noticeable loss of quality in the thumbnail image.

It might be better to scale the main image (instead of scaling the embedded thumbnail) by calling the DrawImage method.

like image 137
Russell Troywest Avatar answered Sep 23 '22 20:09

Russell Troywest


The following code will write an image in proportional to the response, you can modify the code for your purpose:

public void WriteImage(string path, int width, int height) {     Bitmap srcBmp = new Bitmap(path);     float ratio = srcBmp.Width / srcBmp.Height;     SizeF newSize = new SizeF(width, height * ratio);     Bitmap target = new Bitmap((int) newSize.Width,(int) newSize.Height);     HttpContext.Response.Clear();     HttpContext.Response.ContentType = "image/jpeg";     using (Graphics graphics = Graphics.FromImage(target))     {         graphics.CompositingQuality = CompositingQuality.HighSpeed;         graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;         graphics.CompositingMode = CompositingMode.SourceCopy;         graphics.DrawImage(srcBmp, 0, 0, newSize.Width, newSize.Height);         using (MemoryStream memoryStream = new MemoryStream())          {             target.Save(memoryStream, ImageFormat.Jpeg);             memoryStream.WriteTo(HttpContext.Response.OutputStream);         }     }     Response.End(); } 
like image 29
Priyan R Avatar answered Sep 21 '22 20:09

Priyan R