Created
May 16, 2023 21:55
-
-
Save ulisseshen/71cc19d0288f22779e1fdbaa387b6318 to your computer and use it in GitHub Desktop.
Como cortar uma imagem em partes usando Node.js e Sharp
This file contains hidden or 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
const sharp = require('sharp'); | |
const imagePath = './imagens/to_split.png'; | |
sharp(imagePath) | |
.metadata() | |
.then(async metadata => { | |
// Divide a largura e altura da imagem em duas partes | |
const halfWidth = Math.floor(metadata.width / 2); | |
const halfHeight = Math.floor(metadata.height / 2); | |
// Cria um objeto de transformação para cortar a primeira parte superior esquerda | |
const topLeft = sharp(imagePath) | |
.extract({ left: 0, top: 0, width: halfWidth, height: halfHeight }); | |
// Cria um objeto de transformação para cortar a segunda parte superior direita | |
const topRight = sharp(imagePath) | |
.extract({ left: halfWidth, top: 0, width: halfWidth, height: halfHeight }); | |
// Cria um objeto de transformação para cortar a terceira parte inferior esquerda | |
const bottomLeft = sharp(imagePath) | |
.extract({ left: 0, top: halfHeight, width: halfWidth, height: halfHeight }); | |
// Cria um objeto de transformação para cortar a quarta parte inferior direita | |
const bottomRight = sharp(imagePath) | |
.extract({ left: halfWidth, top: halfHeight, width: halfWidth, height: halfHeight }); | |
// Salva as partes cortadas em arquivos separados | |
await Promise.all([ | |
topLeft.toFile('imagens/topLeft.jpg'), | |
topRight.toFile('imagens/topRight.jpg'), | |
bottomLeft.toFile('imagens/bottomLeft.jpg'), | |
bottomRight.toFile('imagens/bottomRight.jpg') | |
]); | |
}) | |
.catch(err => { | |
console.error('Erro ao cortar a imagem:', err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment