This is the code I cam up with to generate square thumbnail in C#
I havent’t code this type of thing before.
Since this code will be used heavily, I am checking with you before I put this in production.
Do you see anything bad or can be improved further?
Basically I have a set of thumbnails sitting in some folder.
Those thumbnails are not square and I need to make all of them square.
This will be called in a loop for each file in the folder.
This is how I call it:
SaveSquareThumb(75, "C:\storage\images\temp\thumbs", "C:\storage\images\thumbs");
public static void SaveSquareThumb(int squareSize, string sourcePath, string savePath)
{
using (Bitmap srcImage = new Bitmap(sourcePath))
{
int width = srcImage.Width;
int height = srcImage.Height;
int x = 0;
int y = 0;
//Determine dimensions of resized version of the image
if (width > height)
{
width = (int)Decimal.Round(Convert.ToDecimal((decimal)squareSize * ((decimal)width / (decimal)height)), 0);
height = squareSize;
// moves cursor so that crop is more centered
x = Convert.ToInt32(Math.Ceiling(((decimal)(width - height) / 2M)));
}
else if (height > width)
{
height = (int)Decimal.Round(Convert.ToDecimal((decimal)squareSize * ((decimal)height / (decimal)width)), 0);
width = squareSize;
// moves cursor so that crop is more centered
y = Convert.ToInt32(Math.Ceiling(((decimal)(height - width) / 2M)));
}
else
{
width = squareSize;
height = squareSize;
}
// required in case thumbnail creation fails?
Image.GetThumbnailImageAbort dummyCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
ImageCodecInfo codecInfo = GetEncoderInfo("image/jpeg");
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
//get thumbnail from source image
using (Image thumb = srcImage.GetThumbnailImage(width, height, null, System.IntPtr.Zero))
{
//Create a Crop Frame to apply to the Resized Image
using (Bitmap myBitmapCropped = new Bitmap(squareSize, squareSize))
{
using (Graphics myGraphic = Graphics.FromImage(myBitmapCropped))
{
//Apply the Crop to the Resized Image
myGraphic.DrawImage(thumb, new Rectangle(0, 0, width, height), x, y, width, height, GraphicsUnit.Pixel);
//Save the Croped and Resized image as a new square thumnail
myBitmapCropped.Save(savePath, codecInfo, encoderParams);
}
}
}
}
}
First two items are most important, third and fourth are all about code readability:
((decimal)squareSize),((decimal)width)consider single cast and store it in the new method level variableswidthandheightto be equals tosquareSizeand then remove following code block: