jquery实现截取pc图片_使用JQuery插件Jcrop进行图片截取

[HttpPost]publicActionResult UploadPhoto()

{

HttpPostedFileBase file= Request.Files["UserPhoto"];string contentType =file.ContentType;string extension =Path.GetExtension(file.FileName);//检查图片格式

if (!IsAllowImg(contentType, extension))

{return Json(new { Status = "error", Msg = "上传文件格式不符合要求。"});

}//保存形成保存路径

TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);string newFileName = Convert.ToInt64(ts.TotalMilliseconds).ToString(CultureInfo.InvariantCulture) + new Random().Next(100, 999);string path = Server.MapPath("~/Upload/") + newFileName + ".jpeg";//压缩图片、转换格式(jpeg)

Image ResourceImage =Image.FromStream(file.InputStream);if(ResourceImage.Width>300)

{int dWidth = 300;int dHeight = 300 * ResourceImage.Height /ResourceImage.Width;

CompressPicture(file.InputStream, path, dWidth, dHeight,100);

}else{

CompressPicture(file.InputStream, path, ResourceImage.Width, ResourceImage.Height,100);

}

file.InputStream.Close();string url = Request.ApplicationPath + "Upload/" + newFileName + ".jpeg";return Json(new { Status = "success", Msg = "上传成功",ImgUrl=url });

}#region 压缩图像

///

///无损压缩图片///

/// 原图片

/// 压缩后保存位置

/// 宽度

/// 高度

/// 压缩质量 1-100

///

public bool CompressPicture(Stream inputStream, string dFile, int dWidth, int dHeight, intflag)

{

System.Drawing.Image iSource=System.Drawing.Image.FromStream(inputStream);

ImageFormat tFormat=iSource.RawFormat;int sW = 0, sH = 0;//按比例缩放

Size tem_size = newSize(iSource.Width, iSource.Height);if (tem_size.Width > dWidth || tem_size.Height >dHeight)

{if ((tem_size.Width * dHeight) > (tem_size.Height *dWidth))

{

sW=dWidth;

sH= (dWidth * tem_size.Height) /tem_size.Width;

}else{

sH=dHeight;

sW= (tem_size.Width * dHeight) /tem_size.Height;

}

}else{

sW=tem_size.Width;

sH=tem_size.Height;

}

Bitmap ob= newBitmap(dWidth, dHeight);

Graphics g=Graphics.FromImage(ob);

g.Clear(Color.WhiteSmoke);

g.CompositingQuality=CompositingQuality.HighQuality;

g.SmoothingMode=SmoothingMode.HighQuality;

g.InterpolationMode=InterpolationMode.HighQualityBicubic;

g.DrawImage(iSource,new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

g.Dispose();//以下代码为保存图片时,设置压缩质量

EncoderParameters ep = newEncoderParameters();long[] qy = new long[1];

qy[0] = flag;//设置压缩的比例1-100

EncoderParameter eParam = newEncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);

ep.Param[0] =eParam;try{

ImageCodecInfo[] arrayICI=ImageCodecInfo.GetImageEncoders();

ImageCodecInfo jpegICIinfo= null;for (int x = 0; x < arrayICI.Length; x++)

{if (arrayICI[x].FormatDescription.Equals("JPEG"))

{

jpegICIinfo=arrayICI[x];break;

}

}if (jpegICIinfo != null)

{

ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径

}else{

ob.Save(dFile, tFormat);

}return true;

}catch{return false;

}finally{

iSource.Dispose();

ob.Dispose();

}

}///

///无损压缩图片///

/// 原图片

/// 压缩后保存位置

/// 宽度

/// 高度

/// 压缩质量 1-100

///

public bool CompressPicture(string sFile, string dFile, int dWidth, int dHeight, intflag)

