我最近写了一个上传图片的脚本。一切正常。但是现在我想在上传图像后调整图像大小。我对它做了一些研究,我想用 <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"); }
将图像放入 Canvas 元素中 - 缺失
调整它的大小 - 我想以某种方式使用的部分代码:
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) 将源图像调整到 Canvas 上
- 计算在不溢出的情况下适应最大尺寸所需的比例因子
- 创建一个具有缩放尺寸的新 Canvas
- 缩放原始图像并将其绘制到 Canvas 上
重要!确保源图像与您的网页来自同一域,否则 toDataURL
将出于安全原因失败。
(#4) 您可以使用 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;}
关于javascript - 上传前用 Canvas 调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38664890/