!247 imageKnife降采样

Merge pull request !247 from 田双明/master
This commit is contained in:
openharmony_ci 2024-05-07 03:48:56 +00:00 committed by Gitee
commit 937f448fb7
No known key found for this signature in database
GPG Key ID: 173E9B9CA92EEF8F
21 changed files with 839 additions and 52 deletions

View File

@ -1,4 +1,5 @@
## 2.2.0-rc.2 ## 2.2.0-rc.2
- ImageKnife支持下采样
- ImageKnife支持heic图片修改demo按钮控制组件是否展示 - ImageKnife支持heic图片修改demo按钮控制组件是否展示
- 修复通过磁盘链接加载图片无法显示 - 修复通过磁盘链接加载图片无法显示
- ImageKnife控制可视化区域图片 - ImageKnife控制可视化区域图片

View File

@ -449,6 +449,7 @@ request.skipMemoryCache(true)
| request.kuwaharaFilter() | KuwaharaFilterTransform | 桑原滤波器 | | request.kuwaharaFilter() | KuwaharaFilterTransform | 桑原滤波器 |
| request.toonFilter() | ToonFilterTransform | 动画滤波器 | | request.toonFilter() | ToonFilterTransform | 动画滤波器 |
| request.vignetteFilter() | VignetteFilterTransform | 装饰滤波器 | | request.vignetteFilter() | VignetteFilterTransform | 装饰滤波器 |
| request.downsampleOf() | BaseDownsampling | 下采样 |
<img src="screenshot/gif4.gif" width="50%"/> <img src="screenshot/gif4.gif" width="50%"/>
@ -532,6 +533,7 @@ HSP场景适配:
- imageknife # imageknife主要内容 - imageknife # imageknife主要内容
- compress # 压缩相关 - compress # 压缩相关
- constants # 常量相关 - constants # 常量相关
- Downsampling # 下采样相关
- entry # 部分数据结构 - entry # 部分数据结构
- holder # 占位图相关解析 - holder # 占位图相关解析
- interface # 接口相关 - interface # 接口相关
@ -560,6 +562,7 @@ HSP场景适配:
- basicTestResourceManagerPage.ets # 测试本地资源解析 - basicTestResourceManagerPage.ets # 测试本地资源解析
- compressPage.ets # 压缩页面 - compressPage.ets # 压缩页面
- cropImagePage2.ets # 手势裁剪页面 - cropImagePage2.ets # 手势裁剪页面
- DownsamplingPage.ets # 图片下采样测试
- frescoImageTestCasePage.ets # 测试属性动画组件切换 - frescoImageTestCasePage.ets # 测试属性动画组件切换
- frescoRetryTestCasePage.ets # 测试ImageKnifeComponent加载失败重试 - frescoRetryTestCasePage.ets # 测试ImageKnifeComponent加载失败重试
- svgTestCasePage.ets # 测试svg解析页面 - svgTestCasePage.ets # 测试svg解析页面

View File

@ -0,0 +1,366 @@
/*
* Copyright (C) 2024 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 {
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 originalMSquarePixelMap?: PixelMap = undefined;
@State mSquarePixelMap?: PixelMap = undefined;
@State h: number = 0
@State w: number = 0
@State originalBytesNumber: number = 0
@State bytesNumber: number = 0
@State url: string = ''
@State network: Boolean = false
@State imageKnifeOption: ImageKnifeOption = {
loadSrc: $r('app.media.icon'),
placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed')
}
transformSquare1(mUrl: string|Resource|PixelMap) {
let imageKnifeOption: RequestOption = new RequestOption();
imageKnifeOption.load(mUrl)
.addListener({
callback: (err: BusinessError | string, data: ImageKnifeData) => {
this.originalMSquarePixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.originalBytesNumber = (data.drawPixelMap?.imagePixelMap as PixelMap).getPixelBytesNumber()
return false;
}
})
imageKnife?.call(imageKnifeOption);
}
transformSquare2(mUrl: string|Resource|PixelMap) {
let imageKnifeOption: RequestOption = new RequestOption();
let a = new fitter()
imageKnifeOption.load(mUrl)
.addListener({
callback: (err: BusinessError | string, data: ImageKnifeData) => {
this.mSquarePixelMap = data.drawPixelMap?.imagePixelMap as PixelMap;
this.bytesNumber = (data.drawPixelMap?.imagePixelMap as PixelMap).getPixelBytesNumber()
return false;
}
})
.setImageViewSize({ width: this.w, height: this.h })
.downsampleOf(a)
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('切换网络图片')
.onClick(() => {
this.network = !this.network
})
Text('输入网络图片url')
TextInput({ placeholder: '输入url' })
.onChange((urls) => {
this.url = urls
})
}
if (this.network) {
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('jpg')
.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.originalBytesNumber)
Column() {
if (this.originalMSquarePixelMap) {
Image(this.originalMSquarePixelMap == undefined ? '' : this.originalMSquarePixelMap!)
.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.imageKnifeOption = {
loadSrc: pngUrl,
placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'),
downsampling: new fitter()
}
});
Button('svg')
.onClick(() => {
this.transformSquare2(this.url);
this.imageKnifeOption = {
loadSrc: svgUrl,
placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'),
downsampling: new fitter()
}
});
Button('bmp')
.onClick(() => {
this.transformSquare2(this.url);
this.imageKnifeOption = {
loadSrc: bmpUrl,
placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'),
downsampling: new fitter()
}
});
Button('jpg')
.onClick(() => {
this.transformSquare2(this.url);
this.imageKnifeOption = {
loadSrc: jpgUrl,
placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'),
downsampling: new fitter()
}
});
Button('gif')
.onClick(() => {
// this.transformSquare2(this.url);
this.imageKnifeOption = {
loadSrc: gifUrl,
placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'),
downsampling: new fitter()
}
});
Button('webp')
.onClick(() => {
// this.transformSquare2(this.url);
this.imageKnifeOption = {
loadSrc: webpUrl,
placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'),
downsampling: new fitter()
}
});
}.margin({ top: 20, bottom: 20 })
Text("降采样字节大小:" + this.bytesNumber)
this.TextInputSample()
Column() {
if (this.mSquarePixelMap) {
Image(this.mSquarePixelMap == undefined ? '' : this.mSquarePixelMap!)
.objectFit(ImageFit.Fill)
.width(200)
.height(200)
.margin({ top: 10 })
}
Text('component用法')
ImageKnifeComponent({ imageKnifeOption: this.imageKnifeOption }).width(200).height(200)
}.height(300).width('100%').backgroundColor(Color.Pink)
}.backgroundColor(Color.Orange)
} else {
Column() {
Text('原图')
Flex() {
Button('png')
.onClick(() => {
this.transformSquare1(pngUrl);
});
Button('svg')
.onClick(() => {
this.transformSquare1(svgUrl);
});
Button('bmp')
.onClick(() => {
this.transformSquare1(bmpUrl);
});
Button('jpg')
.onClick(() => {
this.transformSquare1(jpgUrl);
});
Button('gif')
.onClick(() => {
this.transformSquare1(gifUrl);
});
Button('webp')
.onClick(() => {
this.transformSquare1(webpUrl);
});
}.margin({ top: 20, bottom: 20 })
Text("原图字节大小:" + this.originalBytesNumber)
Column() {
if (this.originalMSquarePixelMap) {
Image(this.originalMSquarePixelMap == undefined ? '' : this.originalMSquarePixelMap!)
.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.imageKnifeOption = {
loadSrc: pngUrl,
placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'),
}
});
Button('svg')
.onClick(() => {
this.transformSquare2(svgUrl);
this.imageKnifeOption = {
loadSrc: svgUrl,
placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'),
}
});
Button('bmp')
.onClick(() => {
this.transformSquare2(bmpUrl);
this.imageKnifeOption = {
loadSrc: bmpUrl,
placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'),
}
});
Button('jpg')
.onClick(() => {
this.transformSquare2(jpgUrl);
this.imageKnifeOption = {
loadSrc: jpgUrl,
placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'),
}
});
Button('gif')
.onClick(() => {
// this.transformSquare2(gifUrl);
this.imageKnifeOption = {
loadSrc: gifUrl,
placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'),
}
});
Button('webp')
.onClick(() => {
// this.transformSquare2(webpUrl);
this.imageKnifeOption = {
loadSrc: webpUrl,
placeholderSrc: $r('app.media.icon_loading'),
errorholderSrc: $r('app.media.icon_failed'),
}
});
}.margin({ top: 20, bottom: 20 })
Text("降采样字节大小:" + this.bytesNumber)
this.TextInputSample()
Column() {
if (this.mSquarePixelMap) {
Image(this.mSquarePixelMap == undefined ? '' : this.mSquarePixelMap!)
.objectFit(ImageFit.Fill)
.width(200)
.height(200)
.margin({ top: 10 })
}
Text('component用法')
ImageKnifeComponent({ imageKnifeOption: this.imageKnifeOption }).width(200).height(200)
}.height(300).width('100%').backgroundColor(Color.Pink)
}
}
}
}
.height('100%')
}
}

View File

@ -40,6 +40,10 @@ struct IndexFunctionDemo {
console.log("优先级加载") console.log("优先级加载")
router.pushUrl({ url: "pages/testPriorityComponent" }); router.pushUrl({ url: "pages/testPriorityComponent" });
}).margin({ top: 5, left: 3 }) }).margin({ top: 5, left: 3 })
Button("下采样加载")
.onClick(() => {
router.pushUrl({ url: "pages/downsamplingPage" });
}).margin({ top: 5, left: 3 })
}.width('100%').height(60).backgroundColor(Color.Pink) }.width('100%').height(60).backgroundColor(Color.Pink)
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {

View File

@ -57,6 +57,7 @@
"pages/testImageKnifeHeic", "pages/testImageKnifeHeic",
"pages/testImageKnifeNetPlaceholder", "pages/testImageKnifeNetPlaceholder",
"pages/testCustomDataFetchClientWithPage", "pages/testCustomDataFetchClientWithPage",
"pages/testReuseAblePages" "pages/testReuseAblePages",
"pages/downsamplingPage"
] ]
} }

View File

@ -18,7 +18,7 @@ import { DefaultJobQueue } from '@ohos/imageknife/src/main/ets/components/imagek
import { IJobQueue } from '@ohos/imageknife/src/main/ets/components/imageknife/utils/IJobQueue'; import { IJobQueue } from '@ohos/imageknife/src/main/ets/components/imageknife/utils/IJobQueue';
import taskpool from '@ohos.taskpool'; import taskpool from '@ohos.taskpool';
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
import { fitter} from '@ohos/imageknife';
export default function DefaultJobQueueTest() { export default function DefaultJobQueueTest() {
describe('DefaultJobQueueTest', () => { describe('DefaultJobQueueTest', () => {
@ -52,6 +52,13 @@ export default function DefaultJobQueueTest() {
expect(imageKnife.maxRequests).assertEqual(10); expect(imageKnife.maxRequests).assertEqual(10);
}; };
}) })
it("downsampleOf", 1, () => {
let request: RequestOption = new RequestOption()
if (request) {
let requests = request.downsampleOf(new fitter())
expect(requests.downsampType.getName()=='FitCenter').assertTrue()
};
})
}); });
} }

View File

@ -131,3 +131,8 @@ export { IDrawLifeCycle } from './src/main/ets/components/imageknife/interface/I
// 日志管理 // 日志管理
export { LogUtil } from './src/main/ets/components/imageknife/utils/LogUtil' 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'

View File

@ -567,6 +567,7 @@ export class ImageKnife {
data.setDiskMemoryCachePath(this.diskMemoryCache.getPath()) data.setDiskMemoryCachePath(this.diskMemoryCache.getPath())
data.setPlaceHolderRegisterCacheKey(request.placeholderRegisterCacheKey); data.setPlaceHolderRegisterCacheKey(request.placeholderRegisterCacheKey);
data.setPlaceHolderRegisterMemoryCacheKey(request.placeholderRegisterMemoryCacheKey); data.setPlaceHolderRegisterMemoryCacheKey(request.placeholderRegisterMemoryCacheKey);
data.setDownsampType(request.downsampType)
return data; return data;
} }
@ -843,7 +844,7 @@ async function taskExecute(sendData:SendableData,taskData:TaskParams): Promise<P
newRequestOption.size = taskData.size; newRequestOption.size = taskData.size;
newRequestOption.placeholderRegisterCacheKey = sendData.getPlaceHolderRegisterCacheKey(); newRequestOption.placeholderRegisterCacheKey = sendData.getPlaceHolderRegisterCacheKey();
newRequestOption.placeholderRegisterMemoryCacheKey = sendData.getPlaceHolderRegisterMemoryCacheKey(); newRequestOption.placeholderRegisterMemoryCacheKey = sendData.getPlaceHolderRegisterMemoryCacheKey();
newRequestOption.downsampType = sendData.getDownsampType();
if(taskData.placeholderSrc){ if(taskData.placeholderSrc){
newRequestOption.placeholderSrc = taskData.placeholderSrc as string | PixelMap | Resource | undefined; newRequestOption.placeholderSrc = taskData.placeholderSrc as string | PixelMap | Resource | undefined;
} }

View File

@ -259,6 +259,9 @@ export struct ImageKnifeComponent {
if (this.imageKnifeOption.signature) { if (this.imageKnifeOption.signature) {
request.signature = this.imageKnifeOption.signature; request.signature = this.imageKnifeOption.signature;
} }
if(this.imageKnifeOption.downsampling){
request.downsampleOf(this.imageKnifeOption.downsampling)
}
} }
configDisplay(request: RequestOption) { configDisplay(request: RequestOption) {
@ -267,6 +270,7 @@ export struct ImageKnifeComponent {
for (let i = 0; i < this.imageKnifeOption.headerOption.length; i++) { for (let i = 0; i < this.imageKnifeOption.headerOption.length; i++) {
let headerOptions = this.imageKnifeOption.headerOption[i]; let headerOptions = this.imageKnifeOption.headerOption[i];
request.addHeader(headerOptions.key, headerOptions.value); request.addHeader(headerOptions.key, headerOptions.value);
request.signature = new ObjectKey(new Date().getTime().toString())
} }
} }
if( this.imageKnifeOption.priority != undefined) { if( this.imageKnifeOption.priority != undefined) {

View File

@ -28,7 +28,8 @@ import { ObjectKey } from './ObjectKey'
import common from '@ohos.app.ability.common' import common from '@ohos.app.ability.common'
import { Priority } from './RequestOption' import { Priority } from './RequestOption'
import { DataFetchResult } from './networkmanage/DataFetchResult' import { DataFetchResult } from './networkmanage/DataFetchResult'
import { BaseDownsampling } from './downsampling/BaseDownsampling';
import { DownsampleNone } from './downsampling/DownsampleStartegy';
export interface CropCircleWithBorder{ export interface CropCircleWithBorder{
border: number, border: number,
obj: rgbColor obj: rgbColor
@ -87,6 +88,9 @@ export class ImageKnifeOption {
// gif加载展示一帧 // gif加载展示一帧
dontAnimateFlag? = false; dontAnimateFlag? = false;
//下采样
downsampling?:BaseDownsampling = new DownsampleNone()
// 占位图 // 占位图
placeholderSrc?: string | PixelMap | Resource; placeholderSrc?: string | PixelMap | Resource;
placeholderScaleType?: ScaleType = ScaleType.FIT_CENTER placeholderScaleType?: ScaleType = ScaleType.FIT_CENTER

View File

@ -60,7 +60,8 @@ import { SparkMD5 } from '../3rd_party/sparkmd5/spark-md5'
import { FileUtils } from '../cache/FileUtils' import { FileUtils } from '../cache/FileUtils'
import util from '@ohos.util' import util from '@ohos.util'
import { DataFetchResult } from './networkmanage/DataFetchResult' import { DataFetchResult } from './networkmanage/DataFetchResult'
import { BaseDownsampling } from './downsampling/BaseDownsampling'
import { DownsampleNone } from './downsampling/DownsampleStartegy'
export interface Size { export interface Size {
width: number, width: number,
height: number height: number
@ -113,6 +114,8 @@ export class RequestOption {
uuid: string = '' // 唯一标识 uuid: string = '' // 唯一标识
loadSrc: string | PixelMap | Resource = ''; loadSrc: string | PixelMap | Resource = '';
strategy: DiskStrategy = new AUTOMATIC(); strategy: DiskStrategy = new AUTOMATIC();
//下采样相关
downsampType: BaseDownsampling = new DownsampleNone()
dontAnimateFlag = false; dontAnimateFlag = false;
placeholderSrc: string | PixelMap | Resource | undefined = undefined; placeholderSrc: string | PixelMap | Resource | undefined = undefined;
placeholderFunc: AsyncSuccess<ImageKnifeData> | undefined = undefined; placeholderFunc: AsyncSuccess<ImageKnifeData> | undefined = undefined;
@ -511,6 +514,10 @@ export class RequestOption {
this.gpuEnabled = true; this.gpuEnabled = true;
return this; return this;
} }
downsampleOf(downsampType: ESObject){
this.downsampType = downsampType
return this;
}
// 占位图解析成功 // 占位图解析成功
placeholderOnComplete = (imageKnifeData:ImageKnifeData) => { placeholderOnComplete = (imageKnifeData:ImageKnifeData) => {

View File

@ -18,7 +18,8 @@ import { collections } from '@kit.ArkTS';
import { IDataFetch } from './networkmanage/IDataFetch'; import { IDataFetch } from './networkmanage/IDataFetch';
import { DiskLruCache } from '../cache/DiskLruCache'; import { DiskLruCache } from '../cache/DiskLruCache';
import { DownloadClient } from './networkmanage/DownloadClient'; import { DownloadClient } from './networkmanage/DownloadClient';
import { BaseDownsampling } from './downsampling/BaseDownsampling';
import { DownsampleNone } from './downsampling/DownsampleStartegy';
@Sendable @Sendable
export class SendableData{ export class SendableData{
@ -41,6 +42,7 @@ export class SendableData{
private dataFetch: IDataFetch = new DownloadClient(); private dataFetch: IDataFetch = new DownloadClient();
private placeholderRegisterCacheKey: string = ""; private placeholderRegisterCacheKey: string = "";
private placeholderRegisterMemoryCacheKey: string = ""; private placeholderRegisterMemoryCacheKey: string = "";
private downsampType: BaseDownsampling = new DownsampleNone();
public setDataFetch(value: IDataFetch) { public setDataFetch(value: IDataFetch) {
this.dataFetch = value; this.dataFetch = value;
@ -194,4 +196,12 @@ export class SendableData{
public getPlaceHolderRegisterMemoryCacheKey(): string { public getPlaceHolderRegisterMemoryCacheKey(): string {
return this.placeholderRegisterMemoryCacheKey; return this.placeholderRegisterMemoryCacheKey;
} }
public setDownsampType(Type: BaseDownsampling): BaseDownsampling {
return this.downsampType = Type;
}
public getDownsampType(): BaseDownsampling {
return this.downsampType;
}
} }

View File

@ -0,0 +1,26 @@
/*
* Copyright (C) 2024 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 { 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
}

View File

@ -0,0 +1,149 @@
/*
* Copyright (C) 2024 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 { 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 < maxIntegerFactor ? 1 : 0)
return 1 / greaterOrEqualSampleSize
}
getSampleSizeRounding(sourceWidth: number, sourceHeight: number, requestWidth: number, requestHeight: number): number {
return 0
}
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 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 implements BaseDownsampling {
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
}

View File

@ -0,0 +1,134 @@
/*
* Copyright (C) 2024 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 { RequestOption } from '../RequestOption';
import { FileTypeUtil } from '../utils/FileTypeUtil';
import { CenterOutside, FitCenter, SampleSizeRounding } from './DownsampleStartegy';
let TAG = 'downsampling'
export interface calculateScaleType {
targetWidth: number,
targetHeight: number
}
export class Downsampler {
calculateScaling(
imageType: ArrayBuffer,
sourceHeight: number,
sourceWidth: number,
request?: RequestOption
): calculateScaleType {
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){
throw new Error("Cannot found width or height");
};
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 {
powerOfTwoWidth = orientedSourceWidth / powerOfTwoSampleSize;
powerOfTwoHeight = orientedSourceHeight / powerOfTwoSampleSize;
}
let a: calculateScaleType = { "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;
}
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);
}
}

View File

@ -13,8 +13,9 @@
* limitations under the License. * limitations under the License.
*/ */
import { BusinessError } from '@ohos.base' import { BusinessError } from '@ohos.base'
import { RequestOption } from '../RequestOption';
export interface IParseImage<T> { export interface IParseImage<T> {
parseImage:(imageinfo:ArrayBuffer, onCompleteFunction:(value:T)=>void | PromiseLike<T>, onErrorFunction:(reason?:BusinessError|string)=>void)=>void; parseImage:(imageinfo:ArrayBuffer, onCompleteFunction:(value:T)=>void | PromiseLike<T>, onErrorFunction:(reason?:BusinessError|string)=>void,request?:RequestOption)=>void;
parseImageThumbnail:(scale:number, imageinfo:ArrayBuffer, onCompleteFunction:(value:T)=>void | PromiseLike<T>, parseImageThumbnail:(scale:number, imageinfo:ArrayBuffer, onCompleteFunction:(value:T)=>void | PromiseLike<T>,
onErrorFunction:(reason?:BusinessError|string)=>void)=>void; onErrorFunction:(reason?:BusinessError|string)=>void)=>void;
} }

View File

@ -167,7 +167,7 @@ export class RequestManager {
// gif、webp处理 // gif、webp处理
if ((ImageKnifeData.GIF == typeValue || ImageKnifeData.WEBP == typeValue) && !request.dontAnimateFlag) { if ((ImageKnifeData.GIF == typeValue || ImageKnifeData.WEBP == typeValue) && !request.dontAnimateFlag) {
// 处理gif、webp // 处理gif、webp
this.gifProcess(onComplete, onError, arrayBuffer, typeValue) this.gifProcess(onComplete, onError, arrayBuffer, typeValue, request)
} else if (ImageKnifeData.SVG == typeValue) { } else if (ImageKnifeData.SVG == typeValue) {
// 处理svg // 处理svg
this.svgProcess(request, onComplete, onError, arrayBuffer, typeValue) this.svgProcess(request, onComplete, onError, arrayBuffer, typeValue)
@ -188,7 +188,7 @@ export class RequestManager {
let success = (value: PixelMap) => { let success = (value: PixelMap) => {
onComplete(value); onComplete(value);
} }
this.mParseImageUtil.parseImage(arrayBuffer, success, onError) this.mParseImageUtil.parseImage(arrayBuffer, success, onError,request)
} }
} }
} }
@ -266,7 +266,7 @@ export class RequestManager {
// 解析磁盘文件 gif、webp 和 svg // 解析磁盘文件 gif、webp 和 svg
if ((ImageKnifeData.GIF == typeValue || ImageKnifeData.WEBP == typeValue) && !request.dontAnimateFlag) { if ((ImageKnifeData.GIF == typeValue || ImageKnifeData.WEBP == typeValue) && !request.dontAnimateFlag) {
// 处理gif、webp // 处理gif、webp
this.gifProcess(onComplete, onError, source, typeValue) this.gifProcess(onComplete, onError, source, typeValue,request)
} else if (ImageKnifeData.SVG == typeValue) { } else if (ImageKnifeData.SVG == typeValue) {
this.svgProcess(request, onComplete, onError, source, typeValue) this.svgProcess(request, onComplete, onError, source, typeValue)
} else { } else {
@ -331,13 +331,13 @@ export class RequestManager {
let success = (value: PixelMap) => { let success = (value: PixelMap) => {
onComplete(value); onComplete(value);
} }
this.mParseImageUtil.parseImage(source, success, onError) this.mParseImageUtil.parseImage(source, success, onError,request)
}, this.options.thumbDelayTime) }, this.options.thumbDelayTime)
} else { } else {
let success = (value: PixelMap) => { let success = (value: PixelMap) => {
onComplete(value); onComplete(value);
} }
this.mParseImageUtil.parseImage(source, success, onError) this.mParseImageUtil.parseImage(source, success, onError,request)
} }
} }
} }
@ -360,13 +360,13 @@ export class RequestManager {
let success = (value: PixelMap) => { let success = (value: PixelMap) => {
onComplete(value); onComplete(value);
} }
this.mParseImageUtil.parseImage(source, success, onError) this.mParseImageUtil.parseImage(source, success, onError,request)
}, this.options.thumbDelayTime) }, this.options.thumbDelayTime)
} else { } else {
let success = (value: PixelMap) => { let success = (value: PixelMap) => {
onComplete(value); onComplete(value);
} }
this.mParseImageUtil.parseImage(source, success, onError) this.mParseImageUtil.parseImage(source, success, onError,request)
} }
} }
@ -396,7 +396,7 @@ export class RequestManager {
// 解析磁盘文件 gif、webp 和 svg // 解析磁盘文件 gif、webp 和 svg
if ((ImageKnifeData.GIF == filetype || ImageKnifeData.WEBP == filetype) && !this.options.dontAnimateFlag) { if ((ImageKnifeData.GIF == filetype || ImageKnifeData.WEBP == filetype) && !this.options.dontAnimateFlag) {
// 处理gif、webp // 处理gif、webp
this.gifProcess(onComplete, onError, source, filetype) this.gifProcess(onComplete, onError, source, filetype,request)
// 保存二级磁盘缓存 // 保存二级磁盘缓存
Promise.resolve(source) Promise.resolve(source)
@ -454,7 +454,7 @@ export class RequestManager {
this.saveCacheAndDisk(value, filetype, onComplete, source); this.saveCacheAndDisk(value, filetype, onComplete, source);
} }
} }
this.mParseImageUtil.parseImage(source, success, onError) this.mParseImageUtil.parseImage(source, success, onError,request)
}, this.options.thumbDelayTime) }, this.options.thumbDelayTime)
} else { } else {
let success = (value: PixelMap) => { let success = (value: PixelMap) => {
@ -462,7 +462,7 @@ export class RequestManager {
this.saveCacheAndDisk(value, filetype, onComplete, source); this.saveCacheAndDisk(value, filetype, onComplete, source);
} }
} }
this.mParseImageUtil.parseImage(source, success, onError) this.mParseImageUtil.parseImage(source, success, onError,request)
} }
} }
} }
@ -534,9 +534,17 @@ export class RequestManager {
svgParseImpl.parseSvg(option, arraybuffer, onComplete, onError) svgParseImpl.parseSvg(option, arraybuffer, onComplete, onError)
} }
private gifProcess(onComplete: (value: PixelMap | GIFFrame[]) => void | PromiseLike<ImageKnifeData>, onError: (reason?: BusinessError | string) => void, arraybuffer: ArrayBuffer, typeValue: string, cacheStrategy?: (cacheData: ImageKnifeData) => void) { private gifProcess(
onComplete: (value: PixelMap | GIFFrame[]) => void | PromiseLike<ImageKnifeData>,
onError: (reason?: BusinessError | string) => void,
arraybuffer: ArrayBuffer,
typeValue: string,
request?:RequestOption,
cacheStrategy?: (cacheData: ImageKnifeData) => void) {
let gifParseImpl = new GIFParseImpl() let gifParseImpl = new GIFParseImpl()
gifParseImpl.parseGifs(arraybuffer, (data?: GIFFrame[], err?: BusinessError | string) => { gifParseImpl.parseGifs(
arraybuffer,
(data?: GIFFrame[], err?: BusinessError | string) => {
if (err) { if (err) {
onError(err) onError(err)
} }
@ -552,6 +560,6 @@ export class RequestManager {
} else { } else {
onError('Parse GIF callback data is null, you need check callback data!') onError('Parse GIF callback data is null, you need check callback data!')
} }
}) },request)
} }
} }

