I am developing application using .NET(4.5) MVC(4.0) C#(5.0).
i want to generate image thumbnail from image that i already have.
Now requirement is like it should generate thumbnail of maximum square portion from center of image without stretching not whole image except image is square size.
as per example my original image size :578x700
i want to generate thumbnail for placeholder size :200x150, 185x138, 140x140, 89x66, 80x80, 45x45, 28x28
i had create my below code but didn't get exact result.
here is my core method that generate thumbnail
public string GenerateThumbnailFromImage(string imageFilePath, int thumbWidth, int thumbHeight)
{
try
{
//Check if file exist
if (File.Exists(imageFilePath))
{
//bool preserveAspectRatio = true;
string oldFilePath = imageFilePath;
string folderPath = Path.GetDirectoryName(imageFilePath);
string filename = Path.GetFileNameWithoutExtension(imageFilePath);
//Rename file with thumbnail size
filename = filename + "_" + thumbWidth.ToString() + Path.GetExtension(imageFilePath);
imageFilePath = Path.Combine(folderPath, filename);
using (Image image = Image.FromFile(oldFilePath))
{
decimal originalWidth = image.Width;
decimal originalHeight = image.Height;
decimal requiredThumbWidth = thumbWidth;
decimal requiredThumbHeight = thumbHeight;
decimal startXPosition = 0;
decimal startYPosition = 0;
decimal screenWidth = originalWidth;
decimal screenHeight = originalHeight;
decimal ar = thumbWidth < thumbHeight
? originalWidth / originalHeight
: originalHeight / originalWidth;
//Define Starting Position for thumbnail generation
if (originalWidth > originalHeight)
startXPosition = (originalWidth - originalHeight) / 2;
else if (originalHeight > originalWidth)
startYPosition = (originalHeight - originalWidth) / 2;
if (thumbWidth>thumbHeight)
{
requiredThumbWidth = thumbWidth;
requiredThumbHeight = requiredThumbWidth*ar;
}
else if (thumbHeight>thumbWidth)
{
requiredThumbHeight = thumbHeight;
requiredThumbWidth = requiredThumbHeight*ar;
}
else
{
requiredThumbWidth = thumbWidth;
requiredThumbHeight = thumbWidth;
}
using (var bmp = new Bitmap((int)requiredThumbWidth, (int)requiredThumbHeight))
{
Graphics gr = Graphics.FromImage(bmp);
gr.SmoothingMode = SmoothingMode.HighQuality;
gr.CompositingQuality = CompositingQuality.HighQuality;
gr.InterpolationMode = InterpolationMode.High;
var rectDestination = new Rectangle(0, 0, (int)requiredThumbWidth, (int)requiredThumbHeight);
gr.DrawImage(image, rectDestination, (int)startXPosition, (int)startYPosition, (int)screenWidth, (int)screenHeight, GraphicsUnit.Pixel);
bmp.Save(imageFilePath);
return filename;
}
}
}
return null;
}
catch (Exception ex)
{
GlobalUtil.HandleAndLogException(ex, this);
throw ex;
}
finally
{
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…