我最近写了一个脚本来上传图像。一切正常。但是现在我想在上传图像后调整图像的大小。我已经对此进行了一些研究,并且希望尝试使用该<canvas>
元素。我有部分脚本,其他部分丢失了,我也不知道如何连接所有内容。
这些步骤是:
将图像上传到img/uploads
-完成。
<form action="picupload.php" method="post" enctype="multipart/form-data"> <input name="uploadfile" type="file" accept="image/jpeg, image/png"> <input type="submit" name="btn[upload]"> </form>
picupload.php:
$tmp_name = $_FILES['uploadfile']['tmp_name']; $uploaded = is_uploaded_file($tmp_name); $upload_dir = "img/uploads"; $savename = "[several code]";
if($uploaded == 1) { move_uploaded_file ( $_FILES['uploadfile']['tmp_name'] , "$upload_dir/$savename"); }
将图片放入画布元素-丢失
调整大小-我想以某种方式使用的部分代码:
var MAX_WIDTH = 400;
var MAX_HEIGHT = 300;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
将现有图像替换为新的调整大小的图像。- 丢失的
如果有人会给我一些提示来完成它,那就太好了-谢谢!
(#2-3)将源图像调整为画布大小
重要的!确保源图像与您的网页来自同一域,否则toDataURL
出于安全原因将失败。
(#4)您可以使用#3将画布从#3转换为图像 resizedImg.src=context.toDataURL
带注释的示例代码和一个演示:
var MAX_WIDTH = 400;
var MAX_HEIGHT = 300;
var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/annotateMe.jpg";
function start(){
var canvas=fitImageOntoCanvas(img,MAX_WIDTH,MAX_HEIGHT);
// #4
// convert the canvas to an img
var imgResized=new Image();
imgResized.onload=function(){
// Use the new imgResized as you desire
// For this demo, just add resized img to page
document.body.appendChild(imgResized);
}
imgResized.src=canvas.toDataURL();
}
// #3
function fitImageOntoCanvas(img,MAX_WIDTH,MAX_HEIGHT){
// calculate the scaling factor to resize new image to
// fit MAX dimensions without overflow
var scalingFactor=Math.min((MAX_WIDTH/img.width),(MAX_HEIGHT/img.height))
// calc the resized img dimensions
var iw=img.width*scalingFactor;
var ih=img.height*scalingFactor;
// create a new canvas
var c=document.createElement('canvas');
var ctx=c.getContext('2d');
// resize the canvas to the new dimensions
c.width=iw;
c.height=ih;
// scale & draw the image onto the canvas
ctx.drawImage(img,0,0,iw,ih);
// return the new canvas with the resized image
return(c);
}
body{ background-color:white; }
img{border:1px solid red;}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句