vue之使用Cropper进行图片剪裁上传压缩

vue之使用Cropper进行图片剪裁上传

在项目中,对上传的图片按照比例和尺寸进行裁剪,以便于应用到不同的场景和平台上。这里采用cropper插件裁剪图片

一、cropper的使用
使用教程:https://github.com/fengyuanchen/cropper#options

二、用例:

点击头像上传图片→对图片进行裁剪


源码

<template>
    <div class="index_seting">
        <ul class="set_center">
            <li class="set_head_img">
                <a class="set_item">
                    <label class="head_lab" for="change">
                        <h3>头像</h3>
                        <span class="head_img">
                            <img :src="set_head">
                        </span>
                    </label>
                    <input type="file" id="change" class="none" @change="change" accept="image/png, image/jpeg, image/gif, image/jpg" multiple>
                </a>
            </li>
        </ul>
        <div class="img-view" v-show="img_cro_model" >
            <img id="image" :src="url" alt="Picture">
            <div class="gif_loading" v-show="update_img">
                <p>头像上传中...</p>
                <span></span>
            </div>
            <div class="img_btn">
                <span @click="hideImageCro">取消</span>
                <span @click="doCrop">完成</span>
            </div>
        </div>
    </div>
</template>

<script>
import Cropper from 'cropperjs'
export default {
  data () {
    return {
        set_head:'',                //头像图片临时缓存url
        update_img:false,           //头像上传中gif
        picValue:'',                //图片参数
        cropper:'',  
        croppable:false,            //是否初始化裁剪框
        img_cro_model:false,        //是否显示底部头像裁剪模块  
        url:'',                     //每次替换图片要重新得到新的url
        base64:''                   //裁剪并压缩后的图片
    }
  },
  mounted:function(){
    //初始化裁剪框  
    var self = this;
    var image = document.getElementById('image');  
    this.cropper = new Cropper(image, {  
        aspectRatio: 1,  
        viewMode: 1,  
        background:false,  
        zoomable:false,  
        ready: function () {  
            self.croppable = true;
        }  
    });
  },
  methods:{
    hideImageCro(){
        this.img_cro_model = false;
    },
    //让浏览器执行createObjectURL方法,实现本地图片预览
    getObjectURL (file) {  
        var url = null ;
        if (window.createObjectURL!=undefined) {    // basic  
            url = window.createObjectURL(file);  
        } else if (window.URL!=undefined) {         // firefox
            url = window.URL.createObjectURL(file);  
        } else if (window.webkitURL!=undefined) {   // chrome  
            url = window.webkitURL.createObjectURL(file);  
        }  
        return url;
    },  
    change (e) {  
        let files = e.target.files || e.dataTransfer.files;  
        if (!files.length) return;
        this.picValue = files[0];  
        this.url = this.getObjectURL(this.picValue);  
        //每次替换图片要重新得到新的url  
        if(this.cropper){
            this.cropper.replace(this.url);  
        }  
        this.img_cro_model = true;  
    },
    //强制让crop函数在弹窗后执行
    doCrop(){
        let that = this;
        this.update_img = true;
        setTimeout(function(){
            that.crop();
        },10);
    }, 
    crop () {  
        var croppedCanvas;  
        var roundedCanvas;  
        if (!this.croppable) {  
          return;  
        }  
        //裁剪
        croppedCanvas = this.cropper.getCroppedCanvas();  
        //圆
        roundedCanvas = this.getRoundedCanvas(croppedCanvas);  
        //将裁剪后的base64图片做压缩处理        
        this.compressImg(roundedCanvas.toDataURL());
    },  
    getRoundedCanvas (sourceCanvas) {
        var canvas = document.createElement('canvas');  
        var context = canvas.getContext('2d');  
        var width = sourceCanvas.width;  
        var height = sourceCanvas.height;  
        canvas.width = width;  
        canvas.height = height;  
        context.imageSmoothingEnabled = true;
        context.drawImage(sourceCanvas, 0, 0, width, height);  
        context.globalCompositeOperation = 'destination-in';  
        context.beginPath();  
        //取消输出图片的圆形截取效果
        // context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI, true);  
        context.fill();  
        return canvas;
    },
    compressImg(img_base64){
        let that = this,
            Img = new Image();
        Img.src = img_base64;
        Img.onload = function(){
            let w = this.naturalWidth,
                h = this.naturalHeight,
                resizeW = 0,
                resizeH = 0;
            //压缩设置
            let maxSize = {
                width:320,
                height:320,
                level:0.6      //图片保存质量
            };
            //计算压缩比例
            if(w > maxSize.width || h > maxSize.height){
                let multiple = Math.max(w / maxSize.width , h / maxSize.height);
                resizeW = w / multiple;
                resizeH = h / multiple; 
            }else{
                resizeW = w;
                resizeH = h;
            }
            let canvas = document.createElement("canvas"),
                ctx = canvas.getContext('2d');
            //ios手机拍照会旋转90度,这里做处理
            if(window.navigator.userAgent.indexOf('iphone') > 0){
                canvas.width = resizeH;
                canvas.height = resizeW;
                ctx.retate(90 * Math.PI / 180);
                ctx.drawImage(Img,0,-resizeH,resizeW,resizeH);
            }else{
                canvas.width = resizeW;
                canvas.height = resizeH;
                ctx.drawImage(Img,0,0,resizeW,resizeH);
            }
            that.base64 = canvas.toDataURL('image/jpeg',maxSize.level);
            that.$http.post('/hnwfx/setDaoGouInfo',{file:that.base64},{'headers':{'Content-Type':'application/json'}}).then(function(res){
                that.update_img = false;
                that.img_cro_model = false;
                that.set_head = that.base64;
            }); 
        }
    }
  }
}
</script>

