Question :
I have an array of bytes in base64 that is in a String in C #. It represents an image. The size of the String is between 50 and 80 thousand characters. I would like to know if you can reduce this size, compressing and removing the quality of the image.
HttpPost method that receives the byte array:
[HttpPost]
public void Post([FromBody]CreateViewModel model)
{
if (String.IsNullOrEmpty(model.PhotoFile))
{
Console.WriteLine("Foto não foi selecionada");
throw new Exception("Foto não foi selecionada");
}
_professionalApp.CreateProfessional(model);
}
I would like to have a method that decreases the size of the PhotoFile – CreateViewModel String attribute.
Answer :
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 50×30 (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.