前言

也是很少来写博客了,也是赖吧,哈哈

最近新的进度里有上传图片太大,需要前台进行图片压缩问题,然后查阅了相关资料

上传图片大于100* 1024 的用canvas 来压缩来解决

然后IOS拍照上传会有图片旋转的问题,然后用了github 上的exif.js很好的插件,项目里面npm install exif-js --save   安装,

然后import一下就可以使用了,来看看代码吧

HTML+CSS+JS  Vue的组件代码

<template>
<div>
<div style="padding:20px;">
<div class="show">
<div class="picture" :style="'backgroundImage:url('+headerImage+')'"></div>
</div>
<div style="margin-top:20px;">
<input type="file" id="upload" accept="image" @change="upload">
<label for="upload"></label>
</div>
</div>
</div>
</template> <script>
import Exif from 'exif-js' export default {
data () {
return {
headerImage:'',picValue:''
}
},
mounted () {
},
methods: {
upload (e) {
let files = e.target.files || e.dataTransfer.files;
if (!files.length) return;
this.picValue = files[];
this.imgPreview(this.picValue);
},
imgPreview (file) {
let self = this;
let Orientation;
//去获取拍照时的信息,解决拍出来的照片旋转问题
Exif.getData(file, function(){
Orientation = Exif.getTag(this, 'Orientation');
});
// 看支持不支持FileReader
if (!file || !window.FileReader) return; if (/^image/.test(file.type)) {
// 创建一个reader
let reader = new FileReader();
// 将图片2将转成 base64 格式
reader.readAsDataURL(file);
// 读取成功后的回调
reader.onloadend = function () {
let result = this.result;
let img = new Image();
img.src = result;
//判断图片是否大于100K,是就直接上传,反之压缩图片
if (this.result.length <= ( * )) {
self.headerImage = this.result;
self.postImg();
}else {
img.onload = function () {
let data = self.compress(img,Orientation);
self.headerImage = data;
self.postImg();
}
}
}
}
},
postImg () {
//这里写接口
},
rotateImg (img, direction,canvas) {
//最小与最大旋转方向,图片旋转4次后回到原方向
const min_step = ;
const max_step = ;
if (img == null)return;
//img的高度和宽度不能在img元素隐藏后获取,否则会出错
let height = img.height;
let width = img.width;
let step = ;
if (step == null) {
step = min_step;
}
if (direction == 'right') {
step++;
//旋转到原位置,即超过最大值
step > max_step && (step = min_step);
} else {
step--;
step < min_step && (step = max_step);
}
//旋转角度以弧度值为参数
let degree = step * * Math.PI / ;
let ctx = canvas.getContext('2d');
switch (step) {
case :
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, , );
break;
case :
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, , -height);
break;
case :
canvas.width = width;
canvas.height = height;
ctx.rotate(degree);
ctx.drawImage(img, -width, -height);
break;
case :
canvas.width = height;
canvas.height = width;
ctx.rotate(degree);
ctx.drawImage(img, -width, );
break;
}
},
compress(img,Orientation) {
let canvas = document.createElement("canvas");
let ctx = canvas.getContext('2d');
//瓦片canvas
let tCanvas = document.createElement("canvas");
let tctx = tCanvas.getContext("2d");
let initSize = img.src.length;
let width = img.width;
let height = img.height;
//如果图片大于四百万像素,计算压缩比并将大小压至400万以下
let ratio;
if ((ratio = width * height / ) > ) {
console.log("大于400万像素")
ratio = Math.sqrt(ratio);
width /= ratio;
height /= ratio;
} else {
ratio = ;
}
canvas.width = width;
canvas.height = height;
// 铺底色
ctx.fillStyle = "#fff";
ctx.fillRect(, , canvas.width, canvas.height);
//如果图片像素大于100万则使用瓦片绘制
let count;
if ((count = width * height / ) > ) {
console.log("超过100W像素");
count = ~~(Math.sqrt(count) + ); //计算要分成多少块瓦片
// 计算每块瓦片的宽和高
let nw = ~~(width / count);
let nh = ~~(height / count);
tCanvas.width = nw;
tCanvas.height = nh;
for (let i = ; i < count; i++) {
for (let j = ; j < count; j++) {
tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, , , nw, nh);
ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
}
}
} else {
ctx.drawImage(img, , , width, height);
}
//修复ios上传图片的时候 被旋转的问题
if(Orientation != "" && Orientation != ){
switch(Orientation){
case ://需要顺时针(向左)90度旋转
this.rotateImg(img,'left',canvas);
break;
case ://需要逆时针(向右)90度旋转
this.rotateImg(img,'right',canvas);
break;
case ://需要180度旋转
this.rotateImg(img,'right',canvas);//转两次
this.rotateImg(img,'right',canvas);
break;
}
}
//进行最小压缩
let ndata = canvas.toDataURL('image/jpeg', 0.1);
console.log('压缩前:' + initSize);
console.log('压缩后:' + ndata.length);
console.log('压缩率:' + ~~( * (initSize - ndata.length) / initSize) + "%");
tCanvas.width = tCanvas.height = canvas.width = canvas.height = ;
return ndata;
},
}
}
</script> <style>
*{
margin: ;
padding: ;
}
.show {
width: 100px;
height: 100px;
overflow: hidden;
position: relative;
border-radius: %;
border: 1px solid #d5d5d5;
}
.picture {
width: %;
height: %;
overflow: hidden;
background-position: center center;
background-repeat: no-repeat;
background-size: cover;
}
</style>

