我正在尝试从方法中获取Image(ImageSharp(,然后将其作为参数传递给另一个方法并通过电子邮件发送,但我收到了Object Disposed Exception。
以下是我的代码的样子:
public async Task<Unit> Handle( CancellationToken cancellationToken)
{
...
var ticketImage = await ticket.GetTicketWithQRCode(cancellationToken);
_emailService.Send(ticketImage);
return new Unit();
}
async public Task<Image> GetTicketWithQRCode(CancellationToken cancellationToken)
{
var qrCode = QrCode.EncodeText($@"
{{
Id:""{this.TickedGuid}"",
UserData:""{this.TickedUserData.Name} {this.TickedUserData.Surname}""
}}
", QrCode.Ecc.Quartile);
using var imageBase = await Image.LoadAsync<Rgba32>($"/var/opt/clubapp/images/{this.Ticket.Image.ImageSrc}", cancellationToken);
using var imageWithQRCode = new Image<Rgba32>(imageBase.Width, imageBase.Height);
imageWithQRCode.CombineWithBaseImageAndQrCode(imageBase, qrCode, new Size() { Width = 390, Height = 495 }, 250);
await imageWithQRCode.ResizeToHasMaximumFileSize(1.5, cancellationToken);
var imageRatio = imageWithQRCode.Width / imageWithQRCode.Height;
imageWithQRCode.Mutate(x => x.Resize(new ResizeOptions() { Mode = ResizeMode.Max, Size = new Size() { Height = 100, Width = 100 * imageRatio } }));
return imageWithQRCode;
}
public string Send(Image image)
{
var message = new MimeMessage();
[...]
var body = new TextPart("Html")
{
Text = @"test"
};
using var memoryStream = new MemoryStream();
image.SaveAsPng(memoryStream) <<------------exception on this line
var attachment = new MimePart("image", "png")
{
Content = new MimeContent(memoryStream),
ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
};
...
}
这是日志:
Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HMLNLCMVSL21", Request id "0HMLNLCMVSL21:00000002": An unhandled exception was thrown by the application.
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'Image`1'.
at SixLabors.ImageSharp.Image.ThrowObjectDisposedException(Type type)
at SixLabors.ImageSharp.Image.EnsureNotDisposed()
at SixLabors.ImageSharp.Image.Save(Stream stream, IImageEncoder encoder)
at SixLabors.ImageSharp.ImageExtensions.SaveAsPng(Image source, Stream stream, PngEncoder encoder)
at SixLabors.ImageSharp.ImageExtensions.SaveAsPng(Image source, Stream stream)
at YaClubApp.Infrastructure.Services.EmailService.Send(Image image) in /src/src/Infrastructure/Services/EmailService.cs:line 73
我应该更改此方法并在顶部(在Handle中(使用memoryStream,然后将其传递给GetTicketWithQRCode,然后再传递给Send吗?
或者什么是正确的方法?
您的线路
using var imageWithQRCode = new Image<Rgba32>(imageBase.Width, imageBase.Height);
正在处理方法结束时的结果图像。。。如果您希望调用程序在该方法完成后使用图像对象,请从该行中删除using
。。。别忘了,现在是callsite负责调用dispose。
所以基本上从上面的行中删除using
,并将其添加到前面
var ticketImage = await ticket.GetTicketWithQRCode(cancellationToken);
因为这是一个地方,现在需要拥有终身的形象。