Я хочу создать миниатюру PNG из разных файлов, загруженных в корзину Google Storage.На данный момент я ориентируюсь на изображения и PDF-файлы.Для изображений функции работают нормально, но для PDF я не могу заставить его работать.Идея состоит в том, чтобы загрузить файл из корзины, выполнить работу и затем загрузить новый файл (миниатюру PNG) в корзину.
Итак, я проверяю тип загруженного файла иесли файл является изображением, я выполняю преобразование с помощью функции createImageFromImage
, а если это PDF, я использую createImageFromPDF
.
Основная функция:
const gm = require('gm').subClass({imageMagick: true});
const fs = require('fs');
const path = require('path');
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const im = require('imagemagick');
exports.generatePreviewImage = event => {
const object = event.data || event; // Node 6: event.data === Node 8+: event
const file = storage.bucket(object.bucket).file(object.name);
const filePath = `gs://${object.bucket}/${object.name}`;
// Ignore already-resized files (to prevent re-invoking this function)
if (file.name.endsWith('-thumb.png')) {
console.log(`The image ${file.name} is already resized.`);
return;
} else {
console.log(`Analyzing ${file.name}.`);
// Check the file extension
if(object.contentType.startsWith('image/')) { // It's an image
console.log("This is an image!")
return createImageFromImage(file);
} else if (object.contentType === 'application/pdf') { // It's a PDF
console.log("This is a PDF file!")
return createImageFromPDF(file);
} else {
return;
}
}
};
createImageFromImage (file) - который работает
function createImageFromImage(file) {
const tempLocalPath = `/tmp/${path.parse(file.name).base}`;
// Download file from bucket.
return file
.download({destination: tempLocalPath})
.catch(err => {
console.error('Failed to download file.', err);
return Promise.reject(err);
})
.then(() => {
console.log(
`Image ${file.name} has been downloaded to ${tempLocalPath}.`
);
// Resize the image using ImageMagick.
return new Promise((resolve, reject) => {
gm(tempLocalPath)
.resize(250)
.setFormat('png')
.write(tempLocalPath, (err, stdout) => {
if (err) {
console.error('Failed to resize the image.', err);
reject(err);
} else {
resolve(stdout);
}
});
});
})
.then(() => {
console.log(`Image ${file.name} has been resized.`);
// Get the name of the file without the file extension and mark the result as resized, to avoid re-triggering this function.
const newName = `${path.parse(file.name).name}-thumb.png`;
// Upload the Blurred image back into the bucket.
return file.bucket
.upload(tempLocalPath, {destination: newName})
.catch(err => {
console.error('Failed to upload resized image.', err);
return Promise.reject(err);
});
})
.then(() => {
console.log(`Resized image has been uploaded to ${file.name}.`);
// Delete the temporary file.
return new Promise((resolve, reject) => {
fs.unlink(tempLocalPath, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
});
}
createImageFromPDF (файл) - который не работает
function createImageFromPDF(file) {
const tempLocalPath = `/tmp/${path.parse(file.name).base}`;
return file
.download({destination: tempLocalPath}) // Download file from bucket.
.catch(err => {
console.error('Failed to download file.', err);
return Promise.reject(err);
})
.then(() => { // Convert the file to PDF.
console.log(`File ${file.name} has been downloaded to ${tempLocalPath}.`);
return new Promise((resolve, reject) => {
im.convert([tempLocalPath, '-resize', '250x250', `${path.parse(file.name).name}-thumb.png`],
function(err, stdout) {
if (err) {
reject(err);
} else {
resolve(stdout);
}
});
});
})
.then(() => { // Upload the new image to the bucket
console.log(`File ${file.name} has been resized.`);
// Get the name of the file without the file extension and mark the result as resized, to avoid re-triggering this function.
const newName = `${path.parse(file.name).name}-thumb.png`;
// Upload the Blurred image back into the bucket.
return file.bucket
.upload(tempLocalPath, {destination: newName})
.catch(err => {
console.error('Failed to upload resized image.', err);
return Promise.reject(err);
});
})
.then(() => { // Delete the temporary file.
console.log(`Resized image has been uploaded to ${file.name}.`);
return new Promise((resolve, reject) => {
fs.unlink(tempLocalPath, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
});
}
Я получаю ошибку от im.convert
, которая говорит: Command failed: convert: no images defined 'test1-thumb.png' @ error/convert.c/ConvertImageCommand/3210.
Я не уверенЕсли это правильный способ создания эскиза PNG из файла PDF, я безуспешно пробовал другие решения.Посоветуйте пожалуйста что я делаю не так.Спасибо!