在开发中难免碰到图片上传问题!图片上传问题很好解决,而上传到服务器上的图片尺寸大小不一,使表现层无法使用统一的规格显示被上传的图片。
那么被上传的图片的 等比例缩 与等比率放 还有等比率截图 可能会给我们的开发带来障碍!
使用 jquery.imgareaselect图片处理插件完全可以解决这方面的问题;
jquery.imgareaselect 官方网站:http://odyniec.net/projects/imgareaselect/
导入jquery和jquery.imgareaselect后
例1.
$('#myimg').imgAreaSelect({ selectionColor: 'blue', selectionOpacity: 0.2,
borderWidth: 2 });
});
注释:
myimg:需要处理的图片
selectionColor:选择区域颜色
selectionOpacity:选择区域透明度
borderWidth:选择层边框大小
如果使用selectionColor参数 就必须设置selectionOpacity(透明度)
$('#myimg').imgAreaSelect({aspectRatio: '4:3', maxWidth: 400, maxHeight: 300});
});
注释:
myimg:需要处理的图片
aspectRatio:选择框宽高比率
maxWidth:选择区域透宽最大值
maxHeight:选择区域透高最大值
$('#myimg').imgAreaSelect({ x1: 0, y1: 0, x2: 400, y2: 300,keys: { arrows: 15, shift: 5 } });
});
注释:
myimg:需要处理的图片
x1:右上角x轴坐标
y1:右上角y轴坐标
x2:右下角x轴坐标
y2:右下角y轴坐标
key:开启键盘支持
例4:最关键的一个 等比率缩放
实现原理 需要两个图片 第一图是原图 第二个图是选择区域后显示的图
用第一个图上的选择坐标+css控制 产生第二个图 实际上两个图是一样的 只不过通
过css控制了第二张图的显示区域与缩放比率 如果需要实现真正截图功能必须使用
服务器端支持。 例如php asp aspx jsp ......
function preview(img, selection)
{
var scaleX = 100 / (selection.width || 1);
var scaleY = 100 / (selection.height || 1);
$('#myimg + div > img').css({
width: Math.round(scaleX * 400) + 'px',
height: Math.round(scaleY * 300) + 'px',
marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
});
}
$(document).ready(function () {
$('<div><img src="myimg.jpg" style="position: relative;" /></div>')
.css({
float: 'left',
position: 'relative',
overflow: 'hidden',
width: '100px',
height: '100px'
})
.insertAfter($('#myimg'));
});
$('#myimg').imgAreaSelect({ aspectRatio: '1:1', onSelectChange: preview });
});
注释:
myimg:需要处理的图片
onSelectChange:选择区域发生变化的时候回调处理
function preview(img, selection):回调函数
var scaleX = 100 / (selection.width || 1); 100->新图的宽
var scaleY = 100 / (selection.height || 1);100->新图的高
width: Math.round(scaleX * 400) + 'px', 400->原图的宽
height: Math.round(scaleY * 300) + 'px', 300->原图的高
$('<div><img src="myimg.jpg" style="position: relative;" /></div>')
.css({
float: 'left',
position: 'relative',
overflow: 'hidden',
width: '100px',
height: '100px'
})
值得注意的是:
这些参数必须设置正确、否则会出现 选择偏差 须设置正确、否则会出现 选择偏差
接下来是php服务端如何处理:
$x = $_GET['x'];//客户端选择区域左上角x轴坐标
$y = $_GET['y'];//客户端选择区域左上角y轴坐标
$lename" title="filename" >filename = "c:/myimg";//图片的路径
$im = imagecreatefromjpeg($lename" title="filename" >filename);// 读取需要处理的图片
$newim = imagecreatetruecolor(100, 100);//产生新图片 100 100 为新图片的宽和高
imagecopyresampled($newim, $im, 0, 0, $x, $y, 100, 100, $w, $h);
// [1] [2] [3][4] [5] [6] [7] [8] [9] [10]
//[7] 生成新图片的宽
//[8] 生成新图片的高
imagejpeg($newim, $lename" title="filename" >filename);
imagedestroy($im);
imagedestroy($newim);
--EOF--
非常好,谢谢分享
评分:5分
服装搭配技巧 : 2011-03-12 09:46
非常好,谢谢分享