0
I have this code that creates me thumbnails
for my project:
//**** INICIO GUARDA THUMB **********
// valores para altura e largura do thumb:
int resizeToWidth = 260; //px
int resizeToHeight = 260; //px
//busca-se a main image
Image thumb = Image.FromFile(saveFilePath, false);
//transforma-se a imagem para o tamanho pretendido
Bitmap bmp = new Bitmap(resizeToWidth, resizeToHeight);
Graphics graphic = Graphics.FromImage(bmp);
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.CompositingQuality = CompositingQuality.HighQuality;
graphic.DrawImage(thumb, 0, 0, resizeToWidth, resizeToHeight);
//Aqui já temos uma Image que é um thumbnail
Image imageToSave = bmp;
//caminho fisico onde guarda-se o thumb
string thumbPath = Server.MapPath("~/thumbnails");
//caminho dentro do projeto onde guardam-se as thumbs
imageToSave.Save(thumbPath + "\\" + imgGuid + extension);
//****** FIM GUARDA THUMB ***********
The imgGuid
is a variable with the name of the image. The problem with this code is that if the image is very different from a square, it is all disfigured.
How can I use the C#
to improve the algorithm and cut the excesses instead of shrinking them?
EDIT: Before using the answer I was given, I used this code to reduce the image size first, before cutting it:
if (thumb.Size.Height > thumb.Size.Width || thumb.Size.Height == thumb.Size.Width)
{
thumb = ResizeImage(sourceImage, resizeToWidth, thumb.Size.Height);
}
else
{
thumb = ResizeImage(sourceImage, thumb.Size.Width, resizeToHeight);
}
public static Image ResizeImage(Image sourceImage, int maxWidth, int maxHeight)
{
//Calculam-se as dimensões novas para a imagem
var ratioX = (double)maxWidth / sourceImage.Width;
var ratioY = (double)maxHeight / sourceImage.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(sourceImage.Width * ratio);
var newHeight = (int)(sourceImage.Height * ratio);
//Cria-se um bitmap com as dimensões otimizadas
var newImage = new Bitmap(newWidth, newHeight);
//Desenha-se a imagem no bitmap
using (var grafico = Graphics.FromImage(newImage))
{
grafico.InterpolationMode = InterpolationMode.HighQualityBicubic;
grafico.SmoothingMode = SmoothingMode.HighQuality;
grafico.PixelOffsetMode = PixelOffsetMode.HighQuality;
grafico.CompositingQuality = CompositingQuality.HighQuality;
grafico.DrawImage(sourceImage, 0, 0, newWidth, newHeight);
};
return newImage;
}
related: How to resize image independent of size?
– novic