{

System.Drawing.Image iSource=System.Drawing.Image.FromFile(sFile);

ImageFormat tFormat=iSource.RawFormat;int sW = 0, sH = 0;//按比例缩放

Size tem_size = newSize(iSource.Width, iSource.Height);if (tem_size.Width > dWidth || tem_size.Height >dHeight)

{if ((tem_size.Width * dHeight) > (tem_size.Height *dWidth))

{

sW=dWidth;

sH= (dWidth * tem_size.Height) /tem_size.Width;

}else{

sH=dHeight;

sW= (tem_size.Width * dHeight) /tem_size.Height;

}

}else{

sW=tem_size.Width;

sH=tem_size.Height;

}

Bitmap ob= newBitmap(dWidth, dHeight);

Graphics g=Graphics.FromImage(ob);

g.Clear(Color.WhiteSmoke);

g.CompositingQuality=CompositingQuality.HighQuality;

g.SmoothingMode=SmoothingMode.HighQuality;

g.InterpolationMode=InterpolationMode.HighQualityBicubic;

g.DrawImage(iSource,new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);

g.Dispose();//以下代码为保存图片时,设置压缩质量

EncoderParameters ep = newEncoderParameters();long[] qy = new long[1];

qy[0] = flag;//设置压缩的比例1-100

EncoderParameter eParam = newEncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);

ep.Param[0] =eParam;try{

ImageCodecInfo[] arrayICI=ImageCodecInfo.GetImageEncoders();

ImageCodecInfo jpegICIinfo= null;for (int x = 0; x < arrayICI.Length; x++)

{if (arrayICI[x].FormatDescription.Equals("JPEG"))

{

jpegICIinfo=arrayICI[x];break;

}

}if (jpegICIinfo != null)

{

ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径

}else{

ob.Save(dFile, tFormat);

}return true;

}catch{return false;

}finally{

iSource.Dispose();

ob.Dispose();

}

}///

///按指定规格裁剪图片///

/// 源文件路径

/// 输出文件路径

/// 裁剪区域的起点

/// 裁剪区域的大小

/// 生成的规格

/// 压缩质量 1-100

///

public bool CropPicture(string sFile, string dFile, Point originPoint , Size sSize, Size dSize, intflag)

{

System.Drawing.Image iSource=System.Drawing.Image.FromFile(sFile);

ImageFormat tFormat=iSource.RawFormat;

Bitmap ob= newBitmap(dSize.Width, dSize.Height);

Graphics g=Graphics.FromImage(ob);

g.Clear(Color.WhiteSmoke);

g.CompositingQuality=CompositingQuality.HighQuality;

g.SmoothingMode=SmoothingMode.HighQuality;

g.InterpolationMode=InterpolationMode.HighQualityBicubic;

g.DrawImage(iSource,new Rectangle(0, 0, dSize.Width, dSize.Height), originPoint.X, originPoint.Y, sSize.Width, sSize.Height, GraphicsUnit.Pixel);

g.Dispose();//以下代码为保存图片时,设置压缩质量

EncoderParameters ep = newEncoderParameters();long[] qy = new long[1];

qy[0] = flag;//设置压缩的比例1-100

EncoderParameter eParam = newEncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);

ep.Param[0] =eParam;try{

ImageCodecInfo[] arrayICI=ImageCodecInfo.GetImageEncoders();

ImageCodecInfo jpegICIinfo= null;for (int i = 0; i < arrayICI.Length; i++)

{if (arrayICI[i].FormatDescription.Equals("JPEG"))

{

jpegICIinfo=arrayICI[i];break;

}

}if(string.IsNullOrEmpty(dFile))

{string[] temp = sFile.Split(new char[] { '\\'}, StringSplitOptions.RemoveEmptyEntries);string fileName = temp[temp.Length - 1];

fileName= fileName.Insert(fileName.IndexOf('.'), '_'+ dSize.Width.ToString() + '_' +dSize.Height.ToString());

temp[temp.Length- 1] =fileName;

dFile= string.Empty;foreach(string item intemp)

{

dFile+= item + "\\";

}

dFile=dFile.TrimEnd('\\');

}if (jpegICIinfo != null)

{

ob.Save(dFile, jpegICIinfo, ep);

}else{

ob.Save(dFile, tFormat);

}return true;

}catch{return false;

}finally{

iSource.Dispose();

ob.Dispose();

}

}#endregion

#region 判断图片格式

public bool IsAllowImg(string contentType, stringfileExtension)

{

contentType=contentType.ToLower();if(!contentType.Contains("image"))

{return false;

}

fileExtension=fileExtension.ToLower();string[] allowExtension = { ".bmp", ".gif", ".jpeg", ".jpg", ".png"};foreach (string item inallowExtension)

{if (fileExtension ==item)

{return true;

}

}return false;

}public static boolIsAllowedExtension(HttpPostedFileBase file)

