在项目中遇到了接入美图秀秀的需求,于是整理了一下,总结一下我在引入美图秀秀的过程中遇到的问题。
美图web开放平台:http://open.web.meitu.com/products/#M1
先登录美图web开放平台,按照步骤引入即可,我这里遇到的第一个问题是上传图片的方式,上传类型有三种,http://open.web.meitu.com/wiki/ ,由于项目里的图片都是上传到阿里云,需要调用相关接口,我选择了第三种方式:为编码成Base64传给JS,方法:xiuxiu.onSaveBase64Image
代码如下:
window.onload=function(){
xiuxiu.allowFullscreen = false;
xiuxiu.movie = "";
xiuxiu.wmode = "transparent";
// 自定义上传图片名称
var random = Math.floor(Math.random () * 1000);
var fileName = new Date().getTime() + random;
var time = new Date();
var date = time.getFullYear() + "/" + (time.getMonth()+1) + "/" + time.getDate() + "/";
xiuxiu.setLaunchVars("file_name", fileName);
// 自定义需要的菜单
xiuxiu.setLaunchVars('customMenu', [{'decorate': ['basicEdit', 'inpaint', 'trinket', 'text', 'particle', 'effect', 'border', 'magic', 'localFixes']}]);
xiuxiu.setLaunchVars('nav', 'decorate/basicEdit');
/*第1个参数是加载编辑器div容器,第2个参数是编辑器类型,第3个参数是div容器宽,第4个参数是div容器高*/
xiuxiu.embedSWF("altContent",3,"100%","100%");
//修改为您自己的图片上传接口
xiuxiu.setUploadURL("图片上传接口");
// 为编码成Base64传给JS
xiuxiu.setUploadType(3);
xiuxiu.onInit = function ()
{
xiuxiu.loadPhoto(imageUrl);
}
xiuxiu.onBeforeUpload = function (data, id)
{
xiuxiu.onSaveBase64Image = function(data, file_name, ext, id) {
/**
* 构造File对象,oss接受的是File对象
* 这里使用了base64编码图片,构造File时,必须要base64转码再构造,否则文件就是错的
*/
var ps_image = dataURLtoFile(data, file_name, ext);
// 上传图片
enclosureImgUpload(ps_image).then(res=>{
imageUrl = res;
// 将图片链接返回到上一个页面
window.opener && window.opener.refreshImage && window.opener.refreshImage(res);
}).catch(err=>{
});
return false;
}
}
}
将base64转换为文件
var mime_base = {
png: 'image/png',
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
gif: 'image/gif',
bmp: 'image/bmp'
};
function dataURLtoFile(data_url, file_name, ext) {
var mime = mime_base[ext],
bstr = atob(data_url),
n = bstr.length,
u8arr = new Uint8Array(n);
while(n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], file_name, {
type: mime
});
}
页面效果