<style scoped src="./seting.css"></style>
@charset "utf-8";

.index_seting .set_center{
	width:100%;
	background-color: #fff;
}
.index_seting .set_center li{
	position: relative;
}
.set_center li .set_item{
	display: block;
	margin: 0 0.426667rem;
	overflow: hidden;
	background: url(./arrow.png) right center no-repeat transparent;
	background-size: 4% auto;
}
.set_center li .set_item .head_lab{
	width:100%;
	height: 100%;
	display: block;
	overflow: hidden;
}
.set_center li .set_item span{
	position: absolute;
	right:1.408rem;
	font-size: 0.554667rem;
	color:#666;
	display: inline-block;
}
.set_center li .set_item .head_img{
	width:2.730667rem;
	height: 2.730667rem;
	display: inline-block;
	margin:0.362667rem 0;
    border-radius: 50%;
    overflow: hidden;
}
.set_center li .set_item .head_img img{
	width:100%;
	height: 100%;
}
.index_seting .set_center li h3{
	float:left;
	font-size: 0.597333rem;
	font-weight: normal;
	color:#000;
}
.index_seting .set_center li:after{
    position:absolute;
    bottom:-1px;
    left:0px;
    content:'';
    width:100%;
    height:1px;
	border-top:1px solid #e4e4e4; 
    -webkit-transform:scaleY(0.5);
}
.set_center .set_head_img{
	line-height: 3.456rem;
}
.img-view{
	width:100%;
	height: 100%;
	position: fixed;
	bottom:0;
	background: rgba(0, 0, 0, 1);
	z-index: 1000;
}
.gif_loading{
	width:6.4rem;
	height: 4.266667rem;
	position: fixed;
	top:50%;
	left:50%;
	margin-top: -2.133333rem;
	margin-left: -3.2rem;
	background-color: #fff;
	border-radius: 10px;
	text-align: center;
	box-shadow: 0px 0px 1px 1px #e6e6e6;
}
.gif_loading p{
	margin-top:1.066667rem;
	font-size: 0.64rem;
}
.gif_loading span{
	display: inline-block;
	width:66px;
	height: 6px;
	background:url(./seting01.gif) center center no-repeat;
	background-size: 100% auto;
}
.img_btn{
	width:100%;
	line-height: 2rem;
	font-size: 0.64rem;
	color:#fff;
	position: fixed;
	bottom: 0;
	z-index:1000;
}
.img_btn span{
	float:left;
	width:50%;
	text-align: center;
}



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
要实现Vue图片裁剪上传,可以使用vue-cropper组件。以下是一个简单的实现过程: 1. 首先,在Vue项目中安装vue-cropper组件。可以使用npm或yarn来安装,命令如下: ``` npm install vue-cropper ``` 2. 在需要使用图片裁剪上传的组件中,引入vue-cropper组件。可以在组件的template中添加以下代码: ```html <template> <div> <vue-cropper ref="cropper" :src="imageSrc" :guides="true" :view-mode="1" :auto-crop-area="0.8" ></vue-cropper> <button @click="cropImage">裁剪并上传</button> </div> </template> ``` 3. 在组件的script部分,添加必要的代码。首先,引入vue-cropper组件: ```javascript import VueCropper from 'vue-cropper' ``` 然后,在components中注册vue-cropper组件: ```javascript components: { VueCropper }, ``` 接下来,定义data中的imageSrc属性,用于展示需要裁剪的图片: ```javascript data() { return { imageSrc: '图片路径' } }, ``` 4. 实现裁剪并上传功能。在methods中,定义cropImage方法: ```javascript methods: { cropImage() { const cropper = this.$refs.cropper const imageData = cropper.getCroppedCanvas().toDataURL('image/jpeg') // 将imageData发送到后端进行上传处理 // ... } }, ``` 在cropImage方法中,通过this.$refs.cropper获取vue-cropper组件实例,并使用getCroppedCanvas方法获取裁剪后的图片数据。最后,将图片数据发送到后端进行上传处理。 这样,就实现了Vue图片裁剪上传的功能。你可以根据具体的需求,自定义vue-cropper组件的属性和方法,来实现更多的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值