Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream to Image and back

I'm taking a Stream convert it to Image, process that image, then return a FileStream.

Is this a performance problem? If not, whats the optimized way to convert and return back a stream?

public FileStream ResizeImage(int h, int w, Stream stream)
{
       var img = Image.FromStream(stream);

       /* ..Processing.. */

       //converting back to stream? is this right?
       img.Save(stream, ImageFormat.Png);

       return stream;
} 

The situation in which this is running: User uploads image on my site (controller gives me a Stream, i resize this, then send this stream to rackspace (Rackspace takes a FileStream).

like image 340
Shawn Mclean Avatar asked Jan 18 '23 15:01

Shawn Mclean


1 Answers

You basically want something like this, don't you:

public void Resize(Stream input, Stream output, int width, int height)
{
    using (var image = Image.FromStream(input))
    using (var bmp = new Bitmap(width, height))
    using (var gr = Graphics.FromImage(bmp))
    {
        gr.CompositingQuality = CompositingQuality.HighSpeed;
        gr.SmoothingMode = SmoothingMode.HighSpeed;
        gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
        gr.DrawImage(image, new Rectangle(0, 0, width, height));
        bmp.Save(output, ImageFormat.Png);
    }
}

which will be used like this:

using (var input = File.OpenRead("input.jpg"))
using (var output = File.Create("output.png"))
{
    Resize(input, output, 640, 480);
}
like image 72
Darin Dimitrov Avatar answered Jan 26 '23 04:01

Darin Dimitrov