import { common2D, drawing } from "@kit.ArkGraphics2D";
import { image } from "@kit.ImageKit";

export class ImageUtils {

  /**
   * 调整图片分辨率
   * @param bitmap
   * @param w
   * @param h
   * @returns
   */
  static async resizeImage(bitmap: PixelMap, w: number, h: number): Promise<image.PixelMap> {
    // 获取图像像素信息
    const imageInfo = await bitmap.getImageInfo();
    const width: number = imageInfo.size.width;
    const height: number = imageInfo.size.height;
    const scaleWidth: number = w / width;
    const scaleHeight: number = h / height;
    const pixelMapColor: ArrayBuffer = new ArrayBuffer(w * h * 2);
    const options: image.InitializationOptions = {
      editable: true,
      pixelFormat: image.PixelMapFormat.RGB_565,
      size: { height: h, width: w }
    };
    // 采用RGB_565格式创建画布PixelMap
    const canvasPixelMap = await image.createPixelMap(pixelMapColor, options);
    // 创建一个以PixelMap作为绘制目标的Canvas对象
    const canvas = new drawing.Canvas(canvasPixelMap);
    // 构造矩阵对象
    const matrix = new drawing.Matrix();
    // 构造画笔对象
    let pen = new drawing.Pen();
    // 绑定画笔到画布上，在画布上进行绘制时，将使用画笔的样式去绘制图形形状的轮廓
    canvas.attachPen(pen);
    // 矩形区域
    let rect: common2D.Rect = {
      left: 0,
      top: 0,
      right: w,
      bottom: h
    };
    // 将图片绘制到画布的指定区域上
    canvas.drawImageRect(bitmap, rect);
    // 将矩阵设置为矩阵右乘围绕轴心点按一定缩放系数缩放后的单位矩阵后得到的矩阵
    matrix.postScale(scaleWidth, scaleHeight, 0, 0);
    // 设置矩阵对象参数
    canvas.setMatrix(matrix);
    // 将画笔与画布解绑
    canvas.detachPen();
    return Promise.resolve(canvasPixelMap)
  }
}