互联网上有几种工具可以使用JavaScript和PHP裁剪图像但不幸的是,如果我们打算让我们的应用程序严格脱机,那么就没有我们可以依赖的服务器端PHP脚本,所以我们必须这样做使用HTML5画布和JavaScript来离线裁剪图像。
答案 0 :(得分:2)
如果图片来自本地域,则可以使用html画布轻松裁剪。
但是,如果图像来自其他域,则会遇到CORS安全错误:http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity
如果需要,您还可以在裁剪时放大/缩小。
以下是使用画布“drawImage
裁剪图片的示例代码:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var img=new Image();
img.onload=function(){
crop();
}
img.src=document.getElementById("source").src;
function crop(){
// this takes a 105x105px crop from img at x=149/y=4
// and copies that crop to the canvas
ctx.drawImage(img,149,4,105,105,0,0,105,105);
// this uses the canvas as the src for the cropped img element
document.getElementById("cropped").src=canvas.toDataURL();
}
}); // end $(function(){});
</script>
</head>
<body>
<img id="source" width=400 height=234 src="localImage.png">
<img id="cropped" width=105 height=105>
<canvas id="canvas" width=105 height=105></canvas>
</body>
</html>