当前位置:网站首页>纯js 实现图片压缩,并返回file图片信息
纯js 实现图片压缩,并返回file图片信息
2022-06-10 03:12:00 【寒墨茗殇】
压缩方法:
1.先将file通过FileReader 转换为base64格式
2.通过canvas绘制图片,并通过canvas.toDataUR()降低图片质量
3.base64转成blod格式文件
4.blod格式文件转成file格式并返回
/*
*file:文件的file
*obj配置 {quality:0.2}压缩比例
*callback 回调
*/
compressImg(file, obj, callback) {
let _this = this;
var ready = new FileReader();
/*开始读取指定的Blob对象或File对象中的内容.
当读取操作完成时,readyState属性的值会成为DONE,
如果设置了onloadend事件处理程序,则调用之.
同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
ready.readAsDataURL(file);
ready.onload = function () {
var path = this.result;
// ↓压缩
var img = new Image();
img.src = path;
img.onload = function () {
var that = this;
// 默认按比例压缩
var w = that.width,
h = that.height,
scale = w / h;
w = obj.width || w;
h = obj.height || w / scale;
var quality = 0.7; // 默认图片质量为0.7
//生成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(that, 0, 0, w, h);
// 图像质量
if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
quality = obj.quality;
}
// quality值越小,所绘制出的图像越模糊
var base64 = canvas.toDataURL("image/jpeg", quality);
// 转换为Blob数据
var BlobData=_this.convertBase64UrlToBlob(base64)
// 转换为file数据
let this_file = new File(
[BlobData],
file.name,
);
// 回调函数返回file的值
callback(this_file);
// ↑压缩
};
};
},
// 转换为Blob数据方法
convertBase64UrlToBlob(urlData) {
var arr = urlData.split(","),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
},
使用:
<template>
<span class="upload_span" @click="uploadFn">
<input
ref="upload"
@change="uploadChange"
style="display: none"
type="file"
:accept="acceptString"
/>
<slot></slot>
</span>
</template>
<script>
export default {
methods:{
uploadChange(e) {
let dom = e.currentTarget;
let files = dom.files;
//使用压缩,方法在上面的代码块
this.compressImg(
files[0],
{
quality: 0.2,
},
(res) => {
console.log(res,'返回的压缩图片的file')
}
);
},
uploadFn() {
this.$refs["upload"].click();
},
}
};
</script>
<style>
.upload_span{
width:100px;
height:100px;
border:1px solid #000
}
</style>案例:

边栏推荐
- 洛谷 P2678 跳石头
- Numpy use
- The hcie Routing & switching test is postponed to December 31, 2022
- Multithreaded usage scenarios
- How to hack user code gracefully
- 张量(tensor)编程
- Sword finger offer 24 Reverse linked list
- Luogu p1902 assassinating Ambassador (two points | BFS)
- 修改pycharm缓存文件路径
- P1082 [noip2012 improvement group] congruence equation
猜你喜欢

How to extract public dependency Libraries

TS 23.122

Huawei Hubble will add another IPO, and Maxon will rush to the scientific innovation board after more than ten years of dormancy

Self taught scaffold - "data driven science and Engineering" by Steven L. Brunton (Chapter 5.0 - 5.4)

Domestic cosmetics, lost 618

修改pycharm缓存文件路径

Tensorflow. Mobilenet for getting started with JS

Cmake record

Why is the denominator of sample variance n-1 (unbiased estimation)?

Tidb experience sharing 02
随机推荐
Don't pretend to miss the Kindle
修改pycharm缓存文件路径
Sword finger offer 30 Stack containing min function
C # extension method (this in the method parameter)
取消打印Tensorflow中的无用信息,如tensorflow:AutoGraph could not transform <*> and will run it as-is、加载CUDA信息等
1px问题
P1516 青蛙的约会(扩欧)
Why is the denominator of sample variance n-1 (unbiased estimation)?
使用webdriver时不显示浏览器运行
Degraded judge (European expansion + enumeration)
switch case语法
Halodoc's key experience in building Lakehouse using Apache Hudi
Detailed explanation of redis iterative query and its use: scan command, sscan command, hscan command and zscan command
Multithreaded usage scenarios
如何区分对象自身的属性以及原型上的属性
修改谷歌浏览器Google Chrome缓存位置
Tensorflow.js入门之mobilenet
Shift+ right mouse button No: Open command window here
1110 区块反转
FPGA 可以双目以及单目运算