中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
小程序插件,需要通过用户提供的url从网络上获取图片的二进制文件(不一定是二进制格式),放在内存变量里,再根据变量中的二进制数据生成图片存储到用户的相册里。(诉求:尽量将图片存放在内存中,而不要放在应用的缓存目录下。这样可以减少app不必要的文件占用。)
微信扫码分享
import http from '@ohos.net.http'; import ResponseCode from '@ohos.net.http'; import image from '@ohos.multimedia.image'; import { BusinessError } from '@ohos.base'; import photoAccessHelper from '@ohos.file.photoAccessHelper' import fs from '@ohos.file.fs' @Entry @Component struct LoadImgFromUrl { @State pixelMap: PixelMap | undefined = undefined; loadImageWithUrl(url: string) { let OutData: http.HttpResponse let imagePackerApi = image.createImagePacker(); let packOpts : image.PackingOption = { format:"image/jpeg", quality:98 }; //确保网络正常 http.createHttp().request(url, { method:http.RequestMethod.GET, connectTimeout:60000, readTimeout:60000 }, async (error: BusinessError, data: http.HttpResponse) => { if (error) { console.error(`http reqeust failed with. Code: ${error.code}, message: ${error.message}`); } else { OutData = data let code: http.ResponseCode | number = OutData.responseCode if (ResponseCode.ResponseCode.OK === code) { let imageData: ArrayBuffer = OutData.result as ArrayBuffer; let imageSource: image.ImageSource = image.createImageSource(imageData); class tmp { height: number = 100 width: number = 100 } let si: tmp = new tmp() let options: Record<string, number | boolean | tmp> = { 'alphaType': 0, // 透明度 'editable': false, // 是否可编辑 'pixelFormat': 3, // 像素格式 'scaleMode': 1, // 缩略值 'size': { height: 100, width: 100 } } // 创建图片大小 imageSource.createPixelMap(options).then((pixelMap: PixelMap) => { this.pixelMap = pixelMap this.pixelMap.getImageInfo().then((info: image.ImageInfo) => { console.info('info.width = ' + info.size.width) }).catch((err: BusinessError) =>{ console.error("Faild " + err);