根据图片路径转成二进制格式文件
dearweb 发布:2022-02-21 22:18:12阅读:根据图片路径转成二进制格式文件
var img = "http://127.0.0.1/test/images/timg.jpg"; var image = new Image(); image.src = img; image.onload = function() { //文件的Base64字符串 var base64 = getBase64Image(image); console.log(base64); //Base64字符串转二进制 var file = dataURLtoBlob(base64); console.log(file); } /** * 图像转Base64 */ function getBase64Image(img) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, img.width, img.height); var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase(); var dataURL = canvas.toDataURL("image/" + ext); return dataURL; } /** *Base64字符串转二进制 */ function dataURLtoBlob(dataurl) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); } console.log(getBase64Image(imgDom),9999) console.log(dataURLtoBlob(getBase64Image(imgDom)),898989) srcimg.value = URL.createObjectURL(dataURLtoBlob(getBase64Image(imgDom))) // srcimg.value = getBase64Image(imgDom)
小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