import fs from "fs" ; import path from "path" ; import { RandomUtil } from "../utils/RandomUtil" ; import { TaskConfig } from "./TaskConfig" ; import { TaskInterface } from "./TaskInterface" ; enum ImageType { PNG , JPG , JPEG , GIF , WEBP } type ImageObject = { /**
     * 图片类型
     */ type : ImageType ; /**
     * 图片路径
     */ filePath : string ; } ; export class ImageEncryptTask implements TaskInterface { param taskConfig handle ( taskConfig ) { let imgs = [ ] ; this . _collectImageFilePaths ( taskConfig . buildOutputResDirPath , imgs ) ; console . log ( `图片处理：找到 ${ imgs . length } 张原始图片` ) ; this . _encryptImage ( imgs ) ; console . log ( `图片处理：${ imgs . length } 张原始图片已加密完成` ) ; } param dirName param imgs private _collectImageFilePaths ( dirName , imgs ) { if ( ! fs . existsSync ( dirName ) ) { throw new Error ( `${ dirName } 目录不存在` ) ; } let files = fs . readdirSync ( dirName ) ; files . forEach ( ( fileName ) => { let filePath = path . join ( dirName , fileName . toString ( ) ) ; let stat = fs . statSync ( filePath ) ; if ( stat . isDirectory ( ) ) { this . _collectImageFilePaths ( filePath , imgs ) ; } else { let fileExtName = path . extname ( filePath ) ; switch ( fileExtName ) { case ".png" : imgs . push ( { type : ImageType . PNG , filePath : filePath , } ) ; break ; case ".jpg" : imgs . push ( { type : ImageType . JPG , filePath : filePath , } ) ; break ; case ".jpeg" : imgs . push ( { type : ImageType . JPEG , filePath : filePath , } ) ; case ".gif" : imgs . push ( { type : ImageType . GIF , filePath : filePath , } ) ; case ".webp" : imgs . push ( { type : ImageType . WEBP , filePath : filePath , } ) ; break ; } } } ) ; } /**
     * 加密图片
     */ private _encryptImage ( imgs ) { imgs . forEach ( ( imgObj ) => { let imgBuffer = fs . readFileSync ( imgObj . filePath ) ; if ( imgBuffer . toString ( ) . startsWith ( "data" ) ) { return ; } let imgBase64String = "" ; switch ( imgObj . type ) { case ImageType . PNG : imgBase64String += "data:image/png;base64," ; break ; case ImageType . JPG : imgBase64String += "data:image/jpg;base64," ; break ; case ImageType . JPEG : imgBase64String += "data:image/jpeg;base64," ; break ; case ImageType . GIF : imgBase64String += "data:image/gif;base64," ; break ; case ImageType . WEBP : imgBase64String += "data:image/webp;base64," ; break ; } imgBase64String += imgBuffer . toString ( "base64" ) ; imgBase64String += RandomUtil . randomString ( 10 ) ; fs . writeFileSync ( imgObj . filePath , imgBase64String ) ; } ) ; } }