zoukankan      html  css  js  c++  java
  • canvas前端压缩图片和视频首屏缩略图并上传到服务器

    图片:

            var img = document.createElement('img')
            img.src = window.URL.createObjectURL(fileObj.file)
            // 加载图片成功
            img.onload = function() {
              var canvas = document.createElement('canvas')
              var context = canvas.getContext('2d')
              // 清除画布
              canvas.width = size
              canvas.height = size
              context.clearRect(0, 0, size, size)
              // 图片压缩
              context.drawImage(img, 0, 0, size, size)
              // canvas转为blob并上传
              canvas.toBlob(function(blob) {
                // 创建forme
                var xhr = new XMLHttpRequest()
                xhr.open('PUT', uploadSrc)// 注意跨域问题
                xhr.send(blob)
                xhr.onerror = function() {
                  return
                }
              }, 'image/png')
            }
    

      size为自定义的大小,决定缩略图的大小。

    createObjectURL方法后面传入的是文件对象,这里为图片的文件

    video缩略图:
            var video = document.createElement('video')
            video.src = window.URL.createObjectURL(fileObj.file)
            // 加载图片成功
            setTimeout(function () {
              var canvas = document.createElement('canvas')
              var context = canvas.getContext('2d')
              // 清除画布
              canvas.width = size
              canvas.height = size
              context.drawImage(video, 0, 0, size, size)
              // canvas转为blob并上传
              canvas.toBlob(function(blob) {
                // 创建forme
                var xhr = new XMLHttpRequest()
                xhr.open('PUT', uploadSrc)// 注意跨域问题
                xhr.send(blob)
                xhr.onerror = function() {
                  return
                }
              }, 'image/png')
            }, 500)
    

      此处要注意的是,多一个setTimeout方法,因为绝大部分视频的首屏都是黑屏,为了避免尴尬,让视频走500毫秒

    整体要注意的是需要测试浏览器是否符合canvas和Blob对象的兼容性。如果后端需要传的是base64,则把canvas对象转成base64就行,canvas自身有转化的方法,具体请参考别的文章

  • 相关阅读:
    Codeforces Round #547 F1&F2. Same Sum Blocks(贪心)
    Codeforces Round #547 D. Colored Boots(贪心)
    Codeforces Round #547 C. Polycarp Restores Permutation(二分枚举/数学+模拟)
    CCF 201812-4 数据中心(最小生成树)
    CCF【小明放学&小明上学】
    TIME_WAIT状态
    ping的详细过程
    两段不相邻子段和之和最大
    神水一题之“Who's in the Middle”
    日进一步之“A Knight's Journey”
  • 原文地址:https://www.cnblogs.com/ypinchina/p/8618586.html
Copyright © 2011-2022 走看看