Home > Uncategorized > Create thumbnail from remote image in c#

Create thumbnail from remote image in c#

Most of the thumbnail scripts I came across show how to create a thumbnail from a local image, but if the image is on another server, then here’s a script in asp.net / c# for that:

protected void Page_Load(object sender, EventArgs e)
{
string Image = Request.QueryString[“Image”];
if (Image == null)
{
throw new Exception(“Image is required”);
}
string sSize = Request[“Size”];
int Size = 120;
if (sSize != null) Size = Int32.Parse(sSize);
Bitmap bmp = CreateThumbnail(Image, Size, Size);
// Put user code to initialize the page here
Response.ContentType = “image/jpeg”;
bmp.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
bmp.Dispose();
}

Then we add the code for CreateThumbnail;

public static Bitmap CreateThumbnail(string strUrl,int lnWidth, int lnHeight)
{

System.Drawing.Bitmap bmpOut = null;
System.Net.WebRequest request = System.Net.WebRequest.Create(strUrl);
System.Net.WebResponse response = request.GetResponse();
System.IO.Stream responseStream = response.GetResponseStream();
Bitmap loBMP = new Bitmap(responseStream);
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();
return bmpOut;
}

 

 

I’ll probably be developing this further to implement a local cache of thumbnails, but let’s see how this goes…

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: