I have situations where a user's avatar is stored in the bank in high quality , but sometimes to render a thumbnail very small (and since I do not have one Reduced version of the saved image anywhere) I return this same image, but with a reduced size (not to spend unnecessary server and client bandwidth). To do this, I use this extension method (only for images):
public static byte[] ReduzTamanhoDaImagem(this byte[] imageData, int width, int height, Drawing.Imaging.ImageFormat type)
{
if (imageData == null)
return null;
if (imageData.Length == 0)
return imageData;
using (MemoryStream myMemStream = new MemoryStream(imageData))
{
Drawing.Image fullsizeImage = Drawing.Image.FromStream(myMemStream);
if (width <= 0 || width > fullsizeImage.Width)
width = fullsizeImage.Width;
if (height <= 0 || height > fullsizeImage.Height)
height = fullsizeImage.Height;
Drawing.Image newImage = fullsizeImage.GetThumbnailImage(width, height, null, IntPtr.Zero);
using (MemoryStream myResult = new MemoryStream())
{
newImage.Save(myResult, type);
return myResult.ToArray();
}
}
}
So you could use it this way:
model.PhotoFile = model.PhotoFile.ReduzTamanhoDaImagem(50, 30, Drawing.Imaging.ImageFormat.Png);
... which would reduce the resolution of the image to 50x30 (in this particular method, if the image already has the width / height smaller than the one passed per parameter, it will keep the size original).
I'm not an expert in image manipulation, but I understand that reducing the resolution does not cause a loss of image quality, but when you try to resize it to its original size, loss of quality occurs.