根据原图生成缩略图(C#)
/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="imgBuffer">原图byte[]</param>
/// <param name="width">生成的缩略图宽度</param>
/// <param name="height">生成的缩略图高度</param>
/// <returns></returns>
private byte[] GenerateThumbImg(byte[] imgBuffer,int width,int height)
{
MemoryStream imgStream = null;
MemoryStream thumbStream = new MemoryStream();;
System.Drawing.Image img = null;
System.Drawing.Image thumbImg = null;
System.Drawing.Graphics g = null;
try
{
imgStream = new MemoryStream(imgBuffer);
img = System.Drawing.Image.FromStream(imgStream);
thumbImg = new System.Drawing.Bitmap(img, width, height);
g = System.Drawing.Graphics.FromImage(thumbImg);
// 设置画布的描绘质量
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(thumbImg, 0, 0, width, height);
/*g.DrawImage(img, new System.Drawing.Rectangle(0, 0, width, height),
0, 0, width, height, System.Drawing.GraphicsUnit.Pixel);*/
thumbImg.Save(thumbStream, System.Drawing.Imaging.ImageFormat.Jpeg);
return thumbStream.ToArray();
}
catch(Exception ex)
{
return null;
}
finally
{
if (g != null)
g.Dispose();
if (thumbImg != null)
thumbImg.Dispose();
if (img != null)
img.Dispose();
if (thumbStream != null)
thumbStream.Close();
if (imgStream != null)
imgStream.Close();
}
}
/// 生成缩略图
/// </summary>
/// <param name="imgBuffer">原图byte[]</param>
/// <param name="width">生成的缩略图宽度</param>
/// <param name="height">生成的缩略图高度</param>
/// <returns></returns>
private byte[] GenerateThumbImg(byte[] imgBuffer,int width,int height)
{
MemoryStream imgStream = null;
MemoryStream thumbStream = new MemoryStream();;
System.Drawing.Image img = null;
System.Drawing.Image thumbImg = null;
System.Drawing.Graphics g = null;
try
{
imgStream = new MemoryStream(imgBuffer);
img = System.Drawing.Image.FromStream(imgStream);
thumbImg = new System.Drawing.Bitmap(img, width, height);
g = System.Drawing.Graphics.FromImage(thumbImg);
// 设置画布的描绘质量
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(thumbImg, 0, 0, width, height);
/*g.DrawImage(img, new System.Drawing.Rectangle(0, 0, width, height),
0, 0, width, height, System.Drawing.GraphicsUnit.Pixel);*/
thumbImg.Save(thumbStream, System.Drawing.Imaging.ImageFormat.Jpeg);
return thumbStream.ToArray();
}
catch(Exception ex)
{
return null;
}
finally
{
if (g != null)
g.Dispose();
if (thumbImg != null)
thumbImg.Dispose();
if (img != null)
img.Dispose();
if (thumbStream != null)
thumbStream.Close();
if (imgStream != null)
imgStream.Close();
}
}