tags:

views:

90

answers:

4

How to save stream as image and store the image in temp files?

+1  A: 

Have a look at the Bitmap Class. There's a constructor overload that takes a Stream as parameter and there's a method called Save which you can use to save it as a file.

Filip Ekberg
The bitmap step is not necessary. We can write the stream directly to a file.
Pierre 303
A: 

Your stream (image) is stream in the code below.

using (Stream output = new FileStream ("mycat.jpg"))
{
    byte[] buffer = new byte[32*1024];
    int read;

    while ( (read=stream.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, read);
    }
}

This code is copyrighted by Jon Skeet: http://www.devnewsgroups.net/dotnetframework/t29039-writing-stream-file.aspx. My contribution is the name of the file ;)

Pierre 303
+2  A: 
var tempFile = Path.GetTempFileName();
using (var fs = File.Create(tempFile))
{
   source.copyTo(fs);
}

where source is source stream. Now your source stream is saved at temp location (given by tempFile). Note that file name extension will be TMP.

VinayC
+1 for the Path.GetTempFileName() that I didn't know it ever existed.
Pierre 303
FileStream does not contain a definition for Create!! Moreover the stream which i use as input is System.IO.Stream and I want to store this IO stream to image in temp files.
banupriya
Sorry for that - I mean to say File.Create and not FileStream.Create. Will edit the answer. Source stream can be of any stream.
VinayC
+1  A: 

Try

Image img = System.Drawing.Image.FromStream(myStream);

img.Save(System.IO.Path.GetTempPath() + "\\myImage.Jpeg", ImageFormat.Jpeg);
Unmesh Kondolikar
The image step is not necessary. We can write the stream directly to a file.
Pierre 303
Yes .. But I assumed that banupriyavijay wants to so something with the image in the application. Otherwise it would be just a file copy operation which can be done using System.IO.File.Copy().
Unmesh Kondolikar