这是 C# 函数,您可以使用它以任何您想要的方式调整图像大小。在您的特定情况下,使其具有一定大小的缩略图。它需要System.Drawing.Image
, 和 aint size
来使其宽度成为并返回System.Drawing.Image
。现在,这个肯定有效,我在我当前的项目中使用它,它很好地完成了这项工作。
public System.Drawing.Image ScaleBySize(System.Drawing.Image imgPhoto, int size)
{
var logoSize = size;
float sourceWidth = imgPhoto.Width;
float sourceHeight = imgPhoto.Height;
float destHeight;
float destWidth;
const int sourceX = 0;
const int sourceY = 0;
const int destX = 0;
const int destY = 0;
// Resize Image to have the height = logoSize/2 or width = logoSize.
// Height is greater than width, set Height = logoSize and resize width accordingly
if (sourceWidth > (2 * sourceHeight))
{
destWidth = logoSize;
destHeight = sourceHeight * logoSize / sourceWidth;
}
else
{
int h = logoSize / 2;
destHeight = h;
destWidth = sourceWidth * h / sourceHeight;
}
// Width is greater than height, set Width = logoSize and resize height accordingly
var bmPhoto = new Bitmap((int)destWidth, (int)destHeight, PixelFormat.Format32bppPArgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
using (Graphics grPhoto = Graphics.FromImage(bmPhoto))
{
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, (int)destWidth, (int)destHeight),
new Rectangle(sourceX, sourceY, (int)sourceWidth, (int)sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
}
return bmPhoto;
}
希望这会对你有所帮助。