0

I have a method below to convert a PNG image file (known file size: under 1MB) to a byte array, Response class returns the byte array for a web request for image download.

The problem is ToArray(), which creates another copy in memory. GetBuffer() returns the underlying buffer, which provides better performance.

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
    using(MemoryStream ms = new MemoryStream())
   {
        imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Png);
        return  ms.ToArray();
    }
}

Can anyone provide the code using GetBuffer()?

.NET 4.5, ASP.NET,

Creating a byte array from a stream

Fastest way to convert Image to Byte array

Pingpong
  • 7,681
  • 21
  • 83
  • 209

1 Answers1

0

You should save the file directly to the output steam of asp.net

    public ActionResult DownloadFile()
    {
        Image imageIn = GetImage();

        imageIn.Save(Response.OutputStream, ImageFormat.Png);

        return new HttpStatusCodeResult(HttpStatusCode.OK);
    }
Kevin Smith
  • 13,746
  • 4
  • 52
  • 77
  • do you dispose the imageIn? – Pingpong Aug 17 '17 at 23:14
  • Depending on who owns the imageIn object, if it's created everytime we call `GetImage()` then you'll need to Dispose of it. However it could be shared within this class then we'd need to implement IDisposable etc.. (however this is just an example) – Kevin Smith Aug 18 '17 at 08:13