将在线图片转换成base64踩坑记录及静态资源跨域及缓存的处理

1、在线图片资源跨域的问题

  解决方法:将“跨域图片资源”转换成base64后,用base64渲染img标签,这样完美解决问题;

  如何将“跨域图片”转换成base64呢?原理很简单,将img绘制成canvas,再将canvas转换成base64的img流;

  因为图片是跨域的,所以我们在转换过程中需要加一段代码:image.crossOrigin = "*";,用来处理跨域;

let image = new Image()
image.src = this.networkImg
image.crossOrigin = "*"

  发现偶尔还是会报错:Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

2、图片url缓存

  在这里能找到答案:https://stackoverflow.com/questions/46609800/canvas-crossorigin-anonymous-cors-chrile-mac-osx

If your images come from a different domain, and you want to be able to export the canvas content after you did draw these images, then you have no choice than loading them with the crossOrigin attribute.

If you are really facing the linked bug, according to it, the proper fix is to always send the CORS headers from your server response, whether or not the request is made with the Origin header.

And a fast workaround is to avoid the cache, by appending a random query string in the image's src (img.src = url + '?v=' + Math.random();).

  需要加个随机数防止缓存即可

let image = new Image()
image.src = this.networkImg + '?v=' + Math.random()
image.crossOrigin = "*"

  我代码里的解决

复制代码
      insertImg () {
        let _this = this
        let image = new Image()
        image.src = this.networkImg + '?v=' + Math.random()
        image.crossOrigin = "*"
        image.onload = function(){
          let base64 = _this.getBase64Image(image)
          _this.talkInfo.imageUrls.push(base64)
          _this.networkImg = ''
        }
      },
      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 dataURL = canvas.toDataURL("image/png")
        return dataURL
      },
复制代码

  思路:

  1、image的onload下载图片资源

  2、利用canvas转换base64

  3、避免跨域及缓存的坑

posted @   古兰精  阅读(5519)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2018-05-09 Node.js:模块系统、函数
2018-05-09 ElementUI表单验证使用
点击右上角即可分享
微信分享提示