What you want is a backend service that is responsible for resizing images, but not storing them. Here are some code snippets that can help you:
- Create a page where you receive the parameters
Url
, width
and height
.
Validate the content received:
string url = Request["Url"];
int? width = Request["width"];
int? height = Request["height"];
Uri uriResult;
var isUrl = Uri.TryCreate(url, UriKind.Absolute, out uriResult) &&
uriResult.Scheme == Uri.UriSchemeHttp;
If the URL is valid, download the content, and create an Image object:
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
using (var httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
using (var stream = httpWebReponse.GetResponseStream())
{
Image image = Image.FromStream(stream);
}
}
Validate the dimensions provided. If one of the parameters is missing, use the corresponding size of the original image:
if (width == null)
width = image.Width;
if (height == null)
height = image.Height;
Resize the image to the desired size (the Resizeimage function is at the end of this post):
image = ResizeImage(image, (int)width, (int)height);
Send the redeemed content to the customer:
using(MemoryStream ms = new MemoryStream())
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.WriteTo(context.Response.OutputStream);
}
Next, the image resizing function. It performs the equivalent of the CSS rule background-size: contain
:
public static Image ResizeImage(Image image, int width, int height)
{
var destRatio = ((float) width/height);
var srcRatio = ((float) image.Width/image.Height);
int intermediateWidth;
int intermediateHeight;
var widthOffSet = 0;
var heightOffSet = 0;
if (srcRatio <= destRatio)
{
intermediateWidth = width;
intermediateHeight = (int) (intermediateWidth/srcRatio);
heightOffSet = 0;
}
else
{
intermediateHeight = height;
intermediateWidth = (int) (intermediateHeight*srcRatio);
widthOffSet = (intermediateWidth - width)/2;
}
var bmPhoto = new Bitmap(intermediateWidth, intermediateHeight, PixelFormat.Format24bppRgb);
Graphics.FromImage(bmPhoto).DrawImage(image, 0, 0, intermediateWidth, intermediateHeight);
var outputImage = new Bitmap(width, height);
var section = new Rectangle(new Point(widthOffSet, heightOffSet), new Size(width, height));
var preoutputGrp = Graphics.FromImage(outputImage);
preoutputGrp.InterpolationMode = InterpolationMode.HighQualityBicubic;
preoutputGrp.DrawImage(bmPhoto, 0, 0, section, GraphicsUnit.Pixel);
preoutputGrp.Dispose();
bmPhoto.Dispose();
return outputImage;
}
These are the results of my test implementation:
Original image:
http://www.wired.com/wp-content/uploads/blogs/opinion/wp-content/uploads/2013/03/socialite.jpg
Page call:
http://localhost/teste.aspx? width=64&height=64&url=http://www.wired.com/wp-content/uploads/blogs/opinion/wp-content/uploads/2013/03/socialite.jpg
Version 64x64:
Version 64x128:
Version 32x32: