往期鸿蒙全套实战文章必看:(附带鸿蒙全栈学习资料)
调用imageSource.createPixelMap()报错“Create PixelMap error”
问题现象
从相册获取到一张图片uri,代码如下:
const file = fs.openSync(uri, fs.OpenMode.READ_ONLY);
const imageSource = image.createImageSource(file.fd);
const pixelMap = await imageSource.createPixelMap({sampleSize: 2, rotate: 0});
此时报错“Create PixelMap error”,没有错误码。如果把sampleSize配置去掉则不报错。如何正确设置sampleSize,将图片缩小。
解决措施
该问题是sampleSize取值错误导致的,sampleSize表示缩略图采样大小,当前只能取1。可通过DecodingOptions.desiredSize指定输出大小。参考代码如下:
import { BusinessError } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';
let decodingOptions: image.DecodingOptions = {
editable: true,
desiredPixelFormat: 3,
desiredSize: { width: 4, height: 6 }
}
const context: Context = getContext(this);
const filePath: string = context.cacheDir + '/test.jpg';
const imageSource: image.ImageSource = image.createImageSource(filePath);
// 创建pixelMap并进行简单的旋转和缩放
imageSource.createPixelMap(decodingOptions).then((pixelMap: image.PixelMap) => {
console.log("Succeeded in creating PixelMap")
}).catch((err: BusinessError) => {
console.error("Failed to create PixelMap")
});