diff --git a/entry/src/main/ets/pages/DownsamplingPage.ets b/entry/src/main/ets/pages/DownsamplingPage.ets new file mode 100644 index 0000000..4a1921e --- /dev/null +++ b/entry/src/main/ets/pages/DownsamplingPage.ets @@ -0,0 +1,325 @@ +import { FitCenter, ImageKnifeComponent, + ImageKnifeData, + ImageKnifeGlobal, + ImageKnifeOption, + RequestOption } from '@ohos/libraryimageknife' +import { BusinessError } from '@ohos.base' +import { fitter, sampleNone } from '@ohos/imageknife'; +let pngUrl = $r('app.media.pngSample'); +let jpgUrl = $r('app.media.jpgSample'); +let svgUrl = $r('app.media.svgSample'); +let gifUrl = $r('app.media.gifSample'); +let bmpUrl = $r('app.media.bmpSample'); +let webpUrl = $r('app.media.webpSample'); +let ImageKnife = ImageKnifeGlobal.getInstance().getImageKnife(); +@Entry +@Component +struct Index { + @State message: string = 'Hello World'; + @State mSquarePixelMap1?: PixelMap = undefined; + @State mSquarePixelMap2?: PixelMap = undefined; + @State h:number = 0 + @State w:number = 0 + @State BytesNumber1:number = 0 + @State BytesNumber2:number = 0 + @State url:string = '' + @State ImageKnifeOption1: ImageKnifeOption = { + loadSrc: $r('app.media.icon'), + placeholderSrc: $r('app.media.icon_loading'), + errorholderSrc: $r('app.media.icon_failed') + } + + transformSquare1(mUrl:ESObject) { + let imageKnifeOption:RequestOption = new RequestOption(); + imageKnifeOption.load(mUrl) + .addListener({ callback: (err: BusinessError | string, data: ImageKnifeData) => { + this.mSquarePixelMap1 = data.drawPixelMap?.imagePixelMap as PixelMap; + this.BytesNumber1 = (data.drawPixelMap?.imagePixelMap as PixelMap).getPixelBytesNumber() + return false; + } }) + ImageKnife?.call(imageKnifeOption); + } + transformSquare2(mUrl:ESObject) { + let imageKnifeOption:RequestOption = new RequestOption(); + imageKnifeOption.load(mUrl) + .addListener({ callback: (err: BusinessError | string, data: ImageKnifeData) => { + this.mSquarePixelMap2 = data.drawPixelMap?.imagePixelMap as PixelMap; + this.BytesNumber2 = (data.drawPixelMap?.imagePixelMap as PixelMap).getPixelBytesNumber() + return false; + } }) + .setImageViewSize({ width: this.w, height:this.h}) + .downsampleStrategy(new fitter()) + ImageKnife?.call(imageKnifeOption); + } + @Builder + TextInputSample() { + Flex() { + TextInput({ placeholder: '输入宽' }) + .onChange((EnterKeyType)=>{ + this.w =Number(EnterKeyType) + }) + TextInput({ placeholder: '输入高' }) + .onChange((EnterKeyType)=>{ + this.h =Number(EnterKeyType) + }) + }.padding(20) + } + + build() { + Scroll(){ + Column() { + Row(){ + Button('切换网络图片') + Text('输入网络图片url') + TextInput({ placeholder: '输入url' }) + .onChange((urls)=>{ + this.url =urls + }) + } + if(this.url!==''){ + Column(){ + Text('原图') + Flex(){ + Button('png') + .onClick(() => { + this.transformSquare1(this.url); + + }); + Button('svg') + .onClick(() => { + this.transformSquare1(this.url); + + }); + Button('bmp') + .onClick(() => { + this.transformSquare1(this.url); + + }); + Button('jpp') + .onClick(() => { + this.transformSquare1(this.url); + + }); + Button('gif') + .onClick(() => { + this.transformSquare1(this.url); + + }); + Button('webp') + .onClick(() => { + this.transformSquare1(this.url); + + }); + }.margin({top:20,bottom:20}) + Text("原图字节大小:"+this.BytesNumber1) + Column(){ + if (this.mSquarePixelMap1) { + Image(this.mSquarePixelMap1 == undefined ? '' : this.mSquarePixelMap1!) + .objectFit(ImageFit.Fill) + .width(200) + .height(200) + .margin({ top: 10 }) + } + Text('component用法') + + }.height(300).width('100%').backgroundColor(Color.Pink) + Text('降采样图片') + Flex(){ + Button('png') + .onClick(() => { + this.transformSquare2(this.url); + this.ImageKnifeOption1 = { + loadSrc: pngUrl, + placeholderSrc: $r('app.media.icon_loading'), + errorholderSrc: $r('app.media.icon_failed'), + } + }); + Button('svg') + .onClick(() => { + this.transformSquare2(this.url); + this.ImageKnifeOption1 = { + loadSrc: svgUrl, + placeholderSrc: $r('app.media.icon_loading'), + errorholderSrc: $r('app.media.icon_failed'), + } + + }); + Button('bmp') + .onClick(() => { + this.transformSquare2(this.url); + this.ImageKnifeOption1 = { + loadSrc: bmpUrl, + placeholderSrc: $r('app.media.icon_loading'), + errorholderSrc: $r('app.media.icon_failed'), + } + }); + Button('jpp') + .onClick(() => { + this.transformSquare2(this.url); + this.ImageKnifeOption1 = { + loadSrc: jpgUrl, + placeholderSrc: $r('app.media.icon_loading'), + errorholderSrc: $r('app.media.icon_failed'), + } + }); + Button('gif') + .onClick(() => { + this.transformSquare2(this.url); + this.ImageKnifeOption1 = { + loadSrc: gifUrl, + placeholderSrc: $r('app.media.icon_loading'), + errorholderSrc: $r('app.media.icon_failed'), + } + }); + Button('webp') + .onClick(() => { + this.transformSquare2(this.url); + this.ImageKnifeOption1 = { + loadSrc: webpUrl, + placeholderSrc: $r('app.media.icon_loading'), + errorholderSrc: $r('app.media.icon_failed'), + } + }); + }.margin({top:20,bottom:20}) + Text("降采样字节大小:"+this.BytesNumber2) + this.TextInputSample() + Column(){ + if (this.mSquarePixelMap2) { + Image(this.mSquarePixelMap2 == undefined ? '' : this.mSquarePixelMap2!) + .objectFit(ImageFit.Fill) + .width(200) + .height(200) + .margin({ top: 10 }) + } + Text('component用法') + ImageKnifeComponent({ imageKnifeOption: this.ImageKnifeOption1 }).width(200).height(200) + }.height(300).width('100%').backgroundColor(Color.Pink) + } + }else { + Column(){ + Text('原图') + Flex(){ + Button('png') + .onClick(() => { + this.transformSquare1(pngUrl); + + }); + Button('svg') + .onClick(() => { + this.transformSquare1(svgUrl); + + }); + Button('bmp') + .onClick(() => { + this.transformSquare1(bmpUrl); + + }); + Button('jpp') + .onClick(() => { + this.transformSquare1(jpgUrl); + + }); + Button('gif') + .onClick(() => { + this.transformSquare1(gifUrl); + + }); + Button('webp') + .onClick(() => { + this.transformSquare1(webpUrl); + + }); + }.margin({top:20,bottom:20}) + Text("原图字节大小:"+this.BytesNumber1) + Column(){ + if (this.mSquarePixelMap1) { + Image(this.mSquarePixelMap1 == undefined ? '' : this.mSquarePixelMap1!) + .objectFit(ImageFit.Fill) + .width(200) + .height(200) + .margin({ top: 10 }) + } + Text('component用法') + + }.height(300).width('100%').backgroundColor(Color.Pink) + Text('降采样图片') + Flex(){ + Button('png') + .onClick(() => { + this.transformSquare2(pngUrl); + this.ImageKnifeOption1 = { + loadSrc: pngUrl, + placeholderSrc: $r('app.media.icon_loading'), + errorholderSrc: $r('app.media.icon_failed'), + } + }); + Button('svg') + .onClick(() => { + this.transformSquare2(svgUrl); + this.ImageKnifeOption1 = { + loadSrc: svgUrl, + placeholderSrc: $r('app.media.icon_loading'), + errorholderSrc: $r('app.media.icon_failed'), + } + + }); + Button('bmp') + .onClick(() => { + this.transformSquare2(bmpUrl); + this.ImageKnifeOption1 = { + loadSrc: bmpUrl, + placeholderSrc: $r('app.media.icon_loading'), + errorholderSrc: $r('app.media.icon_failed'), + } + }); + Button('jpp') + .onClick(() => { + this.transformSquare2(jpgUrl); + this.ImageKnifeOption1 = { + loadSrc: jpgUrl, + placeholderSrc: $r('app.media.icon_loading'), + errorholderSrc: $r('app.media.icon_failed'), + } + }); + Button('gif') + .onClick(() => { + this.transformSquare2(gifUrl); + this.ImageKnifeOption1 = { + loadSrc: gifUrl, + placeholderSrc: $r('app.media.icon_loading'), + errorholderSrc: $r('app.media.icon_failed'), + } + }); + Button('webp') + .onClick(() => { + this.transformSquare2(webpUrl); + this.ImageKnifeOption1 = { + loadSrc: webpUrl, + placeholderSrc: $r('app.media.icon_loading'), + errorholderSrc: $r('app.media.icon_failed'), + } + }); + }.margin({top:20,bottom:20}) + Text("降采样字节大小:"+this.BytesNumber2) + this.TextInputSample() + Column(){ + if (this.mSquarePixelMap2) { + Image(this.mSquarePixelMap2 == undefined ? '' : this.mSquarePixelMap2!) + .objectFit(ImageFit.Fill) + .width(200) + .height(200) + .margin({ top: 10 }) + } + Text('component用法') + ImageKnifeComponent({ imageKnifeOption: this.ImageKnifeOption1 }).width(200).height(200) + }.height(300).width('100%').backgroundColor(Color.Pink) + } + } + + + } + } + .height('100%') + } +} + diff --git a/entry/src/main/ets/pages/imageknifeTestCaseIndex.ets b/entry/src/main/ets/pages/imageknifeTestCaseIndex.ets index 68c7303..190d06d 100644 --- a/entry/src/main/ets/pages/imageknifeTestCaseIndex.ets +++ b/entry/src/main/ets/pages/imageknifeTestCaseIndex.ets @@ -40,6 +40,10 @@ struct IndexFunctionDemo { console.log("优先级加载") router.pushUrl({ url: "pages/testPriorityComponent" }); }).margin({ top: 5, left: 3 }) + Button("下采样加载") + .onClick(() => { + router.pushUrl({ url: "pages/DownsamplingPage" }); + }).margin({ top: 5, left: 3 }) }.width('100%').height(60).backgroundColor(Color.Pink) Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { diff --git a/entry/src/main/resources/base/profile/main_pages.json b/entry/src/main/resources/base/profile/main_pages.json index affb988..e08b039 100644 --- a/entry/src/main/resources/base/profile/main_pages.json +++ b/entry/src/main/resources/base/profile/main_pages.json @@ -57,6 +57,7 @@ "pages/testImageKnifeHeic", "pages/testImageKnifeNetPlaceholder", "pages/testCustomDataFetchClientWithPage", - "pages/testReuseAblePages" + "pages/testReuseAblePages", + "pages/DownsamplingPage" ] } \ No newline at end of file diff --git a/hvigor/hvigor-config.json5 b/hvigor/hvigor-config.json5 index 122677b..69b4a2d 100644 --- a/hvigor/hvigor-config.json5 +++ b/hvigor/hvigor-config.json5 @@ -1,6 +1,6 @@ { - "hvigorVersion": "3.0.9", + "hvigorVersion": "4.1.2", "dependencies": { - "@ohos/hvigor-ohos-plugin": "3.0.9" + "@ohos/hvigor-ohos-plugin": "4.1.2" } } \ No newline at end of file diff --git a/library/index.ets b/library/index.ets index 5e8d3ca..0d52b8d 100644 --- a/library/index.ets +++ b/library/index.ets @@ -130,4 +130,8 @@ export { GIFFrame } from './src/main/ets/components/imageknife/utils/gif/GIFFram export { IDrawLifeCycle } from './src/main/ets/components/imageknife/interface/IDrawLifeCycle' // 日志管理 -export { LogUtil } from './src/main/ets/components/imageknife/utils/LogUtil' \ No newline at end of file +export { LogUtil } from './src/main/ets/components/imageknife/utils/LogUtil' +/*下采样*/ +export {Downsampler} from './src/main/ets/components/imageknife/Downsampling/Downsampler' + +export {DownsampleNone as sampleNone, FitCenter as fitter} from './src/main/ets/components/imageknife/Downsampling/DownsampleStartegy' \ No newline at end of file diff --git a/library/src/main/ets/components/imageknife/Downsampling/BaseDownsampling.ets b/library/src/main/ets/components/imageknife/Downsampling/BaseDownsampling.ets new file mode 100644 index 0000000..e3c09d7 --- /dev/null +++ b/library/src/main/ets/components/imageknife/Downsampling/BaseDownsampling.ets @@ -0,0 +1,9 @@ +import { lang }from '@kit.ArkTs'; + +type ISendable = lang.ISendable; + +export interface BaseDownsampling extends ISendable{ + getName():string + getScaleFactor(sourceWidth:number, sourceHeight:number, requestWidth:number, requestHeight:number):number + getSampleSizeRounding(sourceWidth:number, sourceHeight:number, requestWidth:number, requestHeight:number):number +} \ No newline at end of file diff --git a/library/src/main/ets/components/imageknife/Downsampling/DownsampleStartegy.ets b/library/src/main/ets/components/imageknife/Downsampling/DownsampleStartegy.ets new file mode 100644 index 0000000..5f02cb0 --- /dev/null +++ b/library/src/main/ets/components/imageknife/Downsampling/DownsampleStartegy.ets @@ -0,0 +1,117 @@ +import { BaseDownsampling } from './BaseDownsampling' + +@Sendable +export class CenterInside{ + getName() { return "CenterInside"} + getScaleFactor(sourceWidth:number, sourceHeight:number,requestWidth:number, requestHeight:number):number { + return Math.min(1,this.getScale(sourceWidth, sourceHeight, requestWidth, requestHeight)) + } + getSampleSizeRounding(sourceWidth:number, sourceHeight:number, requestWidth:number, requestHeight:number):number{ + return 1 + } + getScale(sourceWidth: number, sourceHeight: number, requestWidth: number, requestHeight: number): number { + let widthPercentage =requestWidth/sourceWidth + let heightPercentage =requestHeight/sourceHeight + return Math.min(widthPercentage,heightPercentage) + } + +} +/*不进行下采样*/ +@Sendable +export class DownsampleNone implements BaseDownsampling{ + getName(){ + return "DownsampleNone" + } + getScaleFactor(sourceWidth: number, sourceHeight: number, requestWidth: number, requestHeight: number): number { + return 1 + } + + getSampleSizeRounding(sourceWidth: number, sourceHeight: number, requestWidth: number, requestHeight: number): number { + return 1 + } + +} +/* 下采样使得图像的组大尺寸在给定的尺寸的1/2之间*/ +@Sendable +export class AtMost implements BaseDownsampling{ + getName(){ + return "AtMost" + } + getScaleFactor(sourceWidth: number, sourceHeight: number, requestWidth:number,requestHeight: number): number { + let maxIntegerFactor=Math.ceil(Math.max(sourceHeight/requestHeight,sourceWidth/requestWidth)); + let lesserOrEqualSampleSize = Math.max(1,this.highestOneBit(maxIntegerFactor)) + let greaterOrEqualSampleSize = lesserOrEqualSampleSize<<(lesserOrEqualSampleSize> 1); + i |= (i >> 2); + i |= (i >> 4); + i |= (i >> 8); + i |= (i >> 16); + return i - (i >>> 1); + } +} + +@Sendable +export class Atleast implements BaseDownsampling{ + getName(){ + return "Atleast" + } + getScaleFactor(sourceWidth: number, sourceHeight: number, requestWidth: number, requestHeight: number): number { + let minIntegerFactor=Math.floor(Math.min(sourceHeight/requestHeight,sourceWidth/requestWidth)) + return minIntegerFactor==0?1:1/this.highestOneBit(minIntegerFactor) + } + getSampleSizeRounding(sourceWidth: number, sourceHeight: number, requestWidth: number, requestHeight: number): number { + return 1 + } + highestOneBit(i: number): number { + i |= (i >> 1); + i |= (i >> 2); + i |= (i >> 4); + i |= (i >> 8); + i |= (i >> 16); + return i - (i >>> 1); + } +} + +@Sendable +export class CenterOutside implements BaseDownsampling{ + getName(){ + return "CenterOutside" + } + getScaleFactor(sourceWidth: number, sourceHeight: number, requestWidth: number, requestHeight: number): number { + let widthPercentage =requestWidth/sourceWidth + let heightPercentage =requestHeight/sourceHeight + return Math.max(widthPercentage,heightPercentage) + } + + getSampleSizeRounding(sourceWidth: number, sourceHeight: number, requestWidth: number, requestHeight: number): number { + return 1 + } + +} + +@Sendable +export class FitCenter{ + getName(){ + return "FitCenter" + } + getScaleFactor(sourceWidth: number, sourceHeight: number, requestWidth: number, requestHeight: number): number { + let widthPercentage =requestWidth/sourceWidth + let heightPercentage =requestHeight/sourceHeight + return Math.min(widthPercentage,heightPercentage) + } + getSampleSizeRounding(sourceWidth: number, sourceHeight: number, requestWidth: number, requestHeight: number): number { + return 1 + } + +} + +export enum SampleSizeRounding{ + MEMORY, + QUALITY +} \ No newline at end of file diff --git a/library/src/main/ets/components/imageknife/Downsampling/Downsampler.ets b/library/src/main/ets/components/imageknife/Downsampling/Downsampler.ets new file mode 100644 index 0000000..22ce6cc --- /dev/null +++ b/library/src/main/ets/components/imageknife/Downsampling/Downsampler.ets @@ -0,0 +1,121 @@ +/* + * asdfasdfasdfasdfasdf*/ +import { RequestOption } from '../RequestOption'; +import { FileTypeUtil } from '../utils/FileTypeUtil'; +import { CenterOutside, FitCenter, SampleSizeRounding } from './DownsampleStartegy'; + +let TAG = 'downsampling' + +export class Downsampler { + calculateScaling( + imageType: ArrayBuffer, + sourceHeight: number, + sourceWidth: number, + request?: RequestOption + ): ESObject { + const fileType: string | null = new FileTypeUtil().getFileType(imageType) + let powerOfTwoWidth: number | null = null; + let powerOfTwoHeight: number | null = null; + let targetWidth: number = 0 + let targetHeight: number = 0 + if (request?.size.width && !request?.size.height) { + targetWidth = this.round((request?.size.height) * sourceWidth / sourceHeight) + } else if (request?.size.height && !request?.size.width) { + targetHeight = this.round((request?.size.width) * sourceHeight / sourceWidth) + } else if (request?.size.height && request?.size.width) { + targetHeight = request.size.height; + targetWidth = request?.size.width; + } else { + throw new Error("Cannot found width or height "); + } + if (sourceWidth <= 0 || sourceHeight <= 0) return; + let orientedSourceWidth = sourceWidth; + let orientedSourceHeight = sourceHeight; + if (this.isRotationRequired(90)) { + orientedSourceWidth = sourceHeight; + orientedSourceHeight = sourceWidth; + } + /*安卓的模式*/ + let exactScaleFactor: number =new FitCenter() + .getScaleFactor(orientedSourceWidth, orientedSourceHeight, targetWidth, targetHeight) + if (exactScaleFactor <= 0) { + throw new Error("Cannot round with exactScaleFactor"); + } + /*安卓的模式*/ + let rounding: SampleSizeRounding =new FitCenter() + .getSampleSizeRounding(orientedSourceWidth, orientedSourceHeight, targetWidth, targetHeight) + if (rounding == null) { + throw new Error("Cannot round with null rounding"); + } + let outWidth: number = this.round(exactScaleFactor * orientedSourceWidth); + let outHeight: number = this.round(exactScaleFactor * orientedSourceHeight); + let widthScaleFactor = Math.floor(orientedSourceWidth / outWidth); + let heightScaleFactor = Math.floor(orientedSourceHeight / outHeight); + let scaleFactor = rounding == SampleSizeRounding.MEMORY ? + Math.max(widthScaleFactor, heightScaleFactor) : + Math.min(widthScaleFactor, heightScaleFactor) + // 将整型的缩放因子转换为2的次幂采样大小 + let powerOfTwoSampleSize: number = 0; + powerOfTwoSampleSize = Math.max(1,this.highestOneBit(scaleFactor)) + if (rounding == SampleSizeRounding.MEMORY && powerOfTwoSampleSize < (1 / exactScaleFactor)) { + powerOfTwoSampleSize = powerOfTwoSampleSize << 1; + } + // 基于上一步得出的采样大小,根据不同的图片类型,计算采样后的图片尺寸 + if (fileType == "JPEG") { + let nativeScaling = Math.min(powerOfTwoSampleSize, 8); + powerOfTwoWidth = Math.ceil(orientedSourceWidth / nativeScaling); + powerOfTwoHeight = Math.ceil(orientedSourceHeight / nativeScaling); + let secondaryScaling = Math.floor(powerOfTwoSampleSize / 8); + if (secondaryScaling > 0) { + powerOfTwoWidth = powerOfTwoWidth / secondaryScaling; + powerOfTwoHeight = powerOfTwoHeight / secondaryScaling; + } + } else if (fileType == "PNG") { + powerOfTwoWidth = Math.floor(orientedSourceWidth / powerOfTwoSampleSize); + powerOfTwoHeight = Math.floor(orientedSourceHeight / powerOfTwoSampleSize); + } else if (fileType == "WEBP") { + powerOfTwoWidth = Math.round(orientedSourceWidth / powerOfTwoSampleSize); + powerOfTwoHeight = Math.round(orientedSourceHeight / powerOfTwoSampleSize); + } else if (orientedSourceWidth % powerOfTwoSampleSize != 0 || orientedSourceHeight % powerOfTwoSampleSize != 0) { + + } else { + powerOfTwoWidth = orientedSourceWidth / powerOfTwoSampleSize; + powerOfTwoHeight = orientedSourceHeight / powerOfTwoSampleSize; + } + let a: ESObject = { "targetWidth": powerOfTwoWidth, "targetHeight": powerOfTwoHeight } + return a + } + highestOneBit(i: number): number { + i |= (i >> 1); + i |= (i >> 2); + i |= (i >> 4); + i |= (i >> 8); + i |= (i >> 16); + return i - (i >>> 1); + } + + round(value: number): number { + return Math.floor(value + 0.5); + } + + isRotationRequired(degreesToRotate: number): boolean { + return degreesToRotate == 90 || degreesToRotate == 270; + } + + // isScaling(options: ESObject): boolean { + // return options.inTargetDensity >0 + // && options.inDensity>0 + // && options.inTargetDensity != options.inDensity; + //} + getDensityMultiplier(adjustedScaleFactor: number): number { + return Math.round(Number.MAX_VALUE * (adjustedScaleFactor <= 1 ? adjustedScaleFactor : 1 / adjustedScaleFactor)); + } + + adjustTargetDensityForError(adjustedScaleFactor: number): number { + let densityMultiplier = this.getDensityMultiplier(adjustedScaleFactor); + let targetDensity = this.round(densityMultiplier * adjustedScaleFactor); + let scaleFactorWithError = targetDensity / densityMultiplier; + let difference = adjustedScaleFactor / scaleFactorWithError; + return this.round(difference * targetDensity); + } +} \ No newline at end of file diff --git a/library/src/main/ets/components/imageknife/ImageKnife.ets b/library/src/main/ets/components/imageknife/ImageKnife.ets index 040ab4d..8e07d8d 100644 --- a/library/src/main/ets/components/imageknife/ImageKnife.ets +++ b/library/src/main/ets/components/imageknife/ImageKnife.ets @@ -565,8 +565,9 @@ export class ImageKnife { data.setDiskMemoryCache(this.diskMemoryCache) data.setDataFetch(this.dataFetch) data.setDiskMemoryCachePath(this.diskMemoryCache.getPath()) - data.setPlaceHolderRegisterCacheKey(request.placeholderRegisterCacheKey); - data.setPlaceHolderRegisterMemoryCacheKey(request.placeholderRegisterMemoryCacheKey); + // data.setPlaceHolderRegisterCacheKey(request.placeholderRegisterCacheKey); + // data.setPlaceHolderRegisterMemoryCacheKey(request.placeholderRegisterMemoryCacheKey); + data.setDownsampType(request.downsampType) return data; } @@ -841,9 +842,7 @@ async function taskExecute(sendData:SendableData,taskData:TaskParams): Promise

| undefined = undefined; @@ -511,6 +515,10 @@ export class RequestOption { this.gpuEnabled = true; return this; } + downsampleStrategy(downsampType: ESObject){ + this.downsampType = downsampType + return this; + } // 占位图解析成功 placeholderOnComplete = (imageKnifeData:ImageKnifeData) => { diff --git a/library/src/main/ets/components/imageknife/SendableData.ets b/library/src/main/ets/components/imageknife/SendableData.ets index c910e86..eb02777 100644 --- a/library/src/main/ets/components/imageknife/SendableData.ets +++ b/library/src/main/ets/components/imageknife/SendableData.ets @@ -18,6 +18,8 @@ import { collections } from '@kit.ArkTS'; import { IDataFetch } from './networkmanage/IDataFetch'; import { DiskLruCache } from '../cache/DiskLruCache'; import { DownloadClient } from './networkmanage/DownloadClient'; +import { BaseDownsampling } from './Downsampling/BaseDownsampling'; +import { DownsampleNone } from './Downsampling/DownsampleStartegy'; @Sendable export class SendableData{ @@ -39,9 +41,7 @@ export class SendableData{ private diskMemoryCachePath: string = ''; private diskMemoryCache?: DiskLruCache; private dataFetch: IDataFetch = new DownloadClient(); - private placeholderRegisterCacheKey: string = ""; - private placeholderRegisterMemoryCacheKey: string = ""; - + private downsampType: BaseDownsampling = new DownsampleNone(); public setDataFetch(value: IDataFetch) { this.dataFetch = value; } @@ -179,19 +179,11 @@ export class SendableData{ return this.usageType; } - public setPlaceHolderRegisterCacheKey(value: string) { - this.placeholderRegisterCacheKey = value; + public setDownsampType(Type: BaseDownsampling): BaseDownsampling{ + return this.downsampType = Type; } - public getPlaceHolderRegisterCacheKey(): string { - return this.placeholderRegisterCacheKey; - } - - public setPlaceHolderRegisterMemoryCacheKey(value: string) { - this.placeholderRegisterMemoryCacheKey = value; - } - - public getPlaceHolderRegisterMemoryCacheKey(): string { - return this.placeholderRegisterMemoryCacheKey; + public getDownsampType(): BaseDownsampling { + return this.downsampType; } } \ No newline at end of file diff --git a/library/src/main/ets/components/imageknife/interface/IParseImage.ets b/library/src/main/ets/components/imageknife/interface/IParseImage.ets index 9713810..2b6d37c 100644 --- a/library/src/main/ets/components/imageknife/interface/IParseImage.ets +++ b/library/src/main/ets/components/imageknife/interface/IParseImage.ets @@ -13,8 +13,10 @@ * limitations under the License. */ import { BusinessError } from '@ohos.base' +import { RequestOption } from '../RequestOption'; + export interface IParseImage { - parseImage:(imageinfo:ArrayBuffer, onCompleteFunction:(value:T)=>void | PromiseLike, onErrorFunction:(reason?:BusinessError|string)=>void)=>void; + parseImage:(imageinfo:ArrayBuffer, onCompleteFunction:(value:T)=>void | PromiseLike, onErrorFunction:(reason?:BusinessError|string)=>void,request?:RequestOption)=>void; parseImageThumbnail:(scale:number, imageinfo:ArrayBuffer, onCompleteFunction:(value:T)=>void | PromiseLike, onErrorFunction:(reason?:BusinessError|string)=>void)=>void; } \ No newline at end of file diff --git a/library/src/main/ets/components/imageknife/pngj/Png.ets b/library/src/main/ets/components/imageknife/pngj/Png.ets new file mode 100644 index 0000000..02bec03 --- /dev/null +++ b/library/src/main/ets/components/imageknife/pngj/Png.ets @@ -0,0 +1,200 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import {UPNG} from '../../3rd_party/upng/UPNG'; +import {PngCallback} from './PngCallback'; +import image from '@ohos.multimedia.image'; +import resourceManager from '@ohos.resourceManager'; +import ArkWorker from '@ohos.worker' +import { BusinessError } from '@ohos.base' +export class Pngj { + readPngImageInfo(arraybuffer: ArrayBuffer, callback:PngCallback) { + let imageSource:image.ImageSource = image.createImageSource(arraybuffer); + if (imageSource != undefined){ + imageSource.getImageInfo((err:BusinessError, value:image.ImageInfo) => { + if (err) { + return; + } + callback.pngCallback(arraybuffer, value); + }); + } + + } + readPngImage(pngBuffer: ArrayBuffer, callback:PngCallback) { + var png = UPNG.decode(pngBuffer); + callback.pngCallback(pngBuffer, png) + } + + writePngWithString(addInfo:string, pngBuffer: ArrayBuffer,callback:PngCallback) { + var pngDecode = UPNG.decode(pngBuffer); + var newPng = UPNG.encodeWithString(addInfo, UPNG.toRGBA8(pngDecode), pngDecode.width, pngDecode.height, 0) + callback.pngCallback(pngBuffer, newPng); + } + + writePng(pngBuffer: ArrayBuffer,callback:PngCallback) { + var pngDecode = UPNG.decode(pngBuffer); + var newPng = UPNG.encode(UPNG.toRGBA8(pngDecode), pngDecode.width, pngDecode.height, 0) + callback.pngCallback(pngBuffer, newPng); + } + + readPngImageAsync(type: any, pngBuffer: ArrayBuffer, callback: PngCallback) { + // worker.onerror = function (data) { + // + // } + // + // worker.onmessageerror = function (e) { + // + // } + // + // worker.onexit = function () { + // + // } + // + // worker.onmessage = function(e) { + // var data = e.data; + // switch (data.type) { + // case 'readPngImageAsync': + // callback.pngCallback(data.receiver, data.data) + // break; + // default: + // break + // } + // worker.terminate(); + // } + // var obj = { type: 'readPngImageAsync', data: pngBuffer } + // worker.postMessage(obj, [pngBuffer]) + let task = new taskpool.Task(taskParseImage,type, arrayBuffer, callback) + // task.setTransferList([]) + taskpool.execute(task).then((pixelmap: Object) => { + LogUtil.log('ceshi321 : Succeeded in creating pixelmap Ui .' + (pixelmap as image.PixelMap).getPixelBytesNumber()) + onCompleteFunction(pixelmap as image.PixelMap); + }).catch((err: string) => { + LogUtil.log("ceshi321 : test occur error: " + err) + onErrorFunction(err); + }); + + + + } + // taskPoolExecutePixelMap(arrayBuffer: ArrayBuffer, onCompleteFunction: (value: PixelMap) => void | PromiseLike, onErrorFunction: (reason?: BusinessError | string) => void) { + // let task = new taskpool.Task(taskParseImage, arrayBuffer, scale) + // task.setTransferList([]) + // taskpool.execute(task).then((pixelmap: Object) => { + // + // }).catch((err: string) => { + // LogUtil.log("ceshi321 : " + err) + // }); + // } + + + + + + + + + + + + + + writePngWithStringAsync(worker: any, addInfo: string, pngBuffer: ArrayBuffer, callback: PngCallback) { + worker.onerror = function (data) { + + } + + worker.onmessageerror = function (e) { + + } + + worker.onexit = function () { + + } + + worker.onmessage = function(e) { + var data = e.data; + switch (data.type) { + case 'writePngWithStringAsync': + callback.pngCallback(data.receiver, data.data) + break; + default: + break + } + worker.terminate(); + } + + var obj = { type: 'writePngWithStringAsync', data:pngBuffer, info: addInfo} + worker.postMessage(obj, [pngBuffer]) + + } + + writePngAsync(worker: any, pngBuffer: ArrayBuffer, callback: PngCallback) { + worker.onerror = function (data) { + + } + + worker.onmessageerror = function (e) { + + } + + worker.onexit = function () { + + } + + worker.onmessage = function(e) { + var data = e.data; + switch (data.type) { + case 'writePngAsync': + callback.pngCallback(data.receiver, data.data) + break; + default: + break + } + worker.terminate(); + } + + var obj = { type: 'writePngAsync', data:pngBuffer} + worker.postMessage(obj, [pngBuffer]) + + } + +} +@Concurrent +async function taskParseImage(type, arrayBuffer, callback): Promise { + + switch (type.type) { + case 'readPngImageAsync': + callback(data.receiver, data.data) + break; + default: + break + } + + let obj = { type: 'readPngImageAsync', data: arrayBuffer } + + return (obj,[arrayBuffer]) +} + +// function taskPoolExecutePixelMap(arrayBuffer: ArrayBuffer, scale: number, onCompleteFunction: (value: PixelMap) => void | PromiseLike, onErrorFunction: (reason?: BusinessError | string) => void) { +// LogUtil.log("ceshi321 : arrayBuffer长度" + arrayBuffer.byteLength) +// let task = new taskpool.Task(taskParseImage, arrayBuffer, scale) +// task.setTransferList([]) +// taskpool.execute(task).then((pixelmap: Object) => { +// LogUtil.log('ceshi321 : Succeeded in creating pixelmap Ui .' + (pixelmap as image.PixelMap).getPixelBytesNumber()) +// onCompleteFunction(pixelmap as image.PixelMap); +// }).catch((err: string) => { +// LogUtil.log("ceshi321 : test occur error: " + err) +// onErrorFunction(err); +// }); +// } diff --git a/library/src/main/ets/components/imageknife/requestmanage/RequestManager.ets b/library/src/main/ets/components/imageknife/requestmanage/RequestManager.ets index a415276..74efddd 100644 --- a/library/src/main/ets/components/imageknife/requestmanage/RequestManager.ets +++ b/library/src/main/ets/components/imageknife/requestmanage/RequestManager.ets @@ -34,7 +34,6 @@ import { LogUtil } from '../../imageknife/utils/LogUtil' import { BusinessError } from '@ohos.base' import { DataFetchResult } from '../networkmanage/DataFetchResult' - export enum Stage { INITIALIZE, @@ -167,7 +166,7 @@ export class RequestManager { // gif、webp处理 if ((ImageKnifeData.GIF == typeValue || ImageKnifeData.WEBP == typeValue) && !request.dontAnimateFlag) { // 处理gif、webp - this.gifProcess(onComplete, onError, arrayBuffer, typeValue) + this.gifProcess(onComplete, onError, arrayBuffer, typeValue,request) } else if (ImageKnifeData.SVG == typeValue) { // 处理svg this.svgProcess(request, onComplete, onError, arrayBuffer, typeValue) @@ -188,7 +187,7 @@ export class RequestManager { let success = (value: PixelMap) => { onComplete(value); } - this.mParseImageUtil.parseImage(arrayBuffer, success, onError) + this.mParseImageUtil.parseImage(arrayBuffer, success, onError,request) } } } @@ -331,13 +330,13 @@ export class RequestManager { let success = (value: PixelMap) => { onComplete(value); } - this.mParseImageUtil.parseImage(source, success, onError) + this.mParseImageUtil.parseImage(source, success, onError, request) }, this.options.thumbDelayTime) } else { let success = (value: PixelMap) => { onComplete(value); } - this.mParseImageUtil.parseImage(source, success, onError) + this.mParseImageUtil.parseImage(source, success, onError, request) } } } @@ -360,13 +359,13 @@ export class RequestManager { let success = (value: PixelMap) => { onComplete(value); } - this.mParseImageUtil.parseImage(source, success, onError) + this.mParseImageUtil.parseImage(source, success, onError, request) }, this.options.thumbDelayTime) } else { let success = (value: PixelMap) => { onComplete(value); } - this.mParseImageUtil.parseImage(source, success, onError) + this.mParseImageUtil.parseImage(source, success, onError, request) } } @@ -454,7 +453,7 @@ export class RequestManager { this.saveCacheAndDisk(value, filetype, onComplete, source); } } - this.mParseImageUtil.parseImage(source, success, onError) + this.mParseImageUtil.parseImage(source, success, onError, request) }, this.options.thumbDelayTime) } else { let success = (value: PixelMap) => { @@ -462,7 +461,7 @@ export class RequestManager { this.saveCacheAndDisk(value, filetype, onComplete, source); } } - this.mParseImageUtil.parseImage(source, success, onError) + this.mParseImageUtil.parseImage(source, success, onError, request) } } } @@ -534,9 +533,17 @@ export class RequestManager { svgParseImpl.parseSvg(option, arraybuffer, onComplete, onError) } - private gifProcess(onComplete: (value: PixelMap | GIFFrame[]) => void | PromiseLike, onError: (reason?: BusinessError | string) => void, arraybuffer: ArrayBuffer, typeValue: string, cacheStrategy?: (cacheData: ImageKnifeData) => void) { + private gifProcess( + onComplete: (value: PixelMap | GIFFrame[]) => void | PromiseLike, + onError: (reason?: BusinessError | string) => void, + arraybuffer: ArrayBuffer, + typeValue: string, + request?:RequestOption, + cacheStrategy?: (cacheData: ImageKnifeData) => void + ) { let gifParseImpl = new GIFParseImpl() - gifParseImpl.parseGifs(arraybuffer, (data?: GIFFrame[], err?: BusinessError | string) => { + gifParseImpl.parseGifs( + arraybuffer, (data?: GIFFrame[], err?: BusinessError | string) => { if (err) { onError(err) } @@ -552,6 +559,6 @@ export class RequestManager { } else { onError('Parse GIF callback data is null, you need check callback data!') } - }) + },request) } } diff --git a/library/src/main/ets/components/imageknife/utils/ParseImageUtil.ets b/library/src/main/ets/components/imageknife/utils/ParseImageUtil.ets index fd3cb98..d6fd0c5 100644 --- a/library/src/main/ets/components/imageknife/utils/ParseImageUtil.ets +++ b/library/src/main/ets/components/imageknife/utils/ParseImageUtil.ets @@ -16,15 +16,20 @@ import { IParseImage } from '../interface/IParseImage' import image from '@ohos.multimedia.image'; import { BusinessError } from '@ohos.base' -import taskpool from '@ohos.taskpool'; -import { LogUtil } from './LogUtil'; +import { RequestOption } from '../RequestOption'; +import { Downsampler } from '../Downsampling/Downsampler'; export class ParseImageUtil implements IParseImage { - parseImage(imageinfo: ArrayBuffer, onCompleteFunction: (value: PixelMap) => void | PromiseLike, onErrorFunction: (reason?: BusinessError | string) => void) { - this.parseImageThumbnail(1, imageinfo, onCompleteFunction, onErrorFunction) + parseImage( + imageinfo: ArrayBuffer, + onCompleteFunction: (value: PixelMap) => void | PromiseLike, + onErrorFunction: (reason?: BusinessError | string) => void, + request?:RequestOption + ) { + this.parseImageThumbnail(1, imageinfo, onCompleteFunction, onErrorFunction,request) } - parseImageThumbnail(scale: number, imageinfo: ArrayBuffer, onCompleteFunction: (value: PixelMap) => void | PromiseLike, onErrorFunction: (reason?: BusinessError | string) => void) { + parseImageThumbnail(scale: number, imageinfo: ArrayBuffer, onCompleteFunction: (value: PixelMap) => void | PromiseLike, onErrorFunction: (reason?: BusinessError | string) => void,request?:RequestOption) { let imageSource: image.ImageSource = image.createImageSource(imageinfo); // 步骤一:文件转为pixelMap 然后变换 给Image组件 imageSource.getImageInfo().then((value) => { @@ -38,6 +43,18 @@ export class ParseImageUtil implements IParseImage { editable: true, desiredSize: defaultSize }; + if(request?.downsampType.getName()!=='DownsampleNone'){ + const b:ESObject = new Downsampler().calculateScaling(imageinfo, hValue, wValue,request) + opts= { + editable: true, + desiredSize: { + height: b.targetHeight, + width: b.targetWidth + } + }; + } + + imageSource.createPixelMap(opts).then((pixelMap: image.PixelMap) => { onCompleteFunction(pixelMap); diff --git a/library/src/main/ets/components/imageknife/utils/gif/GIFParseImpl.ets b/library/src/main/ets/components/imageknife/utils/gif/GIFParseImpl.ets index abe1a37..cfd485c 100644 --- a/library/src/main/ets/components/imageknife/utils/gif/GIFParseImpl.ets +++ b/library/src/main/ets/components/imageknife/utils/gif/GIFParseImpl.ets @@ -19,6 +19,8 @@ import { BusinessError } from '@ohos.base' import worker, { ErrorEvent, MessageEvents } from '@ohos.worker'; import taskpool from '@ohos.taskpool' import { LogUtil } from '../LogUtil' +import { RequestOption } from '../../RequestOption' +import { Downsampler } from '../../Downsampling/Downsampler' export interface senderData { type: string, @@ -34,7 +36,11 @@ export interface gifBackData { } export class GIFParseImpl implements IParseGif { - parseGifs(imageinfo: ArrayBuffer, callback: (data?: GIFFrame[], err?: BusinessError | string) => void) { + parseGifs( + imageinfo: ArrayBuffer, + callback: (data?: GIFFrame[], err?: BusinessError | string) => void, + _request?: RequestOption + ) { // 硬解码流程 let imageSource = image.createImageSource(imageinfo); let decodeOpts: image.DecodingOptions = { @@ -42,7 +48,29 @@ export class GIFParseImpl implements IParseGif { editable: true, rotate: 0 } - let data:GIFFrame[] = []; + let hValue: number = 0 + let wValue: number = 0 + imageSource.getImageInfo().then((value) => { + hValue = Math.round(value.size.height); + wValue = Math.round(value.size.height); + console.log('原始宽高:', JSON.stringify(value.size)) + console.log('classType', JSON.stringify(_request?.downsampType.getName())) + console.log('classType2', hValue, wValue) + if (_request?.downsampType.getName() !== 'DownsampleNone') { + const b: ESObject = new Downsampler().calculateScaling(imageinfo, Math.round(value.size.height), Math.round(value.size.width), _request) + console.log("classType1", JSON.stringify(b)) + decodeOpts = { + sampleSize: 1, + editable: true, + rotate: 0, + desiredSize: { + width: b.targetWidth, + height: b.targetHeight + } + } + } + }) + let data: GIFFrame[] = []; imageSource.createPixelMapList(decodeOpts).then((pixelList: Array) => { //sdk的api接口发生变更:从.getDelayTime() 变为.getDelayTimeList() imageSource.getDelayTimeList().then(delayTimes => { @@ -60,20 +88,20 @@ export class GIFParseImpl implements IParseGif { } data.push(frame) } - callback(data,undefined) + callback(data, undefined) imageSource.release(); }).catch((err: string) => { imageSource.release(); - callback(undefined,err) + callback(undefined, err) }) } }).catch((err: string) => { imageSource.release(); - callback(undefined,err) + callback(undefined, err) }) }).catch((err: string) => { imageSource.release(); - callback(undefined,err) + callback(undefined, err) }) } } \ No newline at end of file diff --git a/library/src/main/ets/components/imageknife/utils/gif/IParseGif.ets b/library/src/main/ets/components/imageknife/utils/gif/IParseGif.ets index d80f388..c83a64d 100644 --- a/library/src/main/ets/components/imageknife/utils/gif/IParseGif.ets +++ b/library/src/main/ets/components/imageknife/utils/gif/IParseGif.ets @@ -17,5 +17,9 @@ import { GIFFrame } from './GIFFrame' import worker from '@ohos.worker'; export interface IParseGif{ // gif解析 - parseGifs:(imageinfo: ArrayBuffer, callback: (data?:GIFFrame[], err?:BusinessError|string) => void, worker?:worker.ThreadWorker,runMainThread?:boolean)=>void + parseGifs:( + imageinfo: ArrayBuffer, + callback: (data?:GIFFrame[], err?:BusinessError|string) => void, + request:ESObject, + worker?:worker.ThreadWorker,runMainThread?:boolean)=>void } \ No newline at end of file diff --git a/library/src/main/ets/components/imageknife/utils/svg/SVGParseImpl.ets b/library/src/main/ets/components/imageknife/utils/svg/SVGParseImpl.ets index 557214a..921830d 100644 --- a/library/src/main/ets/components/imageknife/utils/svg/SVGParseImpl.ets +++ b/library/src/main/ets/components/imageknife/utils/svg/SVGParseImpl.ets @@ -17,6 +17,7 @@ import { RequestOption } from '../../RequestOption' import { BusinessError } from '@ohos.base' import { ImageKnifeData, ImageKnifeType } from '../../ImageKnifeData' import image from '@ohos.multimedia.image' +import { Downsampler } from '../../Downsampling/Downsampler' export class SVGParseImpl implements IParseSvg { parseSvg(option: RequestOption, imageInfo: ArrayBuffer, @@ -24,16 +25,28 @@ export class SVGParseImpl implements IParseSvg { onErrorFunction: (reason?: BusinessError | string) => void) { let imageSource: image.ImageSource = image.createImageSource(imageInfo); // 步骤一:文件转为pixelMap 然后变换 给Image组件 - let hValue = Math.round(option.size.height); - let wValue = Math.round(option.size.width); - let defaultSize: image.Size = { - height: hValue, - width: wValue - }; - let opts: image.DecodingOptions = { - editable: true, - desiredSize: defaultSize - }; + imageSource.getImageInfo().then((value) => { + let hValue = Math.round(value.size.height); + let wValue = Math.round(value.size.width); + let defaultSize: image.Size = { + height: hValue, + width: wValue + }; + let opts: image.DecodingOptions = { + editable: true, + desiredSize: defaultSize + }; + if (option?.downsampType.getName() !== 'DownsampleNone') { + const b: ESObject = new Downsampler().calculateScaling(imageInfo, hValue, wValue, option) + console.log("bbb-----", JSON.stringify(b)) + opts = { + editable: true, + desiredSize: { + width: b.targetWidth, + height: b.targetHeight + } + } + } imageSource.createPixelMap(opts).then((pixelMap: image.PixelMap) => { let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, pixelMap) onComplete(imageKnifeData?.drawPixelMap?.imagePixelMap as PixelMap); @@ -42,5 +55,6 @@ export class SVGParseImpl implements IParseSvg { onErrorFunction(err); imageSource.release() }) + }) } } \ No newline at end of file