Redimensionar imagem dinamicamente usando C#
1- Crie uma nova página C# com o nome. thumbnails.aspx.
2- No Page load da página adicione.
string FileName = Request.QueryString["img"];
int MaxH = Convert.ToInt32(Request.QueryString["maxH"]);
int MaxW = Convert.ToInt32(Request.QueryString["maxW"]);
Image OriImg = Image.FromFile(Server.MapPath(FileName));
if (OriImg.Width > MaxW)
{
MaxH = Convert.ToInt32(OriImg.Height*MaxW)/OriImg.Width;
}
else
{
if (OriImg.Height > MaxH)
{
MaxW = Convert.ToInt32(OriImg.Width*MaxW)/OriImg.Height;
}
else
{
MaxW = OriImg.Width;
MaxH = OriImg.Height;
}
}
Image thumbnail = new Bitmap(MaxW, MaxH, OriImg.PixelFormat);
Graphics graphic = Graphics.FromImage(thumbnail);
var Params = new EncoderParameters(1);
Params.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
graphic.InterpolationMode = InterpolationMode.HighQualityBilinear;
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.CompositingQuality = CompositingQuality.HighQuality;
graphic.DrawImage(OriImg, 0, 0, MaxW, MaxH);
var MS = new MemoryStream();
thumbnail.Save(MS, ImageFormat.Png);
byte[] MsAr = MS.ToArray();
Response.ContentType = "image/Png";
Response.BinaryWrite(MsAr);
if (MS != null)
{
MS.Close();
MS.Dispose();
}
if (OriImg != null)
{
OriImg.Dispose();
OriImg = null;
}
4 - Para uso:
<asp:Image ID="Image1" runat="server" ImageUrl="~/thumbnails.aspx?img=suaImagem.jpg&MaxW=200&MaxH=200" />