private static string CreateThumbnail(string filepath, int tWidth, int tHeight)
{
if (string.IsNullOrEmpty(filepath))
{
return "";
}
string paramOriginalDirectory = "thumbnail";
string oldfilepath = filepath;
//string originalImagePath = HttpContext.Current.Server.MapPath(filepath);//全路径(即绝对路径)
string originalImagePath = filepath;//全路径(即绝对路径)
//originalImagePath = ApiToWeb(originalImagePath);
string filename = System.IO.Path.GetFileName(originalImagePath);
string oldthumbnailImagePath = oldfilepath.Replace(filename, "") + paramOriginalDirectory + "/" + filename;
string thumbnailPath = originalImagePath.Replace(filename, "") + paramOriginalDirectory;
string thumbnailImagePath = originalImagePath.Replace(filename, "") + paramOriginalDirectory + "/" + filename;
if (!Directory.Exists(thumbnailPath))
{
Directory.CreateDirectory(thumbnailPath);
}
if (!File.Exists(originalImagePath))
{
return oldthumbnailImagePath;
}
if (File.Exists(thumbnailImagePath))
{
return oldthumbnailImagePath;
}
try
{
FileStream fileStream = File.OpenRead(originalImagePath);
Int32 filelength = 0;
filelength = (int)fileStream.Length;
Byte[] image = new Byte[filelength];
fileStream.Read(image, 0, filelength);
System.Drawing.Image oImage = System.Drawing.Image.FromStream(fileStream);
fileStream.Close();
int oWidth = oImage.Width;//原图宽度
int oHeight = oImage.Height;//原图高度
if (tWidth == 0)
{
tWidth = 100;
}
if (tHeight == 0)
{
tHeight = 100;
}
//按比例计算出缩略图的宽度和高度
if (oWidth >= oHeight)
{
tHeight = (int)Math.Floor(Convert.ToDouble(oHeight) * (Convert.ToDouble(tWidth) / Convert.ToDouble(oHeight)));
}
else
{
tWidth = (int)Math.Floor(Convert.ToDouble(oWidth) * (Convert.ToDouble(tHeight) / Convert.ToDouble(oHeight)));
}
//生成缩略图
Bitmap tImage = new Bitmap(tWidth, tHeight);
Graphics g = Graphics.FromImage(tImage);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;//设置高质量插值法
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;//设置高质量,低速度呈现平滑程度
g.Clear(Color.Transparent);//清空画布并以透明背景色填充
g.DrawImage(oImage, new Rectangle(0, 0, tWidth, tHeight), new Rectangle(0, 0, oWidth, oHeight), GraphicsUnit.Pixel);
//string oPath = originalImagePath + "\\" + filename + ".jpg";
//string thumbnailImagePath = thumbnailPath + "\\" + filename + ".jpg";
tImage.Save(thumbnailImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
//释放资源
oImage.Dispose();
g.Dispose();
tImage.Dispose();
return oldthumbnailImagePath;
}
catch (Exception ex)
{
return ex.Message + ex.StackTrace;
}
}