// Make a thumbnail of the input image. newWidth and newHeight are both limits; the image will not
// be larger than original, but if necessary will be shrunk to fit within the indicated rectangle.
// If parameter 'backColor' is not Empty, we fill the background of the thumbnail with that color.
public static bool GenerateThumbnail(string originalPath, string pathToProcessedImage, int newWidth, Color backColor)
{
using (var originalImage = PalasoImage.FromFileRobustly(originalPath))
{
// check if it needs resized
if (originalImage.Image.Width <= newWidth)
{
return(false);
}
// calculate dimensions
var newW = (originalImage.Image.Width > newWidth) ? newWidth : originalImage.Image.Width;
// allow for proper rounding from the division
var newH = (newW * originalImage.Image.Height + (originalImage.Image.Width / 2)) / originalImage.Image.Width;
var thumbnail = new Bitmap(newW, newH);
var g = Graphics.FromImage(thumbnail);
if (backColor != Color.Empty)
{
using (var brush = new SolidBrush(backColor))
{
g.FillRectangle(brush, new Rectangle(0, 0, newW, newH));
}
}
Image imageToDraw = originalImage.Image;
bool useOriginalImage = ImageUtils.AppearsToBeJpeg(originalImage);
if (!useOriginalImage)
{
imageToDraw = MakePngBackgroundTransparent(originalImage);
}
var destRect = new Rectangle(0, 0, newW, newH);
// Note the image size may change when the background is made transparent.
// See https://silbloom.myjetbrains.com/youtrack/issue/BL-5632.
g.DrawImage(imageToDraw, destRect, new Rectangle(0, 0, imageToDraw.Width, imageToDraw.Height), GraphicsUnit.Pixel);
if (!useOriginalImage)
{
imageToDraw.Dispose();
}
RobustImageIO.SaveImage(thumbnail, pathToProcessedImage);
}
return(true);
}