HarmonyOS 鸿蒙Next 如何根据本地图片文件path得到图片宽高 此时不加载图片 获取宽高后才做响应加载图片
HarmonyOS 鸿蒙Next 如何根据本地图片文件path得到图片宽高 此时不加载图片 获取宽高后才做响应加载图片 如何根据本地图片文件path 得到图片宽高尼 此时不加载图片,获取宽高后才做响应加载图片
可以通过获取图片的pixelMap 再通过 getImageInfo
获取图片信息中的宽高值 参考文档:
https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V13/js-apis-image-V13#getimageinfo7
https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V13/js-apis-image-V13#imagecreatepixelmap8
import { image } from '@kit.ImageKit';
import fs from '@ohos.file.fs';
@Entry
@Component
struct Index {
@State _pixelMap: image.PixelMap | undefined = undefined;
@State wit: number = 0;
@State hig: number = 0;
build() {
Column() {
Image(this._pixelMap)
.width(100)
.height(100)
.margin(20)
Button('获取宽高')
.onClick(async () => {
let filesDir: string = getContext(this).filesDir
let filePath = filesDir + "/xxx.png";
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let imageSource: image.ImageSource = image.createImageSource(file.fd);
let opts: image.DecodingOptions = { editable: true }
this._pixelMap = await imageSource.createPixelMap(opts);
this._pixelMap.getImageInfo().then((imageInfo: image.ImageInfo) => {
if (imageInfo == undefined) {
console.error(`Failed to obtain the image pixel map information.`);
}
this.wit = imageInfo.size.width;
this.hig = imageInfo.size.height;
console.log(`Succeeded in obtaining the image pixel map information., ${JSON.stringify(this.wit)}, ${JSON.stringify(this.hig)}`);
})
})
}
}
}
更多关于HarmonyOS 鸿蒙Next 如何根据本地图片文件path得到图片宽高 此时不加载图片 获取宽高后才做响应加载图片的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙系统中,如果你需要根据本地图片文件的路径获取图片的宽高而不加载图片,可以利用BitmapFactory类来实现。以下是具体方法:
-
使用BitmapFactory.Options:首先,你需要创建一个BitmapFactory.Options对象,并设置其inJustDecodeBounds属性为true。这样做可以确保在解码图片时不会分配内存给位图,而只是获取图片的宽高信息。
-
解码图片文件:然后,使用BitmapFactory.decodeFile方法传入图片路径和上述Options对象。该方法会解析图片文件但不会加载图片到内存中,只会填充Options对象中的outWidth和outHeight属性。
-
获取宽高:最后,从Options对象中读取outWidth和outHeight属性,即可得到图片的宽高。
示例代码如下:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
int width = options.outWidth;
int height = options.outHeight;
// 此时已获取宽高,可根据宽高进行后续操作,如加载图片等。
注意:上述代码示例仅用于说明思路,在鸿蒙系统中实际使用时,需根据鸿蒙API进行调整。
如果问题依旧没法解决请联系官网客服,官网地址是 https://www.itying.com/category-93-b0.html,