直接拿去用
/**
* 图片压缩工具
*/
import { image } from '@kit.ImageKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { buffer, util } from '@kit.ArkTS';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileIo } from '@kit.CoreFileKit';
import { promptAction } from '@kit.ArkUI';
import { common } from '@kit.AbilityKit';
export class ImageUtils {
/**
* 图片压缩 先缩放后质量压缩
* @param pixelMap
* @param success
* @param error
* @param maxWidth
* @param maxHeight
* @param quality
* @returns
*/
static compress(
pixelMap: image.PixelMap | undefined,
success: (pixelMap: image.PixelMap) => void,
error: (err: BusinessError) => void = () => {
},
maxWidth: number = 540,
maxHeight: number = 960,
quality: number = 80,
) {
if (pixelMap != undefined) {
ImageUtils.scaleCompress(pixelMap, (scaleCompressPixelMap: image.PixelMap) => {
ImageUtils.packingCompress(scaleCompressPixelMap, (compressPixelMap: image.PixelMap) => {
success(compressPixelMap)
}, (err: BusinessError) => {
console.error(`compress packingCompress 失败。 code:${err.code}, message:${err.message}`);
error(err)
}, quality)
}, (err: BusinessError) => {
console.error(`compress scaleCompress 失败。 code:${err.code}, message:${err.message}`);
error(err)
}, maxWidth, maxHeight)
} else {
console.error(`compress 失败:pixelMap == undefined`);
error({
code: -1,
name: '压缩失败',
message: 'pixelMap = undefined'
})
}
}
/**
* 图片压缩 先缩放后质量压缩
* @param filePath
* @param success
* @param error
* @param maxWidth
* @param maxHeight
* @param quality
* @returns
*/
static compressUri(
filePath: string,
success: (pixelMap: image.PixelMap) => void,
error: (err: BusinessError) => void = () => {
},
maxWidth: number = 540,
maxHeight: number = 960,
quality: number = 80,
) {
if (filePath) {
const imageSourceApi: image.ImageSource = image.createImageSource(filePath);
let packOpts: image.PackingOption = { format: "image/jpeg", quality: quality };
const imagePackerApi: image.ImagePacker = image.createImagePacker();
imagePackerApi.packing(imageSourceApi, packOpts, (err: BusinessError, data: ArrayBuffer) => {
if (err) {
console.error(`compressUri packing 失败。 code:${err.code}, message:${err.message}`);
error(err)
} else {
console.info(`compressUri packing 压缩成功 size:${data.byteLength}}`);
ImageUtils.toPixelMap(data, (compressPixelMap: image.PixelMap) => {
ImageUtils.scaleCompress(compressPixelMap, (scaleCompressPixelMap: image.PixelMap) => {
ImageUtils.packingCompress(scaleCompressPixelMap, (compressPixelMap: image.PixelMap) => {
success(compressPixelMap)
}, (err: BusinessError) => {
console.error(`compressUri packingCompress 失败。 code:${err.code}, message:${err.message}`);
error(err)
}, quality)
}, (err: BusinessError) => {
console.error(`compressUri scaleCompress 失败。 code:${err.code}, message:${err.message}`);
error(err)
}, maxWidth, maxHeight)
}, (err: BusinessError) => {
console.error(`compressUri toPixelMap 失败。 code:${err.code}, message:${err.message}`);
error(err)
})
}
imagePackerApi.release()
})
} else {
console.error(`compressUri 失败:pixelMap == undefined`);
error({
code: -1,
name: '压缩失败',
message: 'pixelMap = undefined'
})
}
}
/**
* packing图片压缩
* @param pixelMap
* @param success
* @param error
* @param quality
* @returns
*/
static packingCompress(
pixelMap: image.PixelMap | undefined,
success: (pixelMap: image.PixelMap) => void,
error: (err: BusinessError) => void = () => {
},
quality: number = 0,
) {
if (pixelMap != undefined) {
let packOpts: image.PackingOption = { format: "image/jpeg", quality: quality };
const imagePackerApi: image.ImagePacker = image.createImagePacker();
imagePackerApi.packing(pixelMap, packOpts, (err: BusinessError, data: ArrayBuffer) => {
if (err) {
console.error(`packingCompress packing 失败。 code:${err.code}, message:${err.message}`);
error(err)
} else {
console.info(`packingCompress packing 压缩成功 size:${data.byteLength}}`);
ImageUtils.toPixelMap(data, (compressPixelMap: image.PixelMap) => {
success(compressPixelMap)
}, (err: BusinessError) => {
console.error(`packingCompress toPixelMap 失败。 code:${err.code}, message:${err.message}`);
error(err)
})
}
})
imagePackerApi.release()
} else {
console.error(`packingCompress 失败:pixelMap == undefined`);
error({
code: -1,
name: '压缩失败',
message: 'pixelMap = undefined'
})
}
return pixelMap
}
/**
* packing图片压缩
* @param filePath
* @param success
* @param error
* @param quality
*/
static packingCompressUri(
filePath: string,
success: (pixelMap: image.PixelMap) => void,
error: (err: BusinessError) => void = () => {
},
quality: number = 0,
) {
if (filePath) {
const imageSourceApi: image.ImageSource = image.createImageSource(filePath);
let packOpts: image.PackingOption = { format: "image/jpeg", quality: quality };
const imagePackerApi: image.ImagePacker = image.createImagePacker();
imagePackerApi.packing(imageSourceApi, packOpts, (err: BusinessError, data: ArrayBuffer) => {
if (err) {
console.error(`packingCompressUri packing 失败。 code:${err.code}, message:${err.message}`);
error(err)
} else {
console.info(`packingCompressUri packing 压缩成功 size:${data.byteLength}}`);
ImageUtils.toPixelMap(data, (compressPixelMap: image.PixelMap) => {
success(compressPixelMap)
}, (err: BusinessError) => {
console.error(`packingCompressUri toPixelMap 失败。 code:${err.code}, message:${err.message}`);
error(err)
})
}
imagePackerApi.release()
})
}
}
/**
* 图片缩放(分辨率)压缩
* @param pixelMap
* @param success
* @param error
* @param maxWidth
* @param maxHeight
*/
static scaleCompress(
pixelMap: image.PixelMap,
success: (pixelMap: image.PixelMap) => void,
error: (err: BusinessError) => void = () => {
},
maxWidth: number = 540,
maxHeight: number = 960,
) {
pixelMap.getImageInfo().then((value: image.ImageInfo) => {
let size = value.size
let widthScale = maxWidth / size.width;
let heightScale = maxHeight / size.width;
let scale = Math.min(widthScale, heightScale);
pixelMap.scale(scale, scale).then(() => {
console.info('scaleCompress scale 压缩成功');
success(pixelMap)
}).catch((err: BusinessError) => {
console.error(`scaleCompress scale 失败。 code:${err.code}, message:${err.message}`);
error(err)
});
}).catch((err: BusinessError) => {
console.error(`scaleCompress getImageInfo 失败。 code:${err.code}, message:${err.message}`);
error(err)
});
}
/**
* ArrayBuffer转PixelMap
* @param data
* @param callback
*/
static toPixelMap(
data: ArrayBuffer,
success: (pixelMap: image.PixelMap) => void,
error: (err: BusinessError) => void = () => {
},
) {
let source: image.ImageSource = image.createImageSource(data)
source.createPixelMap().then((pixelMap: image.PixelMap) => {
console.error(`toPixelMap 成功`);
success(pixelMap)
}).catch((err: BusinessError) => {
console.error(`toPixelMap 失败。 code:${err.code}, message:${err.message}`);
error(err)
});
}
/**
* PixelMap转ArrayBuffer
* @param pixelMap
* @param success
* @param error
*/
static toArrayBuffer(
pixelMap: image.PixelMap | undefined,
success: (data: ArrayBuffer) => void,
error: (err: BusinessError) => void = () => {
},
) {
if (pixelMap != undefined) {
let packOpts: image.PackingOption = { format: "image/jpeg", quality: 100 };
const imagePackerApi: image.ImagePacker = image.createImagePacker();
imagePackerApi.packing(pixelMap, packOpts, (err: BusinessError, data: ArrayBuffer) => {
if (err) {
console.error(`toArrayBuffer packing 失败:ode:${err.code},message:${err.message}`);
error(err)
} else {
console.info('toArrayBuffer packing 成功');
success(data)
}
})
} else {
console.error(`toArrayBuffer 失败:pixelMap == undefined`);
error({
code: -1,
name: '转换错误',
message: 'pixelMap = undefined'
})
}
}
/**
* 转Base64
* @param pixelMap
* @param success
* @param error
*/
static toBase64(
pixelMap: image.PixelMap | undefined,
success: (data: string) => void,
error: (err: BusinessError) => void = () => {
},
quality: number = 100,
) {
if (pixelMap != undefined) {
let packOpts: image.PackingOption = { format: "image/jpeg", quality: quality };
const imagePackerApi: image.ImagePacker = image.createImagePacker();
imagePackerApi.packing(pixelMap, packOpts, (err: BusinessError, data: ArrayBuffer) => {
if (err) {
console.error(`toBase64 packing 失败:ode:${err.code},message:${err.message}`);
error(err)
} else {
console.info('toBase64 packing 成功');
let buf: buffer.Buffer = buffer.from(data);
let base64 = 'data:image/jpeg;base64,' + buf.toString('base64', 0, buf.length);
success(base64)
}
})
} else {
console.error(`toBase64 失败:pixelMap == undefined`);
error({
code: -1,
name: '转换错误',
message: 'pixelMap = undefined'
})
}
}
/**
* base64转PixelMap
* @param base64
* @returns
*/
static base64ToPixelMap(
base64: string,
success: (pixelMap: image.PixelMap) => void,
error: (err: BusinessError) => void = () => {
},
) {
let helper = new util.Base64Helper();
// 转换成buffer数组
let buffer: ArrayBuffer = helper.decodeSync(base64, util.Type.MIME).buffer as ArrayBuffer;
// 创建imageSource
let imageSource = image.createImageSource(buffer);
let opts: image.DecodingOptions = { editable: true };
// 创建PixelMap
imageSource.createPixelMap(opts).then((pixelMap: image.PixelMap) => {
console.info('base64ToPixelMap pixelMap 创建成功。');
success(pixelMap)
}).catch((err: BusinessError) => {
console.error(`base64ToPixelMap pixelMap 创建失败。 code:${err.code}, message:${err.message}`);
error(err)
});
}
/**
* 保存到相册
* @param context
* @param pixelMap
* @param isToast
*/
static async savePixelMapToAlbum(
context: common.UIAbilityContext | undefined,
pixelMap: image.PixelMap,
isToast: boolean = true,
success: (path: string) => void,
error: (err: BusinessError) => void = () => {
},
) {
if (context == undefined) {
promptAction.showToast({ message: '保存图片到图库失败!' });
return
}
// 获取相册的保存路径
let helper = photoAccessHelper.getPhotoAccessHelper(context);
let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpeg');
let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
console.log(`savePixmap2SystemFile 保存图片成功。${file.path}`);
ImageUtils.toArrayBuffer(pixelMap, async (data: ArrayBuffer) => {
let path = file.path
console.log(`savePixmap2SystemFile 保存图片成功。${path}`);
await fileIo.write(file.fd, data);
await fileIo.close(file.fd);
if (isToast) {
promptAction.showToast({ message: '保存图片成功!' });
}
success(path);
}, (err: BusinessError) => {
console.error(`savePixmap2SystemFile 保存图片成功。code:${err.code},message: ${err.message}`);
if (isToast) {
promptAction.showToast({ message: '保存图片失败!' });
}
error(err);
})
}
/**
* 保存到应用沙箱
* @param context
* @param pixelMap
* @param filesDir
* @param isToast
*/
static savePixmap2SystemFile(
context: Context,
pixelMap: image.PixelMap,
filesDir: string = context.filesDir,
isToast: boolean = true,
success: (path: string) => void,
error: (err: BusinessError) => void = () => {
},
) {
if (!pixelMap) {
return;
}
ImageUtils.toArrayBuffer(pixelMap, async (data: ArrayBuffer) => {
const file =
fileIo.openSync(filesDir + `/${Date.now()}.jpg`, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
let path = file.path
console.log(`savePixmap2SystemFile 保存图片成功。${path}`);
await fileIo.write(file.fd, data);
await fileIo.close(file.fd);
if (isToast) {
promptAction.showToast({ message: '保存图片成功!' });
}
success(path);
}, (err: BusinessError) => {
console.error(`savePixmap2SystemFile 保存图片成功。code:${err.code},message: ${err.message}`);
if (isToast) {
promptAction.showToast({ message: '保存图片失败!' });
}
error(err);
})
}
}