[英]How to correctly use streams to retrieve, edit, save and send image via discordbot
我正在使用 DSharp plus 庫編寫一個 discord 機器人。
我目前正在編寫的命令從 discord 聊天中獲取圖像,然后我編輯圖像並將編輯后的圖像作為單幀 gif 發回。
我使用以下方法從圖像 url 中檢索圖像:
HttpClient client = new HttpClient();
Stream stream = await client.GetStreamAsync(attachments[0].Url);
Bitmap image = new Bitmap(System.Drawing.Image.FromStream(stream));
然后我打電話給我的編輯 function 並編輯圖像。 然后我使用以下方法將圖像保存到我的文件中:
using (var stream = new FileStream("Images/output.gif", FileMode.Create))
{
imgToGif.SaveAsGif(stream);
}
其中.SaveAsGif()
是我在網上找到的 KGySoft.Drawing 庫中的 function。
要將編輯后的圖像發回,我使用:
FileStream file = new FileStream("Images/output.gif", FileMode.Open);
DiscordMessageBuilder messagefile = new DiscordMessageBuilder();
messagefile.AddFile(file);
ctx.RespondAsync(messagefile);
但這會引發“該進程無法訪問文件“Image/output.gif”,因為它正被另一個進程使用。” 錯誤。
經過一番谷歌搜索后,我嘗試使用stream.close() or stream.dispose()
關閉將圖像保存到文件中的 FileStream。 然而,問題是我無法再次訪問 stream,因為它會拋出“無法訪問關閉 stream 錯誤”。
我也嘗試使用FileShare.read, FileShare.ReadWrite
。
嘗試同時關閉 stream 並嘗試僅使用 1 stream。 所以我讓 stream 保持打開狀態,並用它在 discord 聊天中發送消息,但這會在 discord 聊天中發送一個 0 字節的文件。
我認為您在發送 gif 時過早關閉了 stream
您需要在調用file.Close()
之后調用 file.Close( RespondAsync()
並且您需要更改ctx.RespondAsync(messagefile);
await ctx.RespondAsync(messagefile);
因為RespondAsync()
是一種異步方法,如果您不使用await
rest 代碼將繼續運行,因此 stream 將關閉,而ctx.RespondAsync(messagefile);
仍在運行,它會報錯。
發送 gif 部分應如下所示:
FileStream file = new FileStream("Images/output.gif", FileMode.Open);
DiscordMessageBuilder messagefile = new DiscordMessageBuilder();
messagefile.AddFile(file);
await ctx.RespondAsync(messagefile);
file.Close();
如果你已經完成了 rest 的代碼正確這應該工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.