序言
????最近接到一個需求,要求前端把圖片壓縮在傳給后端,并且要將圖片轉換為jpg格式的。經過百度查詢了很多方法,都不是很理想。最后還是通過組件來實現了。
首先是原生的方法 (不推薦)
????這個方法對于僅僅有jpg圖片的項目很是好用,而且十分方便,原理就是通過傳進來的圖片的file流文件,用canvas來繪制出來,返回出來的b64格式的文件,在把其本身處理為file流。在發(fā)送給后端就好了。
/**
* @desc:前端實現圖片壓縮
* @desc:只對jpg圖片生效-對PNG圖片效果甚微
*/
function dataURLtoFile( urlData, fileName ) {
let arr = urlData.split( ',' );
let mime = 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: mime } );
}
//壓縮圖片
function compressImg( file ) {
//支持壓縮的格式
const reg = /\.(png|jpg|gif|jpeg|webp|PNG|JPG|JPEG)$/
//(reg.test( file.name ) )
if ( reg.test( file.name ) ) {
var name = file.name
var src
var files
var fileSize = parseFloat( parseInt( file[ 'size' ] ) / 1024 / 1024 ).toFixed( 2 );
var read = new FileReader()
read.readAsDataURL( file )
return new Promise( function ( resolve, reject ) {
read.onload = function ( e ) {
var img = new Image();
img.src = e.target.result;
img.onload = function () {
//默認按比例壓縮
var w = this.width,
h = this.height;
//生成canvas
var canvas = document.createElement( 'canvas' );
var ctx = canvas.getContext( '2d' );
var base64;
// 創(chuàng)建屬性節(jié)點
canvas.setAttribute( "width", w );
canvas.setAttribute( "height", h );
ctx.drawImage( this, 0, 0, w, h );
if ( fileSize ) {
//所有圖片壓縮一半
base64 = canvas.toDataURL( file[ 'type' ],0.1);
}
// 回調函數返回file的值(將base64編碼轉成file)
files = dataURLtoFile( base64, name ); //如果后臺接收類型為base64的話這一步可以省略
// 以服務的方式調用的 Loading 需要異步關閉
// setTimeout( () => {
// loadingInstance.close()
// }, 500 )
//("files",files)
resolve( files )
}
}
} )
}
else {
return new Promise( function ( resolve, reject ) {
// setTimeout( () => {
// loadingInstance.close()
// }, 500 )
resolve( file )
} )
}
};
//結尾處將該方法暴露出來供外部調用
export default {
compressImg,
}
//使用方式 回調的方式使用其方法
this.$compressImage.compressImg(file)
.then(res=> { // res為壓縮后二進制文件
console.log(res)
})
其次是組件的方法 (推薦)
????組件的方法就很簡單,也很好用,同時支持png和jpg格式的圖片,不管是什么圖都可以壓縮為對應比例的大小。組件名字為imageConversion
- 安裝
??npm i image-conversion --save - 引入
// 圖片壓縮
//引入組件
import * as imageConversion from 'image-conversion'
//注冊組件
Vue.prototype.$imageConversion = imageConversion
//圖片驗證方法
Vue.prototype.$ImgCompress = ImgCompress
//圖片壓縮比計算方法
Vue.prototype.$ImgFormat = ImgFormat
//將png圖片轉換為jpg圖片 拋出file流文件
Vue.prototype.$PngGoImg = PngGoImg
//將png圖片名字轉換為jpg圖片名字 拋出轉換好的名字
Vue.prototype.$PngGoImgB = PngGoImgB
/**
* @desc:圖片壓縮相關方法
*/
//圖片壓縮比計算。 傳入圖片原sizi大小 與b 計算 算出其百分比大小,拋出告訴組件不可超過其百分比大小
export function ImgCompress( a, b = 0.3 ) {
return Math.ceil( a / 1024 ) * b < 300 ? 300 : Math.ceil( a / 1024 ) * b
}
//圖片格式滿足則拋出 true 否則拋出 false
export function ImgFormat( a ) {
const reg = /\.(png|jpg|jpeg)$/
return reg.test( a.toLowerCase() )
}
//PNG轉換jpg并且拋出轉換完成的file流 若非png則直接拋出file
export function PngGoImg( a ) {
let e = a.name.substring( a.name.length - 4 )
if ( e.toLowerCase() === '.png' ) {
let b = a.name.substring( 0, a.name.length - 4 )
let c = b + '.jpg'
let d = new File( [ a ], c, {
type: a.type,
lastModified: Date.now(),
} )
return d
} else {
return a
}
}
//PNG轉換jpg并且拋出轉換完成的圖片Name 若非png 則直接拋出圖片Name
export function PngGoImgB( a ) {
let e = a.substring( a.length - 4 )
if ( e.toLowerCase() === '.png') {
let b = a.substring( 0, a.length - 4 )
let c = b + '.jpg'
return c
} else {
return a
}
}
- 使用
//在圖片上傳之前執(zhí)行此方法
beforeUpload(imgfile) {
//第一步把拿到的圖片是png的圖片的file流轉換為jpg的圖片。
let file = this.$PngGoImg(imgfile)
//判斷其是否為圖片,不是圖片則不執(zhí)行圖片壓縮
if (this.$ImgFormat(file.name)) {
return new Promise((resolve, reject) => {
//異步回調的方式將圖片的file流及圖片的壓縮比傳進組件內部
this.$imageConversion.compressAccurately(file, this.$ImgCompress(file.size))
.then((res) => {
res = new File([res], file.name, {
type: res.type,
lastModified: Date.now(),
})
//res就是轉換并且壓縮過的圖片
}
})
})
} else {
//直接拋出文件的file流
}
},
更新于2021-03-25-13點48分