亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Node JS(fs 和 http)保存后無法打開 JPG 或 PNG

使用 Node JS(fs 和 http)保存后無法打開 JPG 或 PNG

BIG陽 2024-01-18 20:41:42
我的代碼的目標是 1)用戶將發送圖像 URL 2)機器人讀取 URL 3)機器人將圖像保存到“images”文件夾中 4)機器人使用 tfjs 將圖像轉換為張量 5)機器人使用COCO-SSD JS作為預訓練模型(以圖像張量為參數)并打印然后發送結果?,F在,我的問題是,每當我嘗試使用圖像的 URL 保存圖像時,我都會得到一個程序和 Windows 都無法讀取的文件!它工作過一次,能夠打開和使用文件。但現在返回 Windows 10 無法讀取 .PNG 或 .JPG 文件的文件。這是我的代碼:    const {Client, MessageAttachment} = require('discord.js');    const bot = new Client();    const tf = require('@tensorflow/tfjs-node');    const ts = require('@tensorflow/tfjs-core');    require('@tensorflow/tfjs-backend-cpu');    require('@tensorflow/tfjs-backend-webgl');    const coco = require('@tensorflow-models/coco-ssd');    const fs = require('fs');    const fetch = require("node-fetch");    const https = require('https');    const request = require('request');      bot.on('message', gotMessage);    function gotMessage(msg) {        if(msg.content === '!object')  {               const attachments = (msg.attachments).array();            const filepath = "./images/" + Date.now() + "J" + ".jpg";            console.log(filepath);            const imageurl = attachments[0].url;            saveImageToDisk(imageurl,filepath)            const img_buffer = fs.readFileSync(filepath)            const img = tf.node.decodeImage(img_buffer)            coco.load().then(model => {                // detect objects in the image.                model.detect(img).then(predictions => {                    console.log('Predictions: ', predictions);                });              });            msg.reply('Enjoy');            msg.channel.send(attachments[0].url);        }    }    function saveImageToDisk(url,path) {        var fullUrl = url;        var localPath = fs.createWriteStream(path);        var request = https.get(fullUrl,function(response) {             console.log(response)            response.pipe(localPath)        });    }PS:后面的“J”Date.now()是有意的。
查看完整描述

1 回答

?
慕標5832272

TA貢獻1966條經驗 獲得超4個贊

我看到的是你的應用程序完全不同步 - 我的意思是


你有saveImageToDisk(imageurl,filepath)它將文件寫入磁盤,但它執行,將文件寫入隊列,aa,然后你用同步讀?。ㄉ形幢4妫┪募?。


我將嘗試對它進行一些修復,以向您展示至少一種執行此操作的方法 - 但在規劃應用程序的流程時,您需要考慮代碼中的一些同步。


console.log('Authenticating bot...');


const {Client, MessageAttachment} = require('discord.js');

const bot = new Client();

const tf = require('@tensorflow/tfjs-node');

const ts = require('@tensorflow/tfjs-core');

require('@tensorflow/tfjs-backend-cpu');

require('@tensorflow/tfjs-backend-webgl');

const coco = require('@tensorflow-models/coco-ssd');

const fs = require('fs');

const fetch = require("node-fetch");

const https = require('https');

const request = require('request');


bot.login('BOTTOKEN');


bot.on('ready', readyDiscord);


function readyDiscord() {

    console.log('Authenticated and On!');

}


bot.on('message', gotMessage);


async function gotMessage(msg) {

    if(msg.content === '!object')  {   

        const attachments = (msg.attachments).array();


        const filepath = "./images/" + Date.now() + "J" + ".jpg";

        console.log(filepath);

        const imageurl = attachments[0].url;


        await saveImageToDisk(imageurl,filepath)


        const img_buffer = fs.readFileSync(filepath)

        const img = tf.node.decodeImage(img_buffer)


        coco.load().then(model => {

            // detect objects in the image.

            model.detect(img).then(predictions => {

                console.log('Predictions: ', predictions);

            });

          });

        msg.reply('Enjoy');

        msg.channel.send(attachments[0].url);

    }

}

async function saveImageToDisk(url,path) {

  return new Promise((resolve, reject) => {

    var fullUrl = url;

    var localPath = fs.createWriteStream(path);

    var request = https.get(fullUrl,function(response) { 

        console.log(response)

        response.pipe(localPath)

        response.on('end', resolve);

    }).on('error', reject);

  });

}

這樣,在執行讀取尚未填充的文件的代碼之前,代碼將等待,直到文件被寫入(或發生錯誤) - 您當然應該嘗試捕獲錯誤并處理它們。


查看完整回答
反對 回復 2024-01-18
  • 1 回答
  • 0 關注
  • 269 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號