从服务器下载的图片资源如何显示到Image组件上 - HarmonyOS 鸿蒙Next
从服务器下载的图片资源如何显示到Image组件上 - HarmonyOS 鸿蒙Next
图片资源下载到了应用到沙箱目录,如 :/data/storage/el2/base/cache/downloads/picture/01c3685d43f286a80120695cf6c3ae.jpg
如何将上诉制定路径的图片显示到UI组件Image上?
2 回复
Image组件不能直接传入应用沙箱路径,需要传入应用沙箱uri;
拿到文件的沙箱路径后,通过调用@ohos.file.fileuri模块的fileuri.getUriFromPath(file.path)将沙箱路径转化为沙箱uri,传入之后即可正常显示。
更多关于从服务器下载的图片资源如何显示到Image组件上 - HarmonyOS 鸿蒙Next的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS中,可以通过Image
组件显示从服务器下载的图片资源。首先,使用Http
模块发送网络请求获取图片数据。接着,将获取到的图片数据转换为PixelMap
对象。最后,将PixelMap
对象设置到Image
组件的src
属性上。以下是实现步骤:
-
导入相关模块:
import http from '[@ohos](/user/ohos).net.http'; import image from '[@ohos](/user/ohos).multimedia.image';
-
发送网络请求获取图片数据:
let httpRequest = http.createHttp(); httpRequest.request('https://example.com/image.png', { method: http.RequestMethod.GET, expectDataType: http.HttpDataType.ARRAY_BUFFER, }, (err, data) => { if (err) { console.error('Failed to download image:', err); return; } let arrayBuffer = data.result as ArrayBuffer; // 将ArrayBuffer转换为PixelMap image.createImageSource(arrayBuffer).then(imageSource => { imageSource.createPixelMap().then(pixelMap => { // 显示图片 this.imageSrc = pixelMap; }); }); });
-
将
PixelMap
对象绑定到Image
组件:[@State](/user/State) imageSrc: PixelMap | null = null; build() { Column() { if (this.imageSrc) { Image(this.imageSrc) .width(100) .height(100); } } }
通过以上步骤,可以将从服务器下载的图片资源显示到Image
组件上。