filipedeschamps / video-maker

Projeto open source para fazer vídeos automatizados
MIT License
2.43k stars 629 forks source link

UnhandledPromiseRejectionWarning: Error: Command failed: convert-im6.q16: unable to open image #127

Closed filipeamaldonado closed 9 months ago

filipeamaldonado commented 5 years ago

Quando executo o node está aparecendo o seguinte erro como retorno e já não sei mais o que fazer

(node:5459) UnhandledPromiseRejectionWarning: Error: Command failed: convert-im6.q16: unable to open image `./content/9-original.png': No such file or directory @ error/blob.c/OpenBlob/2701.
convert-im6.q16: image sequence is required `-clone' @ error/convert.c/ConvertImageCommand/980.

    at ChildProcess.onExit (/mnt/c/users/***/documents/projetos/github/video-maker/node_modules/gm/lib/command.js:301:17)
    at emitTwo (events.js:126:13)
    at ChildProcess.emit (events.js:214:7)
    at maybeClose (internal/child_process.js:925:16)
    at Socket.stream.socket.on (internal/child_process.js:346:11)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at Pipe._handle.close [as _onclose] (net.js:567:12)
(node:5459) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:5459) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Eu não consigo chegar nesse ponto do video de hoje, e avançar.

Eu uso: Ubuntu on Windows 1804.2018.817.0 NPM 6.9.0 Node.JS v8.10.0 ImageMagick 6.9.7-4 Q16 x86_64 20170114

O arquivo image.js que fiz

const gm = require('gm').subClass({imageMagick: true})
const google = require('googleapis').google
const googleSearchCredentials = require('../credentials/google-search.json')
const imageDownloader = require('image-downloader')
const state = require('./state.js')

const customSearch = google.customsearch('v1')

async function robot() {
    const content = state.load()
    // await fetchImagesOfAllSentences(content)
    // await downloadAllImages(content)
    // state.save(content)
    await convertAllImages(content)

    async function convertAllImages(content) {
        for (let sentenceIndex = 0; sentenceIndex = content.sentences.length; sentenceIndex++) {
                await convertImage(sentenceIndex)
        }
    }

    async function convertImage(sentenceIndex) {
        return new Promise((resolve, reject) => {
            const inputFile = `./content/${sentenceIndex}-original.png[0]`
            const outputFile = `./content/${sentenceIndex}-converted.png`
            const width = 1920
            const height = 1080

            gm()
                .in(inputFile)
                .out('(')
                    .out('-clone')
                    .out('0')
                    .out('-background', 'white')
                    .out('-blur', '0x9')
                    .out('-resize', `${width}x${height}^`)
                .out(')')
                .out('(')
                    .out('-clone')
                    .out('0')
                    .out('-background', 'white')
                    .out('-resize', `${width}x${height}`)
                .out(')')
                .out('-delete', '0')
                .out('-gravity', 'center')
                .out('-compose', 'over')
                .out('-composite')
                .out('-extent', `${width}x${height}`)
                .write(outputFile, (error) => {
                    if (error) {
                        return reject(error)
                    }

                    console.log(`> Image converted: ${inputFile}`)
                    resolve()
                })
        })
    }

    async function downloadAllImages(content) {
        content.downloadedImages = []

        for (let sentenceIndex = 0; sentenceIndex < content.sentences.length; sentenceIndex++ ){
            const images = content.sentences[sentenceIndex].images

            for (let imageIndex = 0; imageIndex < images.length; imageIndex++) {
                const imageUrl = images[imageIndex]

                try {
                    if (content.downloadedImages.includes(imageUrl)) {
                        throw new Error('Imagem já foi baixada')
                    }
                    await downloadAndSave(imageUrl, `${sentenceIndex}-original.png`)
                    content.downloadedImages.push(imageUrl)
                    console.log(`[${sentenceIndex}][${imageIndex}]> Baixou imagem com sucesso: ${imageUrl}`)
                    break
                } catch(error) {
                    console.log(`[${sentenceIndex}][${imageIndex}]> Erro ao baixar (${imageUrl}): ${error}`)
                }
            }
        }
    }

    async function downloadAndSave(url, fileName) {
        return imageDownloader.image({
            url, url,
            dest: `./content/${fileName}`
        })
    }

    async function fetchGoogleAndReturnImagesLinks(query) {
        const response = await customSearch.cse.list({
            auth: googleSearchCredentials.apiKey,
            cx: googleSearchCredentials.searchEngineID,
            q: query,
            searchType: 'image',
            num: 2
        })

        const imagesUrl = response.data.items.map((item) => {
            return item.link
        })

        return imagesUrl
    }

    async function fetchImagesOfAllSentences(content){
        for (const sentence of content.sentences){
            const query = `${content.searchTerm} ${sentence.keywords[0]}`
            sentence.images = await fetchGoogleAndReturnImagesLinks(query)

            sentence.googleSearchQuery = query
        }
    }
}

module.exports = robot
JoaoPedroCJ commented 5 years ago

eu tive um problema parecido com o arquivo, eu usei path.resolve e não tive mais problema com o arquivo

no inicio vc cria uma constante

const path = require('path')

e na hora de chamar o arquivo vc usa o resolve


const inputFile = path.resolve(__dirname, '..', 'content', `${sentenceIndex}-original.png[0]`)
const outputFile = path.resolve(__dirname, '..', 'content', `${sentenceIndex}-converted.png`)
cabral-ricardo commented 5 years ago

126

leodutra commented 4 years ago

@MatheusRV Resolvi isso agora no meu local. Acontece uma divergência por vezes do uso do CMD ou Git Bash que estou tentando resolver.

thomas-amarante commented 4 years ago
`(node:6699) UnhandledPromiseRejectionWarning: Error: Command failed: convert: unable to open image 'blur': No such file or directory @ error/blob.c/OpenBlob/3496.
convert: no decode delegate for this image format `' @ error/constitute.c/ReadImage/562.
convert: unable to open image '0x9': No such file or directory @ error/blob.c/OpenBlob/3496.
convert: unable to open image '0x9': No such file or directory @ error/blob.c/OpenBlob/3496.
convert: no decode delegate for this image format `' @ error/constitute.c/ReadImage/562.
convert: invalid argument for option '-resize': 1920x1080ˆ @ error/convert.c/ConvertImageCommand/2616.

    at ChildProcess.onExit (/Users/*****/Bot-video-maker/node_modules/gm/lib/command.js:301:17)
    at ChildProcess.emit (events.js:189:13)
    at maybeClose (internal/child_process.js:970:16)
    at Socket.stream.socket.on (internal/child_process.js:389:11)
    at Socket.emit (events.js:189:13)
    at Pipe._handle.close (net.js:597:12)
 (node:6699) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error    originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:6699) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

`

Fala galera, bele?

Estou fazendo o passo-a-passo da playlist e me deparei com esse erro quando é necessário tratar as imagens com o ImageMagick implementando o gm().

Algum de vocês passou por isso? Mesmo se n passou, alguma idéia do que possa ser?

Tentei a solução postada acima do path.resolve mas tbm não adiantou.

Agradeço desde já!

Utilizo MacOS com High Sierra 10.13.6 NPM 6.14.5 Node 10.15.3 ImageMagick 7.0.10-14 Q16 x86_64 2020-05-25

leodutra commented 4 years ago

O seu erro ali é a falta de uma imagem no caminho do disco.

thomas-amarante commented 4 years ago

Acabei de ver em um outro Issue aberto aqui uma alternativa que troca o parâmetro 'convert' para 'magick', pois lendo o erro entendi que ele não reconhecia o blur e outras como uma operação válida. Alterei isso e aponta um erro na operação resize. Talvez eu esteja escrevendo errado algum argumento. Veja o erro:

(node:8270) UnhandledPromiseRejectionWarning: Error: Command failed: magick: unable to open image 'resize': No such file or directory @ error/blob.c/OpenBlob/3496.
magick: no decode delegate for this image format `' @ error/constitute.c/ReadImage/562.

    at ChildProcess.onExit (/Users/*****/Bot-video-maker/node_modules/gm/lib/command.js:301:17)
    at ChildProcess.emit (events.js:189:13)
    at maybeClose (internal/child_process.js:970:16)
    at Socket.stream.socket.on (internal/child_process.js:389:11)
    at Socket.emit (events.js:189:13)
    at Pipe._handle.close (net.js:597:12)
(node:8270) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:8270) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
thomas-amarante commented 4 years ago

Consegui.

Além de ir no diretório do GraphicMagick (...node_modules/gm/lib/index.js) e alterar o parâmetro conforme falei acima (dica postada aqui na Issue #110 no comentário: https://github.com/filipedeschamps/video-maker/issues/110#issuecomment-487408677 ) eu corrigi todo o trecho do código a partir da linha gm().

Obrigado pelo auxílio!

matbrgz commented 9 months ago

Fico feliz que tenha resolvido. Irei fechar o issue, caso necessário posso abrir novamente.