源码:(aspx文件测试)
注意文件路径
源码:
protected void Page_Load(object sender, EventArgs e)
{
string path = Server.MapPath("images/57logosmall1.png");
if (CutImage(path))
{
Response.Write("切图成功");
}
else {
Response.Write("继续搞吧");
}
}
private bool CutImage(string path)
{
bool result = false;
System.Drawing.Image originalImage = System.Drawing.Image.FromFile(path);
int towidth = 100;//设置目标宽度
int toheight = originalImage.Height * towidth / originalImage.Width;//按比例设置目标高度
int x = 0;
int y = 0;
int ow = originalImage.Width;
int oh = originalImage.Height;
System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);//新建bmp图片
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);
//以jpg格式保存缩略图
DateTime date = DateTime.Now;
string smallname = date.ToLongDateString().ToString() +date.Hour.ToString()+"时"+date.Minute.ToString()+"分"+date.Second.ToString()+"秒"+ date.Millisecond;
string savepath = Server.MapPath("images/1/" + smallname + ".jpg");
try
{
bitmap.Save(savepath, System.Drawing.Imaging.ImageFormat.Jpeg);
result = true;
}
catch
{
result = false;
}
finally
{
originalImage.Dispose();
bitmap.Dispose();
g.Dispose();
}
return result;
}