{

System.IO.Stream stream=file.InputStream;

System.IO.BinaryReader reader= newSystem.IO.BinaryReader(stream);string fileclass = "";//这里的位长要具体判断.

bytebuffer;try{//buffer = r.ReadByte();//fileclass = buffer.ToString();//buffer = r.ReadByte();//fileclass += buffer.ToString();

for (int i = 0; i < 2; i++)

{

fileclass+=reader.ReadByte().ToString();

}

}catch{

}

reader.Close();

stream.Close();if (fileclass == "255216" || fileclass == "7173")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar

{return true;

}else{return false;

}

}#endregion[HttpPost]public JsonResult CropPhoto(string url,int x,int y,int w,inth)

{if (string.IsNullOrEmpty(url) || w == 0 || h == 0)

{return Json(new { Status = "error", Msg = "参数错误"});

}

Point origin= newPoint(x, y);

Size source= newSize(w, h);

Size destSmall= new Size(48, 48);

Size destLarge= new Size(180, 180);bool result1 =CropPicture(Server.MapPath(url), null, origin, source, destSmall, 100);bool result2 =CropPicture(Server.MapPath(url), null, origin, source, destLarge, 100);var jsonResult = result1 &&result2? new { Status = "success", Msg = "操作成功"}

:new { Status = "error", Msg = "裁剪图片出现错误"};returnJson(jsonResult);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这里提供一个基于jcrop库的图片裁剪演示,您可以在下面的代码框中运行它,体验一下: ```html <!DOCTYPE html> <html> <head> <title>Jcrop 图片裁剪演示</title> <meta charset="utf-8"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jquery-jcrop/0.9.15/css/jquery.Jcrop.min.css" /> <script src="//code.jquery.com/jquery-3.6.0.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-jcrop/0.9.15/js/jquery.Jcrop.min.js"></script> <style> #preview { width: 200px; height: 200px; overflow: hidden; } </style> </head> <body> <h1>Jcrop 图片裁剪演示</h1> <form method="post" action="crop.php"> <input type="hidden" name="image" value="path/to/image.jpg"> <img src="path/to/image.jpg" id="cropbox"> <div id="preview"></div> <p> <button type="submit">保存裁剪结果</button> </p> </form> <script> $(function() { $('#cropbox').Jcrop({ aspectRatio: 1, boxWidth: 500, onChange: updatePreview, onSelect: updatePreview }); }); function updatePreview(coords) { var rx = 200 / coords.w; var ry = 200 / coords.h; $('#preview').css({ width: Math.round(rx * $('#cropbox').width()) + 'px', height: Math.round(ry * $('#cropbox').height()) + 'px', marginLeft: '-' + Math.round(rx * coords.x) + 'px', marginTop: '-' + Math.round(ry * coords.y) + 'px' }); $('input[name="x"]').val(coords.x); $('input[name="y"]').val(coords.y); $('input[name="width"]').val(coords.w); $('input[name="height"]').val(coords.h); } </script> </body> </html> ``` 这段代码会加载jcrop库,并在页面中显示一张图片,您可以使用鼠标拖动裁剪框来选择需要裁剪的区域。当您选择好区域后,可以点击“保存裁剪结果”按钮,将裁剪结果提交给服务器。 为了使代码正常工作,您需要将上面代码中的 `path/to/image.jpg` 修改为您自己的图片路径,并创建一个名为 `crop.php` 的PHP脚本来处理裁剪结果。下面是一个裁剪处理脚本的示例: ```php // 获取裁剪参数 $x = $_POST['x']; $y = $_POST['y']; $width = $_POST['width']; $height = $_POST['height']; // 打开原始图像 $src = imagecreatefromjpeg($_POST['image']); // 创建新图像并复制裁剪区域 $dest = imagecreatetruecolor($width, $height); imagecopy($dest, $src, 0, 0, $x, $y, $width, $height); // 保存新图像 imagejpeg($dest, 'path/to/cropped/image.jpg'); // 释放内存 imagedestroy($src); imagedestroy($dest); ``` 这个脚本会从POST参数中获取裁剪参数和原始图像路径,然后使用GD库创建新图像并保存。请注意,上述代码仅供参考,并且需要根据具体情况进行适当的修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值