当前位置:
首页 > Python基础教程 >
-
C#教程之(2)
"]) ? 0 : int.Parse(context.Request.Params["h"]);//截图的高度
int maxWidth = string.IsNullOrEmpty(context.Request.Params["maxWidth"]) ? 0 : int.Parse(context.Request.Params["maxWidth"]);//最大宽
int maxHeight = string.IsNullOrEmpty(context.Request.Params["maxHeight"]) ? 0 : int.Parse(context.Request.Params["maxHeight"]);//最大高
string fileExt = Path.GetExtension(src);//图片格式
string fileName = Guid.NewGuid().ToString("N") + fileExt;
string savePath = "/uploadfiles/test/" + DateTime.Now.ToString("yyyyMM") + "/" + fileName;
CutImage(GetReducedImage(file, maxHeight, maxHeight), x, y, w, h, savePath, context);
return "{\"code\":0,\"src\":\"" + savePath + "\"}";
}
/// <summary>
/// 生成缩略图重载方法1,返回缩略图的Image对象
/// </summary>
/// <param name="Width">缩略图的宽度</param>
/// <param name="Height">缩略图的高度</param>
/// <returns>缩略图的Image对象</returns>
public Bitmap GetReducedImage(Image ResourceImage, int Width, int Height)
{
try
{
//用指定的大小和格式初始化Bitmap类的新实例
Bitmap bitmap = new Bitmap(Width, Height, PixelFormat.Format32bppArgb);
//从指定的Image对象创建新Graphics对象
Graphics graphics = Graphics.FromImage(bitmap);
//清除整个绘图面并以透明背景色填充
graphics.Clear(Color.Transparent);
//在指定位置并且按指定大小绘制原图片对象
graphics.DrawImage(ResourceImage, new Rectangle(0, 0, Width, Height));
return bitmap;
}
catch (Exception e)
{
return null;
}
}
/// <summary>
/// 截取图片方法
/// </summary>
/// <param name="bitmap">原图</param>
/// <param name="beginX">开始位置-X</param>
/// <param name="beginY">开始位置-Y</param>
/// <param name="width">截取宽度</param>
/// <param name="height">截取长度</param>
/// <param name="path">保存路径</param>
/// <param name="context">上下文</param>
public static void CutImage(Bitmap bitmap, int beginX, int beginY, int width, int height, string path, HttpContext context)
{
if (beginX + width > bitmap.Width)
beginX = bitmap.Width - width;
if (beginY + height > bitmap.Height)
beginY = bitmap.Height - height;
Bitmap destBitmap = new Bitmap(width, height);//目标图
Rectangle destRect = new Rectangle(0, 0, width, height);//矩形容器
Rectangle srcRect = new Rectangle(beginX, beginY, width, height);
Graphics g = Graphics.FromImage(destBitmap);
g.DrawImage(bitmap, destRect, srcRect, GraphicsUnit.Pixel);
destBitmap.Save(context.Server.MapPath(path), ImageFormat.Jpeg);
}