62,072
社区成员
发帖
与我相关
我的任务
分享
//修改后的缩略图方法
public string MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string type)
{
string errMsg = "";
try
{
using (Image originalImage = Image.FromFile(originalImagePath))
{
try
{
//新加,修正竖拍照片
RotateImage(originalImage);
int ow = originalImage.Width;
int oh = originalImage.Height;
int towidth = width;
int toheight = height;
if (type == "normal") //水印图
{
//宽<高,竖图
if (ow < oh)
{
towidth = 1024;
decimal wh = (decimal)oh / ow; //宽高比
toheight = (int)(wh * towidth);
}
}
if (type == "thumbnail")
{
//宽<高,竖图
if (ow < oh)
{
width = 160;
height = 220;
towidth = 160;
toheight = 220;
}
}
int x = 0;
int y = 0;
//新建一个bmp图片
using (Image bitmap = new System.Drawing.Bitmap(towidth, toheight))
{
//新建一个画板
Graphics g = System.Drawing.Graphics.FromImage(bitmap);
//设置高质量插值法
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
//设置高质量,低速度呈现平滑程度
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//清空画布并以透明背景色填充
g.Clear(Color.Transparent);
//在指定位置并且按指定大小绘制原图片的指定部分
g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
new Rectangle(x, y, ow, oh),
GraphicsUnit.Pixel);
try
{
//以jpg格式保存缩略图
if (!Directory.Exists(thumbnailPath))
{
Directory.CreateDirectory(thumbnailPath);
}
if (type == "thumbnail")
{
bitmap.Save(thumbnailPath + Path.GetFileName(originalImagePath), System.Drawing.Imaging.ImageFormat.Jpeg);
}
//如果是普通大小,要添加水印
if (type == "normal")
{
g.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height);
using (Font f = new Font("宋体", 15))
{
using (Brush b = new SolidBrush(Color.White))
{
SizeF ef = g.MeasureString(_WatermarkText, f);
int num = (int)(toheight * 0.05);
float xt = (towidth - (ef.Width / 2f)) - 10f;
float yt = (toheight - num) - (ef.Height / 2f);
StringFormat format = new StringFormat { Alignment = StringAlignment.Center };
g.DrawString(_WatermarkText, f, b, new PointF(xt, yt), format);
_WatermarkFile = ow < oh ? _WatermarkFile.Replace("1.0", "1.1") : _WatermarkFile;
Image _WaterImage = Image.FromFile(_WatermarkFile);
if (_WaterImage != null)
{
ImageAttributes imageAttr = new ImageAttributes();
towidth = (towidth - _WaterImage.Width) - 10;
toheight = (toheight - _WaterImage.Height) - 10;
g.DrawImage(_WaterImage, new Rectangle(towidth, toheight, _WaterImage.Width, _WaterImage.Height), 0, 0, _WaterImage.Width, _WaterImage.Height, GraphicsUnit.Pixel, imageAttr);
}
}
}
//以jpg格式保存缩略图
bitmap.Save(thumbnailPath + Path.GetFileName(originalImagePath), System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
catch (Exception e)
{
errMsg = GetInnerException(e) ;
}
finally
{
bitmap.Dispose();
g.Dispose();
}
}
}
catch (Exception ex)
{
errMsg = GetInnerException(e) ;
}
finally
{
originalImage.Dispose();
}
}
}
catch (Exception ex)
{
errMsg = GetInnerException(e) ;
}
return errMsg;
}
FileInfo fi=new FileInfo(path);
if(fi.Length>0){}