跨域请求图片处理

568 阅读1分钟

this.userInfo.photoId图片id http://10.39.35.11:88/fileserver/photo/getEmpPhoto?eId= 图片请求地址 跨域了

// 转化为base64
 imageUrlToBase64 () {
            //一定要设置为let,不然图片不显示
            let image = new Image();
            let imageUrl = `api${this.userInfo.photoId}`;

            //解决跨域问题
            image.setAttribute('crossOrigin', 'anonymous');
            image.src = imageUrl

            //image.onload为异步加载
            image.onload = () => {
                var canvas = document.createElement("canvas");
                canvas.width = image.width;
                canvas.height = image.height;
                var context = canvas.getContext('2d');
                context.drawImage(image, 0, 0, image.width, image.height);

                var quality = 0.8;
                //这里的dataurl就是base64类型
                this.imageBase = canvas.toDataURL("image/jpeg", quality);//使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png,因为压缩成png后base64的字符串可能比不转换前的长!
            }
        }
    },
// vue.config.js设置代理
  devServer: {
        host: '0.0.0.0',
        port: 18080,
        open: true,
        proxy: {
            // 这里的'/api'指向了127.0.0.1:3000  api为匹配项
            '/api': {
                target:'http://10.39.35.11:88/fileserver/photo/getEmpPhoto?eId=',
                // secure: false,  // 如果是https接口,需要配置这个参数
                changeOrigin: true, // 是否跨域
                pathRewrite: {
                    '^/api': '/' // 重写接口
                }
            }
        }
    },
<img v-if="imageBase" class="use-avatar" :src="imageBase" alt="" />

CSS中内联SVG图片有比Base64更好的形式

https://www.zhangxinxu.com/wordpress/2018/08/css-svg-background-image-base64-encode/