h5上传图片压缩

涉及知识点

  • uniapp项目h5,涉及到前端图片压缩上传
  • uni.chooseImage()
  • canvas压缩
<template>
    <view class="uploadImages" @click="upImg()">
        <view class="defaultBg" style="width: 280rpx;" v-if="!isShow">
              点击上传  
        </view>
        <img v-if="isShow" :src="nFileBase64">
    </view>

  <helang-compress ref="helangCompress" :helangCompressType="uploadImgType"></helang-compress>

</template>
<script>
import helangCompress from '../helang-compress/helang-compress'

    components: {
      helangCompress,
     },
    props: ["uploadImgType"],
    export default {
        data() {
            return {
                nFileBase64: "",
            }
        },
        methods: {
            upImg() {
                var cthis = this;
                uni.chooseImage({
                    count: 1,
                    sizeType: ['compressed'], //此处指定是原图还是压缩图
                    sourceType: ['album'], //从相册选还是相机拍照
                    success(res) {
                        uni.showLoading()
                        cthis.$refs.helangCompress.compress(res.tempFiles[0], async (base64Codes) => {
                            const FileBase64 = base64Codes.replace(/^data:image\/\w+;base64,/, "")
                            cthis[`${type}FileBase64`] = base64Codes;
                            cthis.$emit("success", {
                                FileBase64: FileBase64,
                                FileExt: base64Codes.split(";")[0].split("/")[1],
                                type
                            })

                            setTimeout(function() {
                                uni.hideLoading();
                            }, 200);
                        })
                    },

                })
            }
        }
    }
</script>
<template>
    <view class="compress">
        <canvas :style="{ width: canvasSize.width,height: canvasSize.height}" :canvas-id="helangCompressType"></canvas>
    </view>
</template>

<script>
    export default {
        props:["helangCompressType"],
        data() {
            return {
                canvasSize: {
                    width: 0,
                    height: 0
                }
            }
        },
        methods: {
            // 压缩
            compress(file, objDiv) {
                var ready = new FileReader();
                ready.readAsDataURL(file);
                let _this = this;
                ready.onload = function() {
                    var fileResult = this.result;
                    _this.canvasDataURL(fileResult, objDiv)
                }
            },
            canvasDataURL(path, callback) {
                var img = new Image();
                img.src = path;
                var objCompressed = {}
                var _this = this;
                img.onload = function() {
                    //默认压缩后图片规格
                    var quality = 0.7;
                    var w = this.width;
                    var h = this.height;
                    //实际要求
                    if (w > h) {
                        let scale = h/w
                        h = 1300;
                        w = h/scale;
                    } else {
                        let scale = w/h
                        w = 1300;
                        h = w/scale;
                    }
                    // w = objCompressed.width || w;
                    // h = objCompressed.height || (w / scale);
                    //生成canvas
                    var canvas = document.createElement('canvas');
                    var ctx = canvas.getContext('2d');
                    // 创建属性节点
                    var anw = document.createAttribute("width");
                    anw.nodeValue = w;
                    var anh = document.createAttribute("height");
                    anh.nodeValue = h;
                    canvas.setAttributeNode(anw);
                    canvas.setAttributeNode(anh);
                    ctx.drawImage(this, 0, 0, w, h);
            
                    var base64 = canvas.toDataURL('image/jpeg', quality);
                    // 回调函数返回base64的值
                    callback(base64);
                }
            },
        }
    }
</script>

<style lang="scss" scoped>
    .compress{
        position: fixed;
        width: 12px;
        height: 12px;
        overflow: hidden;
        top: -99999px;
        left: 0;
    }
</style>

参考文章:https://blog.csdn.net/baidu_41604826/article/details/11122460

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容