我有一个场景,我使用 System.Drawing 通过将原始图像的大小调整为提供的大小(正在使用的大小)来生成缩略图。如果源图像是矩形,则生成的缩略图需要是方形的,而不会破坏图像(拉伸它)。到目前为止,我有以下代码:
//Obtain original image from input stream
using (var sourceImage = new Bitmap(Image.FromStream(inStream)))
{
//Setting thumbnail aspect ratio based on source image
int destWidth, destHeight;
if (sourceImage.Width > sourceImage.Height)
{
destWidth = providedSize;
destHeight = Convert.ToInt32(sourceImage.Height * providedSize/ (double)sourceImage.Width);
}
else
{
destWidth = Convert.ToInt32(sourceImage.Width * providedSize/ (double)sourceImage.Height);
destHeight = providedSize;
}
//Initialize thumbnail bitmap
var thumbnail = new Bitmap(destWidth, destHeight);
//Create thumbnail
using (var graphics = Graphics.FromImage(thumbnail))
{
graphics.CompositingQuality = CompositingQuality.HighSpeed;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.DrawImage(sourceImage, 0, 0, destWidth, destHeight);
using (MemoryStream stream = new MemoryStream())
{
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, Convert.ToInt64(Environment.GetEnvironmentVariable("ThumbnailQuality")));
var codecInfo = ImageCodecInfo.GetImageDecoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
thumbnail.Save(stream, codecInfo, encoderParameters);
stream.Position = 0;
//Upload thumbnail
}
}
}