1/* 2 * Copyright (c) 2021 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 16const Jimp = require('jimp'); 17const fs = require('fs'); 18const _path = require('path'); 19/** 20 * Find all image paths in png、jpg、bmp、jpeg format in the directory. 21 * @param {String} imgPath The path of build folder. 22 * @return {Array} Image path array. 23 */ 24async function img2bin(imgPath) { 25 try { 26 const image = await Jimp.read(imgPath); 27 const HEAD_SIZE = 8; 28 const PIXEL_SIZE = 4;// BRGA 29 const DATA_SIZE = image.bitmap.width * image.bitmap.height * PIXEL_SIZE; 30 const binSize = HEAD_SIZE + DATA_SIZE; 31 const binBuffer = new ArrayBuffer(binSize); 32 const binView = new DataView(binBuffer); 33 34 const COLOR_MODE = 1 << 8 + 0; 35 const WIDTH_BIT_OFFSET = 0; 36 const HEIGHT_BIT_OFFSET = 16; 37 const header = (image.bitmap.width << WIDTH_BIT_OFFSET) + 38 (image.bitmap.height << HEIGHT_BIT_OFFSET); 39 40 let binFileOffset = 0; 41 binView.setUint32(binFileOffset, COLOR_MODE, true); 42 binFileOffset += 4; 43 binView.setUint32(binFileOffset, header, true); 44 binFileOffset += 4; 45 46 image.scan(0, 0, image.bitmap.width, image.bitmap.height, function(x, y, idx) { 47 // eslint-disable-next-line no-invalid-this 48 const blue = this.bitmap.data[idx + 2]; 49 binView.setUint8(binFileOffset, blue, true); 50 binFileOffset += 1; 51 52 // eslint-disable-next-line no-invalid-this 53 const green = this.bitmap.data[idx + 1]; 54 binView.setUint8(binFileOffset, green, true); 55 binFileOffset += 1; 56 57 // eslint-disable-next-line no-invalid-this 58 const red = this.bitmap.data[idx + 0]; 59 binView.setUint8(binFileOffset, red, true); 60 binFileOffset += 1; 61 62 // eslint-disable-next-line no-invalid-this 63 const alpha = this.bitmap.data[idx + 3]; 64 binView.setUint8(binFileOffset, alpha, true); 65 binFileOffset += 1; 66 }); 67 if (process.env.PLATFORM_VERSION_VERSION <=6) { 68 const binPath1 = imgPath.replace(/(\.png|\.jpg|\.bmp|\.jpeg|\.BMP|\.JPG|\.PNG|\.JPEG)$/, '.bin'); 69 fs.writeFileSync(binPath1, Buffer.from(binBuffer)); 70 } 71 const binPath2 = imgPath+".bin"; 72 fs.writeFileSync(binPath2, Buffer.from(binBuffer)); 73 } catch (err) { 74 const imageName = _path.basename(imgPath); 75 console.error('\u001b[31m', `Failed to convert image ${imageName}.`, '\u001b[39m'); 76 throw err; 77 } 78} 79 80module.exports = img2bin; 81