You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// dataURI is base64 format
dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
let byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0) {
// 解码base64成为 binary string
byteString = atob(dataURI.split(',')[1]);
} else {
byteString = unescape(dataURI.split(',')[1]);
}
// separate out the mime component
const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// binary string没法转成blob的, 所以先转成ArrayBuffer形式,这里使用
//Uint8Array形式,将binary string字符串存进去,然后就可以使用 new Blob转换了
// write the bytes of the string to a typed array
const ia = new Uint8Array(byteString.length);
for (let i = 0; i < byteString.length; i += 1) {
ia[i] = byteString.charCodeAt(i);
}
// Blob有兼容性问题,需要兼容处理
let blob;
try {
blob = new Blob([ia], { type: mimeString });
} catch (error) {
const BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
const bb = new BlobBuilder();
bb.append([ia]);
blob = bb.getBlob(mimeString);
}
return blob;
}
基础知识
dataURL
一个完整的 dataURI 应该是这样的:
其中mediatype声明了文件类型,遵循MIME规则,如“image/png”、“text/plain”;之后是编码类型,这里我们只涉及 base64;紧接着就是文件编码后的内容了。我们常常在 HTML 里看到img标签的src会这样写:
这个img引用的就是以 base64 编码的 dataURL 了,只要浏览器支持,就可以被解码成声明格式的图片并渲染出来。
.toDataURL()
调取手机相册和相机
使用的是类似input[type=file]文件上传的形式,只不过在手机端会加上一些配置,从而能默认识别到相册 :
处理上传的图片为dataURL
对读取成dataURL的图片进行压缩
压缩处理步骤:
如果要调整图片方向的,可使用canvas的rotate:
对压缩后的图片进行裁剪
使用的是Croppie 这个库实现放缩、移动、裁剪功能,但是其只支持相对或者绝对地址的图片url,所以先需要把我们的dataURI格式图片上传到服务器生成url。
dataURI转换成blob
由于上传接口只支持blob(file)格式,所以需要先把dataURI转换成blob:
上传blob
实现裁剪
初始化
裁剪可通过一个按钮触发
参考
利用 canvas 压缩图片
移动端 h5 照片的处理
HTML5调用照相机并自定义显示获取到的图片
用canvas的toDataURL()将图片转为dataURL(base64)
H5拍照上传填坑
The text was updated successfully, but these errors were encountered: