美文网首页
前端图片转换的几种方式-back

前端图片转换的几种方式-back

作者: 苏本的书柜 | 来源:发表于2021-05-08 16:48 被阅读0次
    /*
     * @Author: your name
     * @Date: 2020-09-04 18:38:23
     * @LastEditTime: 2021-05-07 15:12:14
     * @LastEditors: Please set LastEditors
     * @Description: In User Settings Edit
     * @FilePath: \tt-desktop\src\renderer\utils\imgFormatConversion.js
     */
    // base64转换为blob对象
    export 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 });
    }
    
    export function dataURLtoFile(dataurl) {
        let blob = dataURLtoBlob(dataurl);
        return new File(
            [blob],
            dataurl.substring(25, 40), { type: blob.type }
        );
    
    }
    // 获取base64图片的宽与高
    export function Base64WidthAndHeight(base64) {
        return new Promise((resolve, reject) => {
            var img = new Image()
            img.src = `${base64}`
            img.onload = () => {
                resolve({
                    width: img.width,
                    height: img.height
                })
            }
            img.onerror = error => reject(error)
        })
    }
    
    //file对象转化为buffer对象
    export function fileToBuf(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader()
            const filename = file.name;
            reader.readAsArrayBuffer(file)
            reader.onload = () => {
                resolve(Buffer.from(reader.result))
            }
            reader.onerror = error => reject(error)
        })
    }
    
    
    // file对象转换为base64,去掉了data:image\/png;base64,
    export function toBase64(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader()
            reader.readAsDataURL(file)
            reader.onload = () => {
                resolve(reader.result.split('base64,')[1])
            }
            reader.onerror = error => reject(error)
        })
    }
    //base64转压缩
    export function toSmallBase64(elementObj, maxWidth, maxHeight) {
        return new Promise((resolve, reject) => {
            if (typeof(FileReader) === 'undefined') {
                myApp.log.error("抱歉,你的浏览器不支持发送图片,不支持使用FileReader");
            } else {
                try {
                    //创建一个img对象
                    var img = new Image();
                    img.src = elementObj;
                    // base64地址图片加载完毕后执行
                    img.onload = function() {
                        // 缩放图片需要的canvas(也可以在DOM中直接定义canvas标签,这样就能把压缩完的图片不转base64也能直接显示出来)
                        var canvas = document.createElement('canvas');
                        var context = canvas.getContext('2d');
                        // 图片原始尺寸
                        var originWidth = this.width;
                        var originHeight = this.height;
                        // 最大尺寸限制,可通过设置宽高来实现图片压缩程度
                        //var maxWidth = 500;
                        //var maxHeight = 400;
                        // 目标尺寸
                        var targetWidth = originWidth,
                            targetHeight = originHeight;
                        // 图片尺寸超过最大值的限制
                        if (originWidth > maxWidth || originHeight > maxHeight) {
                            if (originWidth / originHeight > maxWidth / maxHeight) {
                                // 更宽,按照宽度限定尺寸
                                targetWidth = maxWidth;
                                targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                            } else {
                                targetHeight = maxHeight;
                                targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                            }
                        }
                        // canvas对图片进行缩放
                        canvas.width = targetWidth;
                        canvas.height = targetHeight;
                        // 清除画布
                        context.clearRect(0, 0, targetWidth, targetHeight);
                        // 图片压缩
                        /*第一个参数是创建的img对象;第二三个参数是左上角坐标,后面两个是画布区域宽高*/
                        context.drawImage(img, 0, 0, targetWidth, targetHeight);
                        //压缩后的图片转base64 url
                        //canvas.toDataURL(mimeType, qualityArgument),mimeType 默认值是'image/png';
                        //qualityArgument表示导出的图片质量,只有导出为jpeg和webp格式的时候此参数才有效,默认值是0.92
                        var base64_url = canvas.toDataURL('image/jpeg', 0.92); //base64 格式
                        resolve(base64_url)
                    }
                } catch (e) {
                    reject('图片转Base64出错啦!' + e.toString())
                }
            }
        })
    
    }
    //网络图片转化为base64
    export function getBase64Image(img) {
        let canvas = document.createElement("canvas")
        canvas.width = img.width
        canvas.height = img.height
        let ctx = canvas.getContext("2d")
        ctx.drawImage(img, 0, 0, img.width, img.height)
        let ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase()
        let dataURL = canvas.toDataURL("image/" + ext)
        return dataURL
    }
    export function srcToBaseOrFile(src, isFile) {
        let image = new Image()
        image.src = src
        image.setAttribute("crossOrigin", "Anonymous")
        // image.setAttribute("crossorigin", " *")
        image.onload = function() {
            let base64 = getBase64Image(image)
            if (isFile) {
                let formData = new FormData()
                //转换base64到file
                let file = baseToFile(base64, "test")
                formData.append("imageName", file)
            }
        }
    }
    export function baseToFile(data, fileName) {
        const dataArr = data.split(",")
        const byteString = atob(dataArr[1])
    
        const options = {
            type: "image/jpeg",
            endings: "native"
        }
        const u8Arr = new Uint8Array(byteString.length)
        for (let i = 0; i < byteString.length; i++) {
            u8Arr[i] = byteString.charCodeAt(i)
        }
        return new File([u8Arr], fileName + ".jpg", options)
    }
    
    
    // 本地图片转为base64
    export function locationPcitionToBase(fileUrl) {
        const fs = require('fs')
        let imageData = fs.readFileSync(fileUrl); // 例:fileUrl="D:\\test\\test.bmp"
        let imageBase64 = imageData.toString("base64");
        let imagePrefix = "data:image/bmp;base64,";
        return imageBase64;
    }
    

    相关文章

      网友评论

          本文标题:前端图片转换的几种方式-back

          本文链接:https://www.haomeiwen.com/subject/zenudltx.html