What you want is a backend service that is responsible for resizing images without storing them. Here are some snippets of code that can help you:
- Create a page where you get the parameters
Url
, width
and height
.
-
Validate 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 reported dimensions. If one of the parameters is missing, use the corresponding dimension 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 resized content to the client:
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;
}
Here are the results of my test implementation:
Original Image:
link
Page call:
link
64x64 version:
Version64x128:
32x32 Version: