Created
June 27, 2022 15:03
-
-
Save lazuee/d3c90ee44ca434d52dad58cde89d0555 to your computer and use it in GitHub Desktop.
scale image to size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import graphicsmagick from 'gm'; | |
export async function scaleImageToSize( | |
image: Buffer, | |
filename: string, | |
baseWidth: number, | |
baseHeight: number, | |
size: number, | |
): Promise<Buffer> { | |
let width = baseWidth; | |
let height = baseHeight; | |
const isHorizontal = baseWidth > baseHeight; | |
const maximumPixels = size / 4; // PNG is 4 bytes per pixel | |
let area: number; | |
do { | |
if (isHorizontal) { | |
width--; // horizontal image | |
height = Math.floor((baseHeight / baseWidth) * width); | |
} else { | |
height--; // vertical image | |
width = Math.floor((baseWidth / baseHeight) * height); | |
} | |
area = width * height; | |
} while (area > maximumPixels); | |
const gm = graphicsmagick(image, filename); | |
return new Promise<Buffer>((resolve) => { | |
gm.scale(width, height).toBuffer('PNG', (err, buffer) => { | |
console.log('Image scaled to ' + width + 'x' + height + ' @ ' + (buffer.length / 1024 / 1024).toFixed(2) + 'MB'); | |
resolve(buffer); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment