Чтобы преобразовать строку Base64 в изображение PNG в Node.js, вы можете использовать несколько методов. Вот несколько вариантов:
Метод 1: использование модуля «fs» и буфера
const fs = require('fs');
// Base64 string
const base64String = '<your Base64 string>';
// Remove the data URI prefix
const base64Data = base64String.replace(/^data:image\/png;base64,/, '');
// Create a buffer from the Base64 data
const buffer = Buffer.from(base64Data, 'base64');
// Write the buffer to a file
fs.writeFileSync('image.png', buffer);
Способ 2: использование библиотеки «pngjs»
const fs = require('fs');
const PNG = require('pngjs').PNG;
// Base64 string
const base64String = '<your Base64 string>';
// Remove the data URI prefix
const base64Data = base64String.replace(/^data:image\/png;base64,/, '');
// Create a buffer from the Base64 data
const buffer = Buffer.from(base64Data, 'base64');
// Parse the PNG buffer
const png = PNG.sync.read(buffer);
// Write the PNG image to a file
fs.writeFileSync('image.png', PNG.sync.write(png));
Метод 3. Использование библиотеки Sharp
const fs = require('fs');
const sharp = require('sharp');
// Base64 string
const base64String = '<your Base64 string>';
// Remove the data URI prefix
const base64Data = base64String.replace(/^data:image\/png;base64,/, '');
// Create a buffer from the Base64 data
const buffer = Buffer.from(base64Data, 'base64');
// Convert the buffer to a PNG image
sharp(buffer)
.toFile('image.png')
.then(() => console.log('Image converted successfully'))
.catch(err => console.error('Error converting image:', err));