This project has moved and is read-only. For the latest updates, please go here.

StreamReader directly from MagickImage-Object

Oct 3, 2014 at 1:02 AM
I am using Magick.NET and dealing with huge files.

Is there any chance to get a stream-reader directly from the MagickImage-Object?

Currently I have to use the .write-method to save the data to a memory-stream but in my opinion this is wasting a lot of memory and even unnecessary, especially when you are dealing with huge files.

(i am using asp.net mvc 5 and the best would be to create a FilePathResult thats reads directly from the MagickImage-object).
Oct 3, 2014 at 12:41 PM
What you are doing is actually necessary. The image that is in memory is just a bunch of pixels and some metadata. If you want to read the information in another MagickFormat you first need to Write it to 'something'. I have no experience with mvc 5 but are you not allowed to write directly to the Response.OutputStream?
using (MagickImage image = CreateMagickImage())
{
  image.Write(HttpContext.Current.Response.OutputStream);
}
Oct 3, 2014 at 4:01 PM
Thanks for your reply!

Does it mean that Magick.NET uses an internal image-format under the hood? So to get an usable result one has to "convert" the raw-data in memory to the desired image-fileformat like png or jpg? Is this conversion done with the write-method?

And many thanks for your tip. This sould work. The idea of that is just to change the direction. Instead of reading from a stream (image) one can write to the output stream explicitly. I will test this and give a feedback right here.
Oct 3, 2014 at 5:17 PM
You are correct, the conversion is done when you call the write method.
Oct 5, 2014 at 12:19 AM
Edited Nov 12, 2014 at 2:17 AM
I tested it and it worked like a charme with the OutputStream.

The following is specific to ASP.NET MVC. To use the common design pattern used in ASP.NET MVC, I created a new MagickImageResult.
public class MagickImageResult : ActionResult {
    public MagickImage Image { get; private set; }


    public MagickImageResult(MagickImage image) {
        this.Image = image;
    }

    public override void ExecuteResult(ControllerContext context) {
        context.HttpContext.Response.ContentType = this.Image.FormatInfo.MimeType;
        context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;

        this.Image.Write(context.HttpContext.Response.OutputStream);
    }
}
To return an image in a MVC-Controller, use the following code:
public ActionResult MyAction() {
    MagickImage image = new MagickImage();

    return new MagickImageResult(image);
}