图片缩放在图像编缉时是常见的操作。下面的示例实现了通地Canvas的方式对image.PixelMap类型的图片实例,缩放至指定的宽度,并生成新的image.PixelMap实例。
export function zoomPixelMapInWidth_Canvas(
imagePixelMap: image.PixelMap,
width:number
): image.PixelMap {
const imageInfo = imagePixelMap.getImageInfoSync();
const fromWidth = imageInfo.size.width;
const fromHeight = imageInfo.size.height;
const newFromWidth = width/display.getDefaultDisplaySync().densityPixels;
const newFromHeight = newFromWidth / fromWidth * fromHeight;
const offScreenCanvas = new OffscreenCanvas(newFromWidth, newFromHeight);
const offScreenContext = offScreenCanvas.getContext('2d');
offScreenContext.drawImage(imagePixelMap, 0, 0, newFromWidth, newFromHeight);
return offScreenContext.getPixelMap(0, 0, newFromWidth, newFromHeight);
}
调用代码如下
// imagePixelMap是image.PixelMap类型实例,256是px
let imagePixelMap2 = zoomPixelMapInWidth_Canvas(imagePixelMap,256);