简体   繁体   中英

Dynamically generating a thumbnail image from an URL image

I was wondering if anyone has some code/useful link explaining on how I could do this. I would most likely use it this way:

<img src="ShowThumb.aspx?image=http://the_image.jpg" alt="" />

Thanks.

Rather than using an .aspx file, use a Generic Handler file ( .ashx ). This means you only require the 1 file (no markup file), so its a bit neater and a bit quicker. Afterall, you're not generating a web form, so an .aspx file isn't what you're after.

You can make use of System.Drawing.Graphics.DrawImage() to produce a thumbnail.

Something as simple as this will work:

Bitmap bmpOut = new Bitmap(width, height);
Bitmap B = new Bitmap(context.Server.MapPath(ImageURL));

Graphics g = Graphics.FromImage(bmpOut);
g.InterpolationMode = InterpolationMode.High;
g.DrawImage(B, 0, 0, width, height);


context.Response.ContentType = "image/PNG";
MemoryStream MemStream = new MemoryStream();
B.Save(MemStream, System.Drawing.Imaging.ImageFormat.Png);

B.Dispose();

MemStream.WriteTo(HttpContext.Current.Response.OutputStream);

Where width & height are integer values, and ImageURL is a local URI string

I wouldn't resize your image using width/height attributes in HTML/CSS. This means you are sending the full size image to the client wasting everyones bandwidth and time! Furthermore, when HTML resizes it, it usually does a shoddy distorted job of it.


On a side note, I used to generate on-the-fly thumbnails like this, but decided that the performance was compromised as you are resizing the image everytime a HTTP request is made.

Therefore, whenever the main image was uploaded, I saved the thumbnail to a physical location, and called that in my HTML.

Youre on the right track: I did something like this once, only used an HTTP-Handler (ashx) for that. In there you can use the Image class to load the .jpg and resize and return it.

DON'T FORGET to restict the handler to only resize images on your domain, otherwise it could get quite dangerous (easy DOS-Attacks).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM