[點晴永久免費OA]【JavaScript】JS壓縮圖片
當(dāng)前位置:點晴教程→點晴OA辦公管理信息系統(tǒng)
→『 經(jīng)驗分享&問題答疑 』
/*
* 圖片壓縮
* img 原始圖片
* width 壓縮后的寬度
* height 壓縮后的高度
* ratio 壓縮比率
*/
function compress(img, width, height, ratio) {
var canvas, ctx, img64;
canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
img64 = canvas.toDataURL("image/jpeg", ratio);
return img64;
}123456789101112131415161718192021
<input type="file" accept="image/*" name="imageFile" @change="upload">1 upload () {
let file = document.queryselector('input[type=file]').files[0] // 獲取選擇的文件,這里是圖片類型
let reader = new FileReader()
reader.readAsDataURL(file) //讀取文件并將文件以URL的形式保存在resulr屬性中 base64格式
reader.onload = (e) => { // 文件讀取完成時觸發(fā)
let result = e.target.result // base64格式圖片地址
var image = new Image()
image.src = result // 設(shè)置image的地址為base64的地址
image.onload = () => { // 圖片加載完成后才能進(jìn)行壓縮處理,從而轉(zhuǎn)換為base64 進(jìn)行賦值
let width = image.width // 圖片寬度
let height = image.height let dataUrl = this.compress(image, width, height, 0.7)
document.getElementById("test").src = dataUrl }
}
}12345678910111213141516
<template>
<div>
<input type="file" accept="image/*" name="imageFile" @change="upload">
<img id="test" crossorigin alt="">
</div></template><script>export default {
name: '',
data () {
return {
}
},
components: {
},
created () {
},
methods: {
upload () {
let file = document.queryselector('input[type=file]').files[0] // 獲取選擇的文件,這里是圖片類型
let reader = new FileReader()
reader.readAsDataURL(file) //讀取文件并將文件以URL的形式保存在resulr屬性中 base64格式
reader.onload = (e) => { // 文件讀取完成時觸發(fā)
let result = e.target.result // base64格式圖片地址
var image = new Image()
image.src = result // 設(shè)置image的地址為base64的地址
image.onload = () => { // 圖片加載完成后才能進(jìn)行壓縮處理,從而轉(zhuǎn)換為base64 進(jìn)行賦值
let width = image.width // 圖片寬度
let height = image.height let dataUrl = this.compress(image, width, height, 0.7)
document.getElementById("test").src = dataUrl }
}
},
/*
* 圖片壓縮
* img 原始圖片
* width 壓縮后的寬度
* height 壓縮后的高度
* ratio 壓縮比率
*/
compress (img, width, height, ratio) {
let canvas, ctx, img64;
canvas = document.createElement('canvas')
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
img64 = canvas.toDataURL("image/jpeg", ratio);
return img64;
}
}}</script><style lang="less" scoped></style>
該文章在 2023/5/6 12:40:23 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |