ImageHelper.ets 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import { image } from '@kit.ImageKit';
  2. import { FileHelper } from './FileHelper';
  3. import fs from '@ohos.file.fs';
  4. import { BusinessError } from '@kit.BasicServicesKit';
  5. import { textRecognition } from '@kit.CoreVisionKit';
  6. import { util } from '@kit.ArkTS';
  7. export class ImageHelper {
  8. private constructor() {
  9. }
  10. /**
  11. * 图片压缩
  12. * @param sourcePixelMap:原始待压缩图片的PixelMap对象
  13. * @param maxCompressedImageSize:指定图片的压缩目标大小,单位kb
  14. * @returns ArrayBuffer:返回最终压缩后的图片信息
  15. */
  16. static async compressedImage(sourcePixelMap: image.PixelMap, maxCompressedImageSize: number): Promise<ArrayBuffer> {
  17. const imagePackerApi = image.createImagePacker();
  18. const IMAGE_QUALITY = 0;
  19. const packOpts: image.PackingOption = { format: "image/png", quality: IMAGE_QUALITY };
  20. // 通过PixelMap进行编码。compressedImageData为打包获取到的图片文件流。
  21. let compressedImageData: ArrayBuffer = await imagePackerApi.packing(sourcePixelMap, packOpts);
  22. // 压缩目标图像字节长度
  23. const maxCompressedImageByte = maxCompressedImageSize * 1024;
  24. // 图片压缩。先判断设置图片质量参数quality为0时,packing能压缩到的图片最小字节大小是否满足指定的图片压缩大小。如果满足,则使用packing方式二分查找最接近指定图片压缩目标大小的quality来压缩图片。如果不满足,则使用scale对图片先进行缩放,采用while循环每次递减0.4倍缩放图片,再用packing(图片质量参数quality设置0)获取压缩图片大小,最终查找到最接近指定图片压缩目标大小的缩放倍数的图片压缩数据。
  25. if (maxCompressedImageByte > compressedImageData.byteLength) {
  26. // 使用packing二分压缩获取图片文件流
  27. compressedImageData =
  28. await ImageHelper.packingImage(compressedImageData, sourcePixelMap, IMAGE_QUALITY, maxCompressedImageByte);
  29. } else {
  30. // 使用scale对图片先进行缩放,采用while循环每次递减0.4倍缩放图片,再用packing(图片质量参数quality设置0)获取压缩图片大小,最终查找到最接近指定图片压缩目标大小的缩放倍数的图片压缩数据
  31. let imageScale = 1;
  32. const REDUCE_SCALE = 0.4;
  33. // 判断压缩后的图片大小是否大于指定图片的压缩目标大小,如果大于,继续降低缩放倍数压缩。
  34. while (compressedImageData.byteLength > maxCompressedImageByte) {
  35. if (imageScale > 0) {
  36. // 性能知识点: 由于scale会直接修改图片PixelMap数据,所以不适用二分查找scale缩放倍数。这里采用循环递减0.4倍缩放图片,来查找确定最适合的缩放倍数。如果对图片压缩质量要求不高,建议调高每次递减的缩放倍数reduceScale,减少循环,提升scale压缩性能。
  37. imageScale = imageScale - REDUCE_SCALE;
  38. await sourcePixelMap.scale(imageScale, imageScale);
  39. compressedImageData = await ImageHelper.packing(sourcePixelMap, IMAGE_QUALITY);
  40. } else {
  41. // imageScale缩放小于等于0时,没有意义,结束压缩。这里不考虑图片缩放倍数小于reduceScale的情况。
  42. break;
  43. }
  44. }
  45. }
  46. return compressedImageData
  47. }
  48. /**
  49. * packing压缩
  50. * @param sourcePixelMap:原始待压缩图片的PixelMap
  51. * @param imageQuality:图片质量参数
  52. * @returns data:返回压缩后的图片数据
  53. */
  54. static async packing(sourcePixelMap: image.PixelMap, imageQuality: number): Promise<ArrayBuffer> {
  55. const imagePackerApi = image.createImagePacker();
  56. const packOpts: image.PackingOption = { format: "image/jpeg", quality: imageQuality };
  57. const data: ArrayBuffer = await imagePackerApi.packing(sourcePixelMap, packOpts);
  58. return data;
  59. }
  60. /**
  61. * packing二分方式循环压缩
  62. * @param compressedImageData:图片压缩的ArrayBuffer
  63. * @param sourcePixelMap:原始待压缩图片的PixelMap
  64. * @param imageQuality:图片质量参数
  65. * @param maxCompressedImageByte:压缩目标图像字节长度
  66. * @returns compressedImageData:返回二分packing压缩后的图片数据
  67. */
  68. static async packingImage(compressedImageData: ArrayBuffer, sourcePixelMap: image.PixelMap, imageQuality: number,
  69. maxCompressedImageByte: number): Promise<ArrayBuffer> {
  70. // 图片质量参数范围为0-100,这里以10为最小二分单位创建用于packing二分图片质量参数的数组。
  71. const packingArray: number[] = [];
  72. const DICHOTOMY_ACCURACY = 10;
  73. // 性能知识点: 如果对图片压缩质量要求不高,建议调高最小二分单位dichotomyAccuracy,减少循环,提升packing压缩性能。
  74. for (let i = 0; i <= 100; i += DICHOTOMY_ACCURACY) {
  75. packingArray.push(i);
  76. }
  77. let left = 0;
  78. let right = packingArray.length - 1;
  79. // 二分压缩图片
  80. while (left <= right) {
  81. const mid = Math.floor((left + right) / 2);
  82. imageQuality = packingArray[mid];
  83. // 根据传入的图片质量参数进行packing压缩,返回压缩后的图片文件流数据。
  84. compressedImageData = await ImageHelper.packing(sourcePixelMap, imageQuality);
  85. // 判断查找一个尽可能接近但不超过压缩目标的压缩大小
  86. if (compressedImageData.byteLength <= maxCompressedImageByte) {
  87. left = mid + 1;
  88. if (mid === packingArray.length - 1) {
  89. break;
  90. }
  91. // 获取下一次二分的图片质量参数(mid+1)压缩的图片文件流数据
  92. compressedImageData = await ImageHelper.packing(sourcePixelMap, packingArray[mid + 1]);
  93. // 判断用下一次图片质量参数(mid+1)压缩的图片大小是否大于指定图片的压缩目标大小。如果大于,说明当前图片质量参数(mid)压缩出来的图片大小最接近指定图片的压缩目标大小。传入当前图片质量参数mid,得到最终目标图片压缩数据。
  94. if (compressedImageData.byteLength > maxCompressedImageByte) {
  95. compressedImageData = await ImageHelper.packing(sourcePixelMap, packingArray[mid]);
  96. break;
  97. }
  98. } else {
  99. // 目标值不在当前范围的右半部分,将搜索范围的右边界向左移动,以缩小搜索范围并继续在下一次迭代中查找左半部分。
  100. right = mid - 1;
  101. }
  102. }
  103. return compressedImageData;
  104. }
  105. /**
  106. * 提取图片中文字
  107. * @param path
  108. * @returns
  109. */
  110. static recognizeText(path: string | image.PixelMap): Promise<textRecognition.TextRecognitionResult> {
  111. return new Promise((resolve, reject) => {
  112. if (typeof path === 'string') {
  113. let file = FileHelper.openSync(path, fs.OpenMode.READ_ONLY)
  114. const imageSource = image.createImageSource(file.fd);
  115. imageSource.createPixelMap().then((pixelMap) => {
  116. ImageHelper._recognizeText(pixelMap)
  117. .then((data: textRecognition.TextRecognitionResult) => {
  118. resolve(data)
  119. }).catch((err: BusinessError) => {
  120. reject(err)
  121. })
  122. }).catch((err: BusinessError) => {
  123. reject(err)
  124. });
  125. } else {
  126. ImageHelper._recognizeText(path)
  127. .then((data: textRecognition.TextRecognitionResult) => {
  128. resolve(data)
  129. }).catch((err: BusinessError) => {
  130. reject(err)
  131. })
  132. }
  133. });
  134. }
  135. private static _recognizeText(pixelMap: image.PixelMap): Promise<textRecognition.TextRecognitionResult> {
  136. return new Promise((resolve, reject) => {
  137. let visionInfo: textRecognition.VisionInfo = {
  138. pixelMap: pixelMap
  139. };
  140. let textConfiguration: textRecognition.TextRecognitionConfiguration = {
  141. isDirectionDetectionSupported: false
  142. };
  143. textRecognition.recognizeText(visionInfo, textConfiguration)
  144. .then((data: textRecognition.TextRecognitionResult) => {
  145. resolve(data)
  146. })
  147. .catch((error: BusinessError) => {
  148. reject(error)
  149. });
  150. });
  151. }
  152. static base64ToPixelMap(base64Str: string): Promise<image.PixelMap> {
  153. // 移除 Base64 字符串中的前缀(如果存在)
  154. const reg = new RegExp('data:image/\\w+;base64,');
  155. const pureBase64Str = base64Str.replace(reg, '');
  156. // 使用 Base64Helper 解码 Base64 字符串为 ArrayBuffer
  157. const base64Helper = new util.Base64Helper();
  158. const data = base64Helper.decodeSync(pureBase64Str);
  159. // 创建 ImageSource 并生成 PixelMap
  160. const imageSource = image.createImageSource(data.buffer);
  161. const opts: image.DecodingOptions = { editable: true };
  162. return imageSource.createPixelMap(opts);
  163. }
  164. }