View File

@ -16,15 +16,20 @@
import { IParseImage } from '../interface/IParseImage' import { IParseImage } from '../interface/IParseImage'
import image from '@ohos.multimedia.image'; import image from '@ohos.multimedia.image';
import { BusinessError } from '@ohos.base' import { BusinessError } from '@ohos.base'
import taskpool from '@ohos.taskpool'; import { RequestOption } from '../RequestOption';
import { LogUtil } from './LogUtil'; import {Downsampler,calculateScaleType } from '../downsampling/Downsampler';
export class ParseImageUtil implements IParseImage<PixelMap> { export class ParseImageUtil implements IParseImage<PixelMap> {
parseImage(imageinfo: ArrayBuffer, onCompleteFunction: (value: PixelMap) => void | PromiseLike<PixelMap>, onErrorFunction: (reason?: BusinessError | string) => void) { parseImage(
this.parseImageThumbnail(1, imageinfo, onCompleteFunction, onErrorFunction) imageinfo: ArrayBuffer,
onCompleteFunction: (value: PixelMap) => void | PromiseLike<PixelMap>,
onErrorFunction: (reason?: BusinessError | string) => void,
request?:RequestOption
) {
this.parseImageThumbnail(1, imageinfo, onCompleteFunction, onErrorFunction,request)
} }
parseImageThumbnail(scale: number, imageinfo: ArrayBuffer, onCompleteFunction: (value: PixelMap) => void | PromiseLike<PixelMap>, onErrorFunction: (reason?: BusinessError | string) => void) { parseImageThumbnail(scale: number, imageinfo: ArrayBuffer, onCompleteFunction: (value: PixelMap) => void | PromiseLike<PixelMap>, onErrorFunction: (reason?: BusinessError | string) => void,request?:RequestOption) {
let imageSource: image.ImageSource = image.createImageSource(imageinfo); // 步骤一文件转为pixelMap 然后变换 给Image组件 let imageSource: image.ImageSource = image.createImageSource(imageinfo); // 步骤一文件转为pixelMap 然后变换 给Image组件
imageSource.getImageInfo().then((value) => { imageSource.getImageInfo().then((value) => {
@ -38,7 +43,16 @@ export class ParseImageUtil implements IParseImage<PixelMap> {
editable: true, editable: true,
desiredSize: defaultSize desiredSize: defaultSize
}; };
if(request?.downsampType.getName()!==undefined && request?.downsampType.getName()!=='DownsampleNone'){
const b:calculateScaleType = new Downsampler().calculateScaling(imageinfo, hValue, wValue,request)
opts= {
editable: true,
desiredSize: {
height: b.targetHeight,
width: b.targetWidth
}
};
}
imageSource.createPixelMap(opts).then((pixelMap: image.PixelMap) => { imageSource.createPixelMap(opts).then((pixelMap: image.PixelMap) => {
onCompleteFunction(pixelMap); onCompleteFunction(pixelMap);
imageSource.release() imageSource.release()

View File

@ -19,6 +19,8 @@ import { BusinessError } from '@ohos.base'
import worker, { ErrorEvent, MessageEvents } from '@ohos.worker'; import worker, { ErrorEvent, MessageEvents } from '@ohos.worker';
import taskpool from '@ohos.taskpool' import taskpool from '@ohos.taskpool'
import { LogUtil } from '../LogUtil' import { LogUtil } from '../LogUtil'
import { RequestOption } from '../../RequestOption'
import { Downsampler,calculateScaleType } from '../../downsampling/Downsampler'
export interface senderData { export interface senderData {
type: string, type: string,
@ -34,7 +36,11 @@ export interface gifBackData {
} }
export class GIFParseImpl implements IParseGif { 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 imageSource = image.createImageSource(imageinfo);
let decodeOpts: image.DecodingOptions = { let decodeOpts: image.DecodingOptions = {
@ -42,7 +48,25 @@ export class GIFParseImpl implements IParseGif {
editable: true, editable: true,
rotate: 0 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);
if ( _request?.downsampType.getName()!==undefined && _request?.downsampType.getName()!=='DownsampleNone') {
const b: calculateScaleType = new Downsampler().calculateScaling(imageinfo, Math.round(value.size.height), Math.round(value.size.width), _request)
decodeOpts = {
sampleSize: 1,
editable: true,
rotate: 0,
desiredSize: {
width: b.targetWidth,
height: b.targetHeight
}
}
}
})
let data: GIFFrame[] = [];
imageSource.createPixelMapList(decodeOpts).then((pixelList: Array<PixelMap>) => { imageSource.createPixelMapList(decodeOpts).then((pixelList: Array<PixelMap>) => {
//sdk的api接口发生变更从.getDelayTime() 变为.getDelayTimeList() //sdk的api接口发生变更从.getDelayTime() 变为.getDelayTimeList()
imageSource.getDelayTimeList().then(delayTimes => { imageSource.getDelayTimeList().then(delayTimes => {
@ -60,20 +84,20 @@ export class GIFParseImpl implements IParseGif {
} }
data.push(frame) data.push(frame)
} }
callback(data,undefined) callback(data, undefined)
imageSource.release(); imageSource.release();
}).catch((err: string) => { }).catch((err: string) => {
imageSource.release(); imageSource.release();
callback(undefined,err) callback(undefined, err)
}) })
} }
}).catch((err: string) => { }).catch((err: string) => {
imageSource.release(); imageSource.release();
callback(undefined,err) callback(undefined, err)
}) })
}).catch((err: string) => { }).catch((err: string) => {
imageSource.release(); imageSource.release();
callback(undefined,err) callback(undefined, err)
}) })
} }
} }

