简体   繁体   English

如何从磁盘加载图像并使用 ImageSharp 保存到流中,同时保留 mimetype

[英]How load an image from disk and save to a stream using ImageSharp while preserving the mimetype

I've got a bunch of images stored on disk, with the mimetype of the image stored in a database.我在磁盘上存储了一堆图像,图像的 mimetype 存储在数据库中。 If I want to save the image to disk I can use Image.Save(string) (or the Async version) without needing to know the MimeType of the image.如果我想将图像保存到磁盘,我可以使用Image.Save(string) (或异步版本)而无需知道图像的 MimeType。

However, if I want to save to a stream (for example, Response.Body ) then I have to use Image.Save(Stream, IImageEncoder) .但是,如果我想保存到流(例如Response.Body ),那么我必须使用Image.Save(Stream, IImageEncoder)

How do I get the IImageEncoder I need to save to the stream (without just declaring that "All my images ar png/jpeg/bmp" and using eg JpegEncoder )?我如何获得我需要保存到流中的IImageEncoder (而不仅仅是声明“我的所有图像都是 png/jpeg/bmp”并使用例如JpegEncoder )?

ImageSharp can already tell you the mimetype of the input image. ImageSharp 已经可以告诉您输入图像的 mimetype。 With your code if the mimetype doesn't match the input stream then the decode will fail.使用您的代码,如果 mimetype 与输入流不匹配,则解码将失败。

(Image Image, IImageFormat Format) imf = await Image.LoadWithFormatAsync(file.OnDiskFilename);

using Image img = imf.Image;
img.Save(Response.Body, imf.Format);

What we are missing however in the current API v1.0.1 is the ability to save asynchronously while passing the format.然而,我们在当前 API v1.0.1 中缺少的是在传递格式时异步保存的能力。 We need to add that.我们需要补充一点。

It took a bit of messing about, but I've figured it out:这花了一些乱七八糟的东西,但我已经想通了:

var file = ... // From DB

ImageFormatManager ifm = Configuration.Default.ImageFormatsManager;
IImageFormat format = ifm.FindFormatByMimeType(file.MimeType);
IImageDecoder decoder = ifm.FindDecoder(format);
IImageEncoder encoder = ifm.FindEncoder(format);

using Image img = await Image.LoadAsync(file.OnDiskFilename, decoder); 
// Do what you want with the Image, e.g.: img.Mutate(i => i.Resize(width.Value, height.Value)); 
Response.ContentType = format.DefaultMimeType; // In case the stored mimetype was something weird 

await img.SaveAsync(Response.Body, encoder);

(Although I'm happy to be shown a better way) (虽然我很高兴看到更好的方式)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM