I have situations where a user’s avatar is stored in the bank at high quality, but sometimes to render a thumbnail very small (and as I don’t have a reduced version of the saved image anywhere) I return that same image, but with a small size (not to waste unnecessary server and client bandwidth). For 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();
}
}
}
Then you could use it that way:
model.PhotoFile = model.PhotoFile.ReduzTamanhoDaImagem(50, 30, Drawing.Imaging.ImageFormat.Png);
...which would reduce the image resolution to 50x30 (in this particular method, if the image already has the width/height smaller than the one passed by parameter, it will keep the original size).
I am not an expert in image manipulation, but I understand that the fact of reducing the resolution does not cause loss of image quality, however when trying to resize it to the original size (which would be larger), there can occur the loss of quality.
There are some techniques to do this, but it would be too broad to answer. Depending on what you want, you don’t need to do this. Anyway I would need much more information about the situation.
– Maniero
I put an example above.
– Ricardo Mendes
It didn’t help much. The best thing is not to treat it like Base64 that wastes a lot. This is what you want?
– Maniero
How could I save the image ? What I want is to save without spending too much space, because as I said the byte string has between 50 and 80 thousand characters.
– Ricardo Mendes
I’d love to give you a full answer right now, but I’m too exhausted from the job right now, so I’m just going to leave a link here where Microsoft documents how to compress things: https://msdn.microsoft.com/pt-br/library/ms404280(v=vs.110). aspx if anyone wants to elaborate this in a full reply will have my vote.
– Oralista de Sistemas
base 64 in this case only serves to spend more space yet.
– Bacco
So how could I keep the image ?
– Ricardo Mendes
Why don’t you save the image as binary even instead of saving as Base64? Using System.Drawing.* load the image, convert it to JPEG and decrease the quality to the maximum, and then save the binary file (image.jpg), if this is not enough to store, use some compression algorithm like: ZIP/RAR/GZIP
– Guilherme Branco Stracini