我正在使用 .NET(4.5) MVC(4.0) C#(5.0) 开发应用程序。我想从我已经拥有的图像中生成图像缩略图。现在的要求就像它应该从图像中心生成最大正方形部分的缩略图,而不拉伸不是整个图像,除非图像是正方形大小。
例如,我的原始图像尺寸:578x700 我想为占位符尺寸生成缩略图:200x150、185x138、140x140、89x66、80x80、45x45、28x28
我已经创建了下面的代码,但没有得到确切的结果。这是我生成缩略图的核心方法
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
{
}
}