|
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace SilverlightApplication1.Web
{
public partial class resize : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) return;
string fileName = Request["hdnFileName"];
string strFactor = Request["hdnFactor"];
string imgData = Request["hdnImgData"];
string extension = ".jpg";
string[] parts = fileName.Split(new char[] {'.'});
if (parts.Length > 1)
{
extension = parts[parts.Length - 1];
}
ImageFormat imageFormat = ImageFormat.Jpeg;
switch (extension)
{
case "jpg":
case "jpeg":
imageFormat = ImageFormat.Jpeg;
break;
case "png":
imageFormat = ImageFormat.Png;
break;
case "gif":
imageFormat = ImageFormat.Gif;
break;
case "bmp":
imageFormat = ImageFormat.Bmp;
break;
case "tiff":
imageFormat = ImageFormat.Tiff;
break;
}
double factor = 0;
if (!Double.TryParse(strFactor, out factor))
{
throw new ArgumentException("Invalid factor (should be of type Double)");
}
byte[] buffer = Convert.FromBase64String(imgData);
Image img = null;
using (MemoryStream stream = new MemoryStream())
{
stream.Write(buffer, 0, buffer.Length);
img = Image.FromStream(stream);
}
int originalWidth = img.Width;
int originalHeight = img.Height;
int width = Convert.ToInt32(factor * originalWidth);
int height = Convert.ToInt32(factor * originalHeight);
// see e.g. http://www.glennjones.net/Post/799/Highqualitydynamicallyresizedimageswithnet.htm
Bitmap newImage = new Bitmap(width, height, img.PixelFormat);
Graphics g = Graphics.FromImage(newImage);
g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
System.Drawing.Rectangle rect = new Rectangle(0, 0, width, height);
g.DrawImage(img, rect);
// newImage now contains the resized image
using (MemoryStream ms = new MemoryStream())
{
newImage.Save(ms, imageFormat);
ms.Seek(0, SeekOrigin.Begin);
int length = (int)ms.Length;
buffer = new byte[length];
ms.Read(buffer, 0, length);
}
Response.Clear();
Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", fileName));
Response.AddHeader("Content-Length", buffer.Length.ToString());
Response.ContentType = String.Format("image/{0}", imageFormat.ToString());
Response.BinaryWrite(buffer);
Response.End();
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Marc Schluper studied Applied Mathematics at Technical University Eindhoven, The Netherlands.
His employer is Kronos Hiring Solutions in Beaverton, OR.
He is married and has two children.