1/* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import { Log } from '../utils/Log'; 17 18const TAG = "ImageUtil" 19const MAX_BIT = 30; 20const BIT_SIXTEEN = 16; 21const BIT_EIGHT = 8; 22const BIT_FOUR = 4; 23const BIT_TWO = 2; 24const BIT_ONE = 1; 25 26export function computeSampleSize(width: number, height: number, minSideLength: number, maxNumOfPixels: number): number { 27 if (width == 0 || height == 0 || minSideLength == 0 || maxNumOfPixels == 0) { 28 return 2; 29 } 30 let initialSize = computeInitialSampleSize(width, height, minSideLength, maxNumOfPixels); 31 Log.info(TAG, `initialSize: ${initialSize}`); 32 return initialSize <= 8 ? nextPowerOf2(initialSize) : Math.floor((initialSize + 8 - 1) / 8) * 8; 33} 34 35function computeInitialSampleSize(width: number, height: number, minSideLength: number, maxNumOfPixels: number): number { 36 if ((maxNumOfPixels == -1) && (minSideLength == -1)) { 37 return 1; 38 } 39 let lowerBound: number = (maxNumOfPixels == -1) ? 1 : Math.ceil(Math.sqrt((width * height) / maxNumOfPixels)); 40 Log.info(TAG, `lowerBound: ${lowerBound}`); 41 if (minSideLength == -1) { 42 return lowerBound; 43 } else { 44 let sampleSize = Math.min(width / minSideLength, height / minSideLength); 45 return Math.max(sampleSize, lowerBound); 46 } 47} 48 49function nextPowerOf2(value: number): number { 50 let useValue = value; 51 if (useValue <= 0 || useValue > (1 << MAX_BIT)) { 52 } 53 useValue -= 1; 54 useValue |= useValue >> BIT_SIXTEEN; 55 useValue |= useValue >> BIT_EIGHT; 56 useValue |= useValue >> BIT_FOUR; 57 useValue |= useValue >> BIT_TWO; 58 useValue |= useValue >> BIT_ONE; 59 Log.info(TAG, `nextPowerOf2:${useValue}`); 60 return useValue + 1; 61}