View File

@ -15,7 +15,12 @@
import { BusinessError } from '@ohos.base' import { BusinessError } from '@ohos.base'
import { GIFFrame } from './GIFFrame' import { GIFFrame } from './GIFFrame'
import worker from '@ohos.worker'; import worker from '@ohos.worker';
export interface IParseGif{ import { RequestOption } from '../../RequestOption'
export interface IParseGif {
// gif解析 // 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: RequestOption,
worker?: worker.ThreadWorker, runMainThread?: boolean) => void,
} }

View File

@ -17,6 +17,7 @@ import { RequestOption } from '../../RequestOption'
import { BusinessError } from '@ohos.base' import { BusinessError } from '@ohos.base'
import { ImageKnifeData, ImageKnifeType } from '../../ImageKnifeData' import { ImageKnifeData, ImageKnifeType } from '../../ImageKnifeData'
import image from '@ohos.multimedia.image' import image from '@ohos.multimedia.image'
import { Downsampler, calculateScaleType } from '../../downsampling/Downsampler'
export class SVGParseImpl implements IParseSvg { export class SVGParseImpl implements IParseSvg {
parseSvg(option: RequestOption, imageInfo: ArrayBuffer, parseSvg(option: RequestOption, imageInfo: ArrayBuffer,
@ -24,8 +25,9 @@ export class SVGParseImpl implements IParseSvg {
onErrorFunction: (reason?: BusinessError | string) => void) { onErrorFunction: (reason?: BusinessError | string) => void) {
let imageSource: image.ImageSource = image.createImageSource(imageInfo); // 步骤一文件转为pixelMap 然后变换 给Image组件 let imageSource: image.ImageSource = image.createImageSource(imageInfo); // 步骤一文件转为pixelMap 然后变换 给Image组件
let hValue = Math.round(option.size.height); imageSource.getImageInfo().then((value) => {
let wValue = Math.round(option.size.width); let hValue = Math.round(value.size.height);
let wValue = Math.round(value.size.width);
let defaultSize: image.Size = { let defaultSize: image.Size = {
height: hValue, height: hValue,
width: wValue width: wValue
@ -34,6 +36,16 @@ export class SVGParseImpl implements IParseSvg {
editable: true, editable: true,
desiredSize: defaultSize desiredSize: defaultSize
}; };
if (option?.downsampType.getName()!==undefined && option?.downsampType.getName()!=='DownsampleNone') {
const b: calculateScaleType = new Downsampler().calculateScaling(imageInfo, hValue, wValue, option)
opts = {
editable: true,
desiredSize: {
width: b.targetWidth,
height: b.targetHeight
}
}
}
imageSource.createPixelMap(opts).then((pixelMap: image.PixelMap) => { imageSource.createPixelMap(opts).then((pixelMap: image.PixelMap) => {
let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, pixelMap) let imageKnifeData = ImageKnifeData.createImagePixelMap(ImageKnifeType.PIXELMAP, pixelMap)
onComplete(imageKnifeData?.drawPixelMap?.imagePixelMap as PixelMap); onComplete(imageKnifeData?.drawPixelMap?.imagePixelMap as PixelMap);
@ -42,5 +54,6 @@ export class SVGParseImpl implements IParseSvg {
onErrorFunction(err); onErrorFunction(err);
imageSource.release() imageSource.release()
}) })
})
} }
} }