Vue 上传图片压缩 的问题的更多相关文章

  1. js/vue图片压缩

    js版 新建compressImage.js,内容如下: // 将base64转换为blob(有需要可加上,没需要可不加) function convertBase64UrlToBlob(urlDat ...

  2. layui中实现上传图片压缩

    一.关于js上传图片压缩的方法,百度有很多种方法,这里我参考修改了一下: function photoCompress(file, w, objDiv) { var ready = new FileR ...

  3. .netcore+vue 实现压缩文件下载

    一.前言 目前接触的项目中,给定的需求是将系统内所有用户的数据整理好,并保存到文件夹内,目的主要是防止用户在实施人员已配置好的基础上由于不熟悉系统,导致的误删或者误操作.减少实施人员的配置工作.我首先 ...

  4. vue上传图片 base64+canvas压缩图片

    这是先将图片 base64转码 在拿canvas压缩的

  5. vue 上传图片视频组件,可拍照选择照片,解决苹果手机拍照旋转问题

    1.创建组件components > uploadImg > index.vue <template> <input type="file" name ...

  6. Vue 图片压缩上传: element-ui + lrz

    步骤 安装依赖包 npm install --save lrz 在main.js里引入 import lrz from 'lrz' 封装 compress函数 封装上传组件 upload-image ...

  7. Vue上传图片预览组件

    父组件: <template> <div> <h4>基于Vue.2X的html5上传图片组件</h4> <div style="widt ...

  8. java 上传图片压缩

    public static void uploadFile(MultipartFile multfile, String filePath) throws Exception { File targe ...

  9. axios上传图片(及vue上传图片到七牛))

    浏览器上传图片到服务端,我用过两种方法: 1.本地图片转换成base64,然后通过普通的post请求发送到服务端. 操作简单,适合小图,以及如果想兼容低版本的ie没办法用此方法 2.通过form表单提 ...

随机推荐

  1. Python学习笔记:(十二)输入输出

    一.格式化输出 1.str.format()函数,格式化输出值 2.将输出值转变为字符串,可以使用repr()和str() str()函数将返回一个易读的表达式形式: repr()返回一个解释器易读的 ...

  2. linux配置多个ip

    linux配置多个ip /sbin/ifconfig eth0:1 172.19.121.180 broadcast 172.19.121.255  netmask 255.255.255.0 up ...

  3. wpf passwordbox控件 光标移到最后

    /// <summary> /// 设置光标位置 /// </summary> /// <param name="passwordBox">&l ...

  4. Install the Flash plug-in

    Flash is a plug-in for your web browser that allows you to watch videos and use interactive web page ...

  5. centos7 忘记root密码,如何进入单用户模式。

    init方法 1.centos7的grub2界面会有两个入口,正常系统入口和救援模式: 2.修改grub2引导 在正常系统入口上按下"e",会进入edit模式,搜寻ro那一行,以l ...

  6. 原生js之addEventListener,removeEventListener

    使用addEventListener添加事件 <!DOCTYPE html> <html lang="en"> <head> <meta ...

  7. Express全系列教程之(十一):渲染ejs模板引擎

    一.简介 相比于jade模板引擎,ejs对原HTML语言就未作出结构上的改变,只不过在其交互数据方面做出了些许修改,相比于jade更加简单易用.因此其学习成本是很低的.您也可参考ejs官网:https ...

  8. Logistic回归实战篇之预测病马死亡率

    利用sklearn.linear_model.LogisticRegression训练和测试算法. 示例代码: import numpy as np import matplotlib.pyplot ...

  9. 20191128 Spring Boot官方文档学习(10)

    10.附录 附录A:通用应用程序属性 附录B:配置元数据 附录C:自动配置类 附录D:测试的自动配置注释 附录E:可执行的Jar格式 附录F:依赖版本

  10. NameNode格式化后HBase创建新表提示旧表已存在:table already exists

    1.问题出现: 在格式化NameNode后,集群上安装的OpenTSDB的表(存在hbase中)都没有了,重新运行OpenTSDB预创建表步骤报错显示table already exists 2.原因 ...