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

9.5k views Asked by At

I've got a bunch of images stored on disk, with the mimetype of the image stored in a database. 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.

However, if I want to save to a stream (for example, Response.Body) then I have to use 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 e.g. JpegEncoder)?

3

There are 3 answers

9
James South On BEST ANSWER

ImageSharp can already tell you the mimetype of the input image. With your code if the mimetype doesn't match the input stream then the decode will fail.

(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. We need to add that.

2
Moose Morals On

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)

0
Chet On

ImageSharp 3.0 changed the API. LoadWithFormatAsync doesn't exist any more. The new way is:

using var img = await Image.LoadAsync(file.OnDiskFilename);
await img.SaveAsync(Response.Body, img.Metadata.DecodedImageFormat!);