h5实现手机原生拍照和图片上传

 html部分:

<van-button
                round
                type="danger"
                size="large"
                @click="phone"
                >拍摄</van-button
            >
            <input
                ref="phone"
                type="file"
                accept="image/*"
                style="display: none"
                @change="selectPhone($event)"
            />

js部分:

    methods: {
        phone() {
            this.$refs.phone.click();
        },
        // 上传照片
        upload(userFile) {
            let file = this.base64ToFile(
                userFile,
                new Date().getTime() + '.png'
            );
            // 使用自定义的请求方法哈,每个项目封装的是不一样的
            this.getRequest(
                    `${requestUrl}`,
                    {
                        method: 'post',
                        data: {
                            image: file,
                        },
                    },
                    // 请求头类型一般是需要修改的
                    { headers: { 'Content-Type': 'multipart/form-data' } }
                )
                .then((res) => {
                    if (res && res.resultCode == '000000') {
                        //上传成功后的操作
                    } else {
                        //上传失败后的操作
                    }
                });
        },
        async selectPhone(el) {
            var file = el.target.files[0];
            let img = await this.readImg(file);// 读取上传的照片并转为base64
            let image = await this.compressImg(img, file.type, 1000, 1000);//防止上传的照片过大,进行压缩处理
            if (image) {
                // 开始上传
                this.upload(image);
            }
        },
         /**
         * 压缩图片
         * @param img 被压缩的img对象
         * @param type 压缩后转换的文件类型
         * @param mx 触发压缩的图片最大宽度限制
         * @param mh 触发压缩的图片最大高度限制
         */
         compressImg(img, type, mx, mh) {
            return new Promise((resolve, reject) => {
                const canvas = document.createElement('canvas');
                const context = canvas.getContext('2d');
                const { width: originWidth, height: originHeight } = img;
                // 最大尺寸限制
                const maxWidth = mx;
                const maxHeight = mh;
                // 目标尺寸
                var targetWidth = originWidth;
                var targetHeight = originHeight;
                if (originWidth > maxWidth || originHeight > maxHeight) {
                    if (originWidth / originHeight > 1) {
                        // 宽图片
                        targetWidth = maxWidth;
                        targetHeight = Math.round(
                            maxWidth * (originHeight / originWidth)
                        );
                    } else {
                        // 高图片
                        targetHeight = maxHeight;
                        targetWidth = Math.round(
                            maxHeight * (originWidth / originHeight)
                        );
                    }
                }
                canvas.width = targetWidth;
                canvas.height = targetHeight;
                context.clearRect(0, 0, targetWidth, targetHeight);
                // 图片绘制
                context.drawImage(img, 0, 0, targetWidth, targetHeight);
                resolve(canvas.toDataURL(type, 0.2));
            });
        },
        readImg(file) {
            const _this = this;
            return new Promise((resolve, reject) => {
                const img = new Image();
                const reader = new FileReader();
                reader.onload = function (e) {
                    img.src = e.target.result;
                    let bold = _this.base64ToFile(
                        img.src,
                        new Date().getTime() + '.png'
                    );
                };
                reader.onerror = function (e) {
                    reject(e);
                };
                reader.readAsDataURL(file);
                img.onload = function () {
                    resolve(img);
                };
                img.onerror = function (e) {
                    reject(e);
                };
            });
        },
        base64ToFile(urlData, fileName) {
            let arr = urlData.split(',');
            let mine = arr[0].match(/:(.*?);/)[1];
            let bytes = atob(arr[1]); //解码base64
            let n = bytes.length;
            let ia = new Uint8Array(n);
            while (n--) {
                ia[n] = bytes.charCodeAt(n);
            }
            return new File([ia], fileName, { type: mine });
        },
    },

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值