With one day effort , i found how to generate quality images dynamicaly
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.SessionState;
using System.IO;
public class Handler : IHttpHandler,IReadOnlySessionState
{
public void ProcessRequest (HttpContext context) {
Image img = new Bitmap(context.Session["ImagePath"].ToString());
Size _newSize = new Size(800, 800);
img = ResizeImage(img, _newSize);
using (MemoryStream stream = new MemoryStream())
{
int quality = 150; //90 is the magic setting - really. It has excellent quality and file size.
System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);
//img.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
img.Save(stream, GetEncoderInfo("image/bmp"), encoderParameters);
stream.WriteTo(context.Response.OutputStream);
}
}
private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}
private static System.Drawing.Image ResizeImage(System.Drawing.Image original, Size newSize)
{ System.Drawing.Image result = new Bitmap(newSize.Width, newSize.Height);
using(Graphics g = Graphics.FromImage(result))
{ g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
g.DrawImage(original, 0, 0, newSize.Width, newSize.Height); }
return result;}
public bool IsReusable {
get {
return false;
}
}
}
Wednesday, May 27, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment