Stream to image and back

I take Stream convert it to Image , process this image, and then return the FileStream .

Is this a performance issue? If not, then what is the optimized way to convert and return the 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 performed: A user uploads an image on my site (the controller gives me Stream, I resize it, and then send this stream to rackspace (Rackspace takes up FileStream ).

+4
source share
2 answers

Basically you 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 as follows:

 using (var input = File.OpenRead("input.jpg")) using (var output = File.Create("output.png")) { Resize(input, output, 640, 480); } 
+9
source

It looks as simple as it can be. You must read the entire contents of the image in order to be able to process it, and you need to write the result.

FileStreams is the usual way to handle .NET files, so for normal purposes, your approach is fine.

The only thing I do not understand is why you are returning the FileStream again - this is the same object that was passed in the parameter.

If you take a lot of images and only change parts of the data, memory mapped files can improve performance. However, this is a more perfect concept.

0
source

All Articles