我正在开发一个跨平台的cordova项目,该项目涉及将图像上传到服务器并在网站上显示.用于从手机内存中获取已调整大小的图像并获取base64数据的代码如下: var image = new Image();image.src =
var image = new Image(); image.src = URL; image.onload = function () { var canvas = document.createElement("canvas"); var img_width = this.width; var img_height = this.height; canvas.width =1000; canvas.height = 1000; var w=(1000/img_width); var h=(1000/img_height); var ctx = canvas.getContext("2d"); ctx.scale(w,h); ctx.drawImage(this,0,0); var dataURL = canvas.toDataURL("image/png",1);
这里的问题是,图像宽度设置为画布宽度但高度不是.
此外,该代码在Android设备和ipads上完美运行,但问题仅出现在iphone上.
在Iphone 4s和5c上测试过
谁能帮帮我吗!!!!
输入图像是:
画布上的图像输出(作为png文件)是:
通过修改以下链接中提供的答案,我能够为我的案例创建一个解决方法,如下所示:When scaling and drawing an image to canvas in iOS Safari, width is correct but height is squished
我稍微调整了一下代码,所以现在看起来像这样:
var image = new Image(); image.src = URL; image.onload = function () { var canvas = document.createElement("canvas"); var img_width = image.width; var img_height = image.height; canvas.width = 600; canvas.height = 600; var ctx = canvas.getContext("2d"); var imgRatio; if (image.width > image.height) { imgRatio = image.width / image.height; } else { imgRatio = image.height / image.width; } var canRatio = canvas.width / canvas.height; var scaledWidth = image.width * (canvas.height / image.height); var scaledHeight; if (platformVersion.substring(0, 1) < 8) { scaledHeight = (image.height * (canvas.width / image.height)) * 2.1; } else { scaledHeight = (image.height * (canvas.width / image.height)); } if (imgRatio > canRatio) { ctx.drawImage(image, 0, 0, canvas.width, scaledHeight); } else { ctx.drawImage(image, 0, 0, scaledWidth, canvas.height); } var dataURL = canvas.toDataURL("image/png", 1); }
这里取决于手机的操作系统是否来自cordova设备插件,我将一个值乘以缩放高度以补偿压缩效果.