</pre><pre name="code" class="csharp">-----前端html
<script type="text/javascript" src="@Url.Content("~/scripts/jquery-1.7.1.min.js")"></script>
<link rel="stylesheet" type="text/css" href="@Url.Content("~/contentpc/css/imgareaselect-default.css")"/>
<div class="popup" id="cutDiv">
@using (Html.BeginForm("avgupload", "user", FormMethod.Post, new { id = "form2" }))
{
<dl>
<dt>头像截取<a href="###" class="btn_close transition_a" id="Cut_close">关闭</a></dt>
<div style="background-color: #f6f6f6">
<dd>
<div class="l_560" style="width: 600px;">
<div style="float: left; min-width: 400px; text-align: center">
<div style="font-size: 16px; color: #888; text-align: center">
鼠标划拉图片选择区域↖↘</div>
<img alt="" id="oldAvg" width="360" height="360" src="@(string.IsNullOrEmpty(Model.Avg) ? Url.Content("~/contentpc/images/tool/photo_80.png") : Url.Content("~/content/accessory/" + Model.Avg))"/>
</div>
<div style="float: right;">
<div style="font-size: 16px; color: #888; text-align: center">
预览</div>
<div id="preview" style="width: 180px; height: 180px; overflow: hidden;">
<img src="@(string.IsNullOrEmpty(Model.Avg) ? Url.Content("~/contentpc/images/tool/photo_80.png") : Url.Content("~/content/accessory/" + Model.Avg))" >
</div>
<span style="text-align: center">尺寸:180 x 180</span>
<input type="hidden" name="x1" id="x1" value="0" />
<input type="hidden" name="y1" id="y1" value="0" />
<input type="hidden" name="x2" id="x2" value="180" />
<input type="hidden" name="y2" id="y2" value="180" />
</div>
</div>
<br />
<input type="submit" value="保存" class="blue_btn transition_a round_s" style="width: 100px;
padding: 0.5em 0 0 0" />
</dd>
</div>
</dl>
}
</div>
------------前端脚本
<script>
$(document).ready(function () {
$('#oldAvg').imgAreaSelect({
aspectRatio: '1:1',
fadeSpeed: 1200,
autoHide: true,
show: false,
handles: false,
onSelectChange: preview
});
function preview(img, selection) {
if (!selection.width || !selection.height)
return;
$('input[name="x1"]').val(selection.x1);
$('input[name="y1"]').val(selection.y1);
$('input[name="x2"]').val(selection.x2);
$('input[name="y2"]').val(selection.y2);
var scaleX = 180 / selection.width;
var scaleY = 180 / selection.height;
$('#preview img').css({
width: Math.round(scaleX * 360),
height: Math.round(scaleY * 360),
marginLeft: -Math.round(scaleX * selection.x1),
marginTop: -Math.round(scaleY * selection.y1)
});
}
</script>
------------服务器端
[HttpPost]
public ActionResult AvgUpload()
{
TUser model = System.Web.HttpContext.Current.Session["LoginUser"] as TUser;
TUser user = TUserRepository.GetById(model.ID);
try
{
int x1 = Convert.ToInt32(Request["x1"]);
int y1 = Convert.ToInt32(Request["y1"]);
int x2 = Convert.ToInt32(Request["x2"]);
int y2 = Convert.ToInt32(Request["y2"]);
int width = x2 - x1;
int height = y2 - y1;
string SavePath = System.Web.HttpContext.Current.Server.MapPath("~/Content/accessory/");//获取图片存放路径
string oldAvgPath = SavePath + user.Avg;//获取原头像图片
string Thumbnail = Guid.NewGuid().ToString("N") + Path.GetExtension(user.Avg);
string ThumbnailPath = SavePath + Thumbnail;
string newAvg = Guid.NewGuid().ToString("N") + Path.GetExtension(user.Avg);//生成新的图片
string newAvgPath = SavePath + newAvg;
if (!string.IsNullOrEmpty(user.Avg))
{
//-------------------------------------------------------------------原始图片
System.Drawing.Image avgImage = Image.FromFile(oldAvgPath);
//System.Drawing.Image ChangeImage = sourceImage.GetThumbnailImage(360, 360, () => { return false; }, System.IntPtr.Zero);
int AvgWidth = avgImage.Width;
int AvgHeight = avgImage.Height;
//生成缩略图
SaveThumbnail(avgImage, 360, 360, ThumbnailPath, user.Avg, Path.GetExtension(user.Avg), AvgWidth, AvgHeight);
System.Drawing.Image sourceImage = Image.FromFile(ThumbnailPath);
//-------------------------------------------------------------------裁剪的区域
Rectangle fromR = new Rectangle(x1, y1, width, height);
//-------------------------------------------------------------------裁剪出来的图要放在画布的哪个位置
Rectangle toR = new Rectangle(0, 0, width, height);
//-------------------------------------------------------------------要当画布的Bitmap物件
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height);
//-------------------------------------------------------------------产生画布
System.Drawing.Graphics g = Graphics.FromImage(bitmap);
//-------------------------------------------------------------------清空画布,背景白色
g.Clear(Color.White);
//-------------------------------------------------------------------剪裁
g.DrawImage(sourceImage, toR, fromR, GraphicsUnit.Pixel);
//裁剪完成,存盘
bitmap.Save(newAvgPath, ImageFormat.Jpeg);
//释放资源
g.Dispose();
bitmap.Dispose();
sourceImage.Dispose();
avgImage.Dispose();
//ChangeImage.Dispose();
}
user.Avg = newAvg;
TUserRepository.Update(user);
unitOfWork.Commit();
System.IO.File.Delete(oldAvgPath);//把原始档删除
System.IO.File.Delete(ThumbnailPath);//把原始档删除
return RedirectToAction("avgindex", "user");
}
catch
{
return Content("<script>alert('系统出错,请重试!');window.location.href='/user/avgindex'</script>");
}
}
private void SaveThumbnail(Image originBitmap, int Imgwidth, int Imgheight, string physicalPath, string filename, string extension, int initWidth, int initHeight)
{
using (var newImage = new Bitmap(Imgwidth, Imgheight))
{
using (var graphic = GetGraphic(originBitmap, newImage))
{
graphic.DrawImage(originBitmap, new Rectangle(0, 0, 360, 360), new Rectangle(0, 0, initWidth, initHeight), GraphicsUnit.Pixel);
using (var encoderParameters = new EncoderParameters(1))
{
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
newImage.Save(physicalPath,
ImageCodecInfo.GetImageEncoders()
.Where(x => x.FilenameExtension.Contains(extension.ToUpperInvariant()))
.FirstOrDefault(),
encoderParameters);
}
}
}
}
private Graphics GetGraphic(Image originImage, Bitmap newImage)
{
newImage.SetResolution(originImage.HorizontalResolution, originImage.VerticalResolution);
var graphic = Graphics.FromImage(newImage);
graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphic.Clear(Color.White);
return graphic;
}
C#结合imgareaselect生成缩略图并截取图片
最新推荐文章于 2024-04-19 17:24:11 发布