头像剪切后图片上传

前言

在此只介绍后台,用ashx 举例:前端

前端咱们要作的事情,就是将图片从哪一个位置截取,也就是位置x和y。数据库

而后截取的宽和高,width 和 height。ui

如今咱们知道的就是须要四个数据x、y、width、height。code

代码

int x = Convert.ToInt32(context.Request["x"]);
int y = Convert.ToInt32(context.Request["y"]);
int height = Convert.ToInt32(context.Request["height"]);
int width = Convert.ToInt32(context.Request["width"]);
string imageUrl = context.Request["imageUrl"];
using (Bitmap map=new Bitmap(width,height))
{
	using (Graphics g = Graphics.FromImage(map))
	{                   
		using (Image img = Image.FromFile(context.Request.MapPath(imageUrl)))
		{
			g.DrawImage(img,new Rectangle(0,0,width,height),new Rectangle(x,y,width,height),GraphicsUnit.Pixel);
			string fileNewName = Guid.NewGuid().ToString();
			string dir = "/ashx/UPLoad/Image/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/";
			string fulldir = dir + fileNewName + ".jpg";
			map.Save(context.Request.MapPath(fulldir),System.Drawing.Imaging.ImageFormat.Jpeg);
			//处理数据库回调。。。
		} 
	}
}

当年写的代码,见谅。orm

分析一下,当咱们获得了x、y、height、width。对象

而后咱们建立了bitmap,而后建立了graphics 画布,而后开始切割了。图片

g.DrawImage 就开始直接在画布上画图了。string

解释一下参数的意思:it

第一个参数image是图片源。

第二个参数:

destRect
    Rectangle
Rectangle 结构,它指定所绘制图像的位置和大小。 将图像进行缩放以适合该矩形。

第三个参数:

srcRect
    Rectangle

Rectangle 结构,它指定 image 对象中要绘制的部分。

第四个是以什么来计算,通常来讲是以像素来计算的。

而后呢,若是看完是能够发现上面的代码发现有问题的。后台

问题在于切割的后其实咱们应该保持相同大小的,而咱们的头像通常要是正方形。

固然只是业务问题,只是介绍大概思路。