chrome
chrome
  • 发布:2015-10-12 22:23
  • 更新:2017-09-11 00:55
  • 阅读:4378

img src不能load 本地文件?

分类:MUI

为了能够及时的部署代码,而不让用户每次小的修改都升级app,
在manifest里面把页面入口指向了网站,如http://app.xxx.com/index.html

页面里面要上传图片,代码如下,函数的url最后就是 file:///file/path/aaa.jpg
代码最终会把打开的图片按照比例压缩后,转化成base64,放在隐藏的input框里面,随表单一起提交。

现在的问题时发现不能执行 img.onload函数,
但是如果包含这段代码的页面不是放在网站,而是本地页面,
代码执行就没问题。
<code>
var showImg = function (url,imgEl,inputEl) {
// 兼容以“file:”开头的情况
if (0 != url.toString().indexOf("file://")) {
url = "file://" + url;
}
console.log(url);
var img = new Image();
console.log(img);
img.src = url; // 传过来的图片路径在这里用。
// img.onclick = function() {
// plus.runtime.openFile(url);
// };
img.onload = function() {
var tmph = img.height;
var tmpw = img.width;
console.log("img.height = "+img.height);
console.log("img.width = "+img.width);

            var isHengTu = tmpw > tmph;  
            var max = Math.max(tmpw, tmph);  
            var min = Math.min(tmpw, tmph);  
            var bili = min / max;  
            if (max < 600){  
                    $.toast("图片分辨率太低,请重新选择图片!");  
                    return;  
            }  
            if (max > 480) {  
                max = 480;  
                min = Math.floor(bili * max);  
            }  
            tmph = isHengTu ? min : max;  
            tmpw = isHengTu ? max : min;  
            console.log("w="+tmpw+"  h="+tmph);  

// img.style.border = "1px solid rgb(200,199,204)";
// img.style.margin = "10px";
// img.style.width = "240px";
//img.style.height = "150px";
img.onload = null;
plus.io.resolveLocalFileSystemURL(url, function(entry) {
entry.file(function(file) {
console.log(file.size + '--' + file.name);
canvasResize(file, {
width: tmpw,
height: tmph,
crop: false,
quality: 30, //压缩质量
rotate: 0,
callback: function(data, width, height) {
//f1.push(data);
console.log(data.length);
imgEl.src = data;
imgEl.style.height = "160px";
imgEl.parentNode.style.height = "165px";
inputEl.value = data;
//img.src = data;
plus.nativeUI.closeWaiting();
}
});
});
},
function(e) {
plus.nativeUI.closeWaiting();
console.log(e.message);
});
};
};
</code>

2015-10-12 22:23 负责人:无 分享
已邀请:
chrome

chrome (作者)

在网上找到了这个
http://www.oschina.net/code/snippet_19410_37963

不知道HBuild用的是啥浏览器内核啊?有办法解决么?

还有,这里放在img.onload里面处理,主要就是为了获得浏览器获得图片的实际宽高,好进行等比例的缩放。
不知道有没有其他办法获得宽高??

chrome

chrome (作者)

最后试了一下, canvasResize本身可以不用设置宽高, 如果只设置宽,最后工具内会自动按照比例调整高度来适应。
所以没必要用img.src来load对象获取宽高了。

d***@163.com

d***@163.com

最后怎么搞的啊~

该问题目前已经被锁定, 无法添加新回复