Jcrop是一个jQuery插件,它能为你的WEB应用程序快速简单地提供图片裁剪的功能
Jcrop使用:
第一步:引入插件
插件下载地址:http://deepliquid.com/content/Jcrop_Download.html
下面例子效果:
Jcrop是依赖于jQuery,所以在引入 jquery.Jcrop.js之前要先引入jQuery.js。
(1)页面html:
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/demos.css">
<link rel="stylesheet" href="css/jquery.Jcrop.css">
<link rel="stylesheet" href="jquery.Jcrop.js">
<style type="text/css">
/* Apply these styles only when #preview-pane has
been placed within the Jcrop widget */
.jcrop-holder #preview-pane {
display: block;
position: absolute;
z-index: 2000;
top: 10px;
right: -280px;
padding: 6px;
border: 1px rgba(0,0,0,.4) solid;
background-color: white;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
}
/* The Javascript code will set the aspect ratio of the crop
area based on the size of the thumbnail preview,
specified here */
#preview-pane .preview-container {
width: 250px;
height: 170px;
overflow: hidden;
}
</style>
<div class="cut-img">
<img src="@imageUrl" id="target" alt="原图" />
<br />
<div id="preview-pane">
<div class="preview-container">
<img src="@imageUrl" class="jcrop-preview" alt="预览" />
</div>
</div>
</div>
<input type="hidden" id="hidx1" />
<input type="hidden" id="hidy1" />
<input type="hidden" id="hidx2" />
<input type="hidden" id="hidy2" />
<input type="hidden" id="hidw" />
<input type="hidden" id="hidh" />
<script type="text/javascript">
var cutOraImgUrl = '@imageUrl';
var cutImgArr;
jQuery(function ($) {
// Create variables (in this scope) to hold the API and image size
var jcrop_api,
boundx,
boundy,
// Grab some information about the preview pane
$preview = $('#preview-pane'),
$pcnt = $('#preview-pane .preview-container'),
$pimg = $('#preview-pane .preview-container img'),
xsize = $pcnt.width(),
ysize = $pcnt.height();
console.log('init', [xsize, ysize]);
$('#target').Jcrop({
onChange: updatePreview,
onSelect: updatePreview,
aspectRatio: xsize / ysize,
boxWidth: '460',
boxHeight: '460'
}, function () {
// Use the API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
// Store the API in the jcrop_api variable
jcrop_api = this;
jcrop_api.animateTo([0, 0, 362, 178]);
jcrop_api.setOptions({
aspectRatio: 16 / 9
});
console.log("dddddd:" + jcrop_api.tellSelect());
// Move the preview into the jcrop container for css positioning
$preview.appendTo(jcrop_api.ui.holder);
});
function updatePreview(c) {
$('#hidx1').val(c.x);
$('#hidy1').val(c.y);
$('#hidx2').val(c.x2);
$('#hidy2').val(c.y2);
$('#hidw').val(c.w);
$('#hidh').val(c.h);
if (parseInt(c.w) > 0) {
var rx = xsize / c.w;
var ry = ysize / c.h;
//var imageWidth = Math.round(rx * boundx);
//var imageHeight = Math.round(ry * boundy);
var imageMarginLeft = '-' + Math.round(rx * c.x);
var imageMarginTop = '-' + Math.round(ry * c.y);
// console.log("裁剪后的图片:imageWidth=" + imageWidth + ",imageHeight=" + imageHeight + ",imageMarginLeft=" + imageMarginLeft + ",imageMarginTop=" + imageMarginTop);
$pimg.css({
width: Math.round(rx * boundx) + 'px',
height: Math.round(ry * boundy) + 'px',
marginLeft: '-' + Math.round(rx * c.x) + 'px',
marginTop: '-' + Math.round(ry * c.y) + 'px'
});
}
cutImgArr = {
"ImgWidth": parseInt($('#hidw').val()),
"ImgHeight": parseInt($('#hidh').val()),
"Imgx1": parseInt($('#hidx1').val()),
"Imgy1": parseInt($('#hidy1').val()),
"Imgx2": parseInt($('#hidx2').val()),
"Imgy2": parseInt($('#hidy2').val())
};
};
});
function GetValue() {
return cutImgArr;
}
</script>
(2)引用样式表文件和js
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/demos.css">
<link rel="stylesheet" href="css/jquery.Jcrop.css">
<link rel="stylesheet" href="jquery.Jcrop.js">
(3)裁剪图片js:
<script type="text/javascript">
//裁剪图片
$("#btnCutImg").click(function () {
var imgurl = $("#cover").val();
if (imgurl == null || imgurl == "") {
layer.msg("请先上传图片");
return;
}
OpenCutImage(imgurl);
});
var cutImageDialog = "";
$(function () {
var jcrop_api;
});
//打开裁剪图片窗口
function OpenCutImage(imgurl) {
if (imgurl == null || imgurl == "") {
layer.msg("请先上传图片");
return;
}
if (imgurl != '' && imgurl != undefined && imgurl != null) {
layer.open({
btn: ['确定'],
type: 2,
title: '裁剪图片',
shadeClose: true,
shade: 0.8,
area: ['800px', '595px'],
content: '/wechatimage/cutimage?imageurl=' + imgurl,
yes: function (index, layero) {
var iframeWin = window[layero.find('iframe')[0]['name']];
var iframeModel = iframeWin.GetValue();
console.info("弹窗:" + iframeModel);
if (iframeModel != null) {
var fileDir = "";
var fileType = 1;
var wechatFileType = 3;
var fileWidth = iframeModel.ImgWidth;
var fileHeight = iframeModel.ImgHeight;
var fileX = iframeModel.Imgx1;
var fileY = iframeModel.Imgy1;
var data = JSON.stringify({
ImgUrl: imgurl,
FileDir: fileDir,
FileType: fileType,
WechatFileType: wechatFileType,
FileWidth: fileWidth,
FileHeight: fileHeight,
FileX: fileX,
FileY: fileY
});
CutImage(data, function (result) {
console.log(result);
if (result.IsSuccess) {
if (result.Data != null && result.Data != "") {
//裁剪后图片地址
var imgPath = result.Data.ImgUrl;
}
}
})
layer.close(index);
}
else {
layer.msg("请选择图片!");
layer.close(index);
}
}
});
}
}
</script>
(4)裁剪图片后台:
using Model;
using Model.Common;
using Controllers.Filter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Utility;
using WechatOpen.Web.Controllers;
using System.Net;
using System.IO;
using System.Drawing;
namespace Controllers
{
[UserAuthorization(checkWechatAppStatus: true)]
public class UploadImgController : BaseController
{
private bool IsRandomFileName = true;
private string FixedName = string.Empty;
#region 裁剪图片
/// <summary>
/// 裁剪图片
/// </summary>
[HttpPost]
public ActionResult UploadCutImg(string FileDir, string ImgUrl, string FileType, string WechatFileType,
string FileWidth, string FileHeight, string FileX, string FileY)
{
bool isSuccess = false;
string message = "操作失败";
object data = null;
//string fileDir = string.Empty, imgUrl = string.Empty;
int fileWidth = StringHelper.ToInt(FileWidth),
fileHeight = StringHelper.ToInt(FileHeight),
fileX = StringHelper.ToInt(FileX),
fileY = StringHelper.ToInt(FileY),
fileType = StringHelper.ToInt(FileType),
wechatFileType = StringHelper.ToInt(WechatFileType);
int userId = CurrentUser.UserId;
int appId = CurrentUser.AppId;
if (userId <= 0)
{
message = "用户未登录!";
SetAjaxResult(isSuccess, message, data);
return Json(AjaxResult);
}
string fileDir = GetFileDir(userId, appId, FileDir, fileType, wechatFileType);
if (fileDir == null)
{
message = "图片路径不正确!";
SetAjaxResult(isSuccess, message, data);
return Json(AjaxResult);
}
if (string.IsNullOrEmpty(fileDir))
{
message = "文件上传目录为空!";
SetAjaxResult(isSuccess, message, data);
return Json(AjaxResult);
}
if (String.IsNullOrEmpty(ImgUrl))
{
message = "未选择上传图片!";
SetAjaxResult(isSuccess, message, data);
return Json(AjaxResult);
}
try
{
FileDirInfo model = new FileDirInfo();
model.FileDir = fileDir;
model.FileThumbWidth = StringHelper.ToInt(fileWidth);
model.FileThumbHeight = StringHelper.ToInt(fileHeight);
model.Extension = FileHelper.GetFileExtension(ImgUrl);
//是否自动生成文件名称
if (IsRandomFileName)
model.FileName = FileHelper.CreateRandomFileNameByDateTime(1, model.Extension.ToLower());
else
{
if (!string.IsNullOrEmpty(FixedName))
model.FileName = string.Concat(FixedName, model.Extension.ToLower());
else
{
message = "上传失败!";
SetAjaxResult(isSuccess, message, data);
return Json(AjaxResult);
}
}
//文件上传,原图上传
string uploadPath = string.Empty;
string uploadPhysicalPath = string.Empty;
string imgUrlPhysicalPath = System.Web.HttpContext.Current.Server.MapPath(ImgUrl);//原图的物理路径
if (!string.IsNullOrEmpty(model.FileDir) && model.FileThumbWidth > 0 && model.FileThumbHeight > 0)
{
if (GetUploadDir(model.FileDir, model.FileName, IsRandomFileName, out uploadPath, out uploadPhysicalPath))
{
byte[] bitimg = ImageHelper.CropImage(imgUrlPhysicalPath, fileX, fileY, fileWidth, fileHeight);
if (bitimg != null)
{
System.IO.File.WriteAllBytes(uploadPhysicalPath, bitimg); //保存图片到服务器
}
}
}
isSuccess = true;
message = "图片裁剪成功!";
data = new { ImgUrl = uploadPath };
SetAjaxResult(isSuccess, message, data);
return Json(AjaxResult);
}
catch (Exception ex)
{
LogHelper.Error("裁剪图片异常信息:" + ex.ToString());
message = "图片裁剪失败!";
}
SetAjaxResult(isSuccess, message, data);
return Json(AjaxResult);
}
#endregion 裁剪图片
#region 文件夹操作
/// <summary>
/// 生成文件夹
/// </summary>
/// <param name="fileDir">上传路径</param>
/// <param name="fileName">文件名称</param>
/// <param name="uploadPath">上传相对路径</param>
/// <param name="uploadPhysicalPath">上传物理路径</param>
/// <returns></returns>
protected static bool GetUploadDir(string fileDir, string fileName, bool IsRandomFileName, out string uploadPath, out string uploadPhysicalPath)
{
uploadPath = "";
uploadPhysicalPath = "";
if (string.IsNullOrEmpty(fileDir) || string.IsNullOrEmpty(fileName)) return false;
if (IsRandomFileName)
fileDir = FileHelper.MergePath("/", new string[] { fileDir, FileHelper.CreateFolderNameByDateTime("yyyyMMdd") });
uploadPath = FileHelper.MergePath("/", new string[] { fileDir, fileName });
try
{
string uploadPhysicalDir = System.Web.HttpContext.Current.Server.MapPath(fileDir);
if (!string.IsNullOrEmpty(uploadPhysicalDir))
{
FileHelper.CreateDirectory(uploadPhysicalDir);
uploadPhysicalPath = FileHelper.MergePath("\\", new string[] { uploadPhysicalDir, fileName });
return true;
}
}
catch { }
return false;
}
#endregion 文件夹操作
#region 获取Url参数
/// <summary>
/// 获取Url参数(Url编码解密)
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
protected string GetDecodingParams(string name)
{
return this.Server.UrlDecode(GetParams(name));
}
/// <summary>
/// 获取Url参数(Url编码解密)
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
protected string GetDecodingParams(string name, string defaultValue)
{
return this.Server.UrlDecode(GetParams(name, defaultValue));
}
/// <summary>
/// 获取Url参数
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
protected string GetParams(string name)
{
return GetParams(name, "");
}
/// <summary>
/// 获取Url参数
/// </summary>
/// <param name="name"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
protected string GetParams(string name, string defaultValue)
{
string value = Request.Params[name];
if (string.IsNullOrEmpty(value))
{
value = defaultValue;
}
if (!string.IsNullOrEmpty(value))
{
value = value.Trim();
}
return StringHelper.FilterIllegalParameter(value);
}
#endregion 获取Url参数
}
public class FileDirInfo
{
private string fileName = string.Empty;
/// <summary>
/// 文件名称
/// </summary>
public string FileName
{
get { return fileName; }
set { fileName = value; }
}
private string extension = string.Empty;
/// <summary>
/// 文件后缀
/// </summary>
public string Extension
{
get { return extension; }
set { extension = value; }
}
private string fileDir = string.Empty;
/// <summary>
/// 上传文件路径
/// </summary>
public string FileDir
{
get { return fileDir; }
set { fileDir = value; }
}
private string fileThumbDir = string.Empty;
/// <summary>
/// 缩略图路径
/// </summary>
public string FileThumbDir
{
get { return fileThumbDir; }
set { fileThumbDir = value; }
}
private int fileThumbWidth = 0;
/// <summary>
/// 缩略图宽度
/// </summary>
public int FileThumbWidth
{
get { return fileThumbWidth; }
set { fileThumbWidth = value; }
}
private int fileThumbHeight = 0;
/// <summary>
/// 缩略图高度
/// </summary>
public int FileThumbHeight
{
get { return fileThumbHeight; }
set { fileThumbHeight = value; }
}
}
}
(5)裁剪图片ImageHelper类:
ImageHelper.cs:
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
namespace Utility
{
public class ImageHelper
{
#region 裁剪图片
/// <summary>
/// 裁剪图片
/// </summary>
public static byte[] CropImage(string imgUrl, int fileX, int fileY, int fileWidth, int fileHeight)
{
byte[] bitimg = null;
Stream stream = ImageToStream(imgUrl);
if (stream == null)
{
return null;
}
string strBase64 = CropImage(stream, fileX, fileY, fileWidth, fileHeight);
if (String.IsNullOrEmpty(strBase64))
{
return null;
}
bitimg = ImageHelper.Base64ToImg(strBase64);
return bitimg;
}
public static string CropImage(byte[] content, int x, int y, int cropWidth, int cropHeight)
{
using (MemoryStream stream = new MemoryStream(content))
{
return CropImage(stream, x, y, cropWidth, cropHeight);
}
}
public static string CropImage(Stream content, int x, int y, int cropWidth, int cropHeight)
{
using (Bitmap sourceBitmap = new Bitmap(content))
{
//将选择好的图片缩放
Bitmap bitSource = new Bitmap(sourceBitmap, sourceBitmap.Width, sourceBitmap.Height);
Rectangle cropRect = new Rectangle(x, y, cropWidth, cropHeight);
using (Bitmap newBitMap = new Bitmap(cropWidth, cropHeight))
{
newBitMap.SetResolution(sourceBitmap.HorizontalResolution, sourceBitmap.VerticalResolution);
using (Graphics g = Graphics.FromImage(newBitMap))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
g.DrawImage(bitSource, new Rectangle(0, 0, newBitMap.Width, newBitMap.Height), cropRect, GraphicsUnit.Pixel);
return GetBitmapBytes(newBitMap,200,300);
}
}
}
}
public static string GetBitmapBytes(Bitmap source, int resizeWidth, int resizeHeight)
{
//需要重新缩放图片,不然裁剪出来的图片大小会很大
return ResizeImage(source, resizeWidth, resizeHeight);
}
/// <summary>
/// 按比例缩放图片
/// </summary>
/// <param name="content"></param>
/// <param name="resizeWidth"></param>
/// <returns></returns>
public static string ResizeImage(Bitmap sourceBitmap, int resizeWidth, int resizeHeight)
{
int width = sourceBitmap.Width,
height = sourceBitmap.Height;
if (height > resizeHeight || width > resizeWidth)
{
if ((width * resizeHeight) > (height * resizeWidth))
{
resizeHeight = (resizeWidth * height) / width;
}
else
{
resizeWidth = (width * resizeHeight) / height;
}
}
else
{
resizeWidth = width;
resizeHeight = height;
}
// 将选择好的图片缩放
Bitmap bitSource = new Bitmap(sourceBitmap, resizeWidth, resizeHeight);
bitSource.SetResolution(sourceBitmap.HorizontalResolution, sourceBitmap.VerticalResolution);
using (MemoryStream stream = new MemoryStream())
{
bitSource.Save(stream, ImageFormat.Jpeg);
byte[] data = new byte[stream.Length];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(data, 0, Convert.ToInt32(stream.Length));
string newImage = Convert.ToBase64String(data);
return newImage;
}
}
/// <summary>
/// 图片转换Base64
/// </summary>
/// <param name="urlOrPath">图片网络地址或本地路径</param>
public static string ImageToBase64(string urlOrPath)
{
try
{
if (urlOrPath.Contains("http"))
{
Uri url = new Uri(urlOrPath);
using (var webClient = new WebClient())
{
var imgData = webClient.DownloadData(url);
using (var ms = new MemoryStream(imgData))
{
byte[] data = new byte[ms.Length];
ms.Seek(0, SeekOrigin.Begin);
ms.Read(data, 0, Convert.ToInt32(ms.Length));
string netImage = Convert.ToBase64String(data);
return netImage;
}
}
}
else
{
FileStream fileStream = new FileStream(urlOrPath, FileMode.Open);
Stream stream = fileStream as Stream;
byte[] data = new byte[stream.Length];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(data, 0, Convert.ToInt32(stream.Length));
string netImage = Convert.ToBase64String(data);
return netImage;
}
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// 图片转换流
/// </summary>
/// <param name="urlOrPath">图片网络地址或本地路径</param>
public static Stream ImageToStream(string urlOrPath)
{
Stream stream = null;
try
{
if (urlOrPath.Contains("http"))
{
Uri url = new Uri(urlOrPath);
using (var webClient = new WebClient())
{
var imgData = webClient.DownloadData(url);
var ms = new MemoryStream(imgData);
stream = ms as Stream;
}
}
else
{
FileStream fileStream = new FileStream(urlOrPath, FileMode.Open);
stream = fileStream as Stream;
}
}
catch (Exception)
{
return null;
}
return stream;
}
//base64编码的文本 转为 图片
public static byte[] Base64ToImg(string strBase64)
{
byte[] bt = Convert.FromBase64String(strBase64);
return bt;
}
#endregion 裁剪图片
}
}