I see a lot of people who want to get MemoryStream object from an image file and to save a MemoryStream object to a file, so I decided to write a little post about it.
A little explanation about MemoryStream Class:
The MemoryStream class creates streams that have memory as a backing store instead of a disk or a network connection. MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application.
Let's start with saving an image file to a MemoryStream object.
First i will show a code snippet and then I will explain further.
Code snippet(c#):
//Read the file into a MemoryStream.
FileStream fileStream = File.OpenRead(filePath);
MemoryStream imageStream = new MemoryStream();
//Copy all data from the file to MemoryStream Object.
imageStream.SetLength(fileStream.Length);
fileStream.Read(imageStream.GetBuffer(), 0, (int)fileStream.Length);
//Clean up
fileStream.Close();
So what is going on in here…
First open the chosen file for reading and save the stream instance inside the fileStream object.
FileStream fileStream = File.OpenRead(filePath);
Set imageStream length.
imageStream.SetLength(fileStream.Length);
Read all the file data and writes it to the imageStream buffer.
fileStream.Read(imageStream.GetBuffer(), 0, (int)fileStream.Length);
That's all, now we have an image represented by a MemoryStream:)
After we finished explaining how to save image to a MemoryStream object, we will save MemoryStream object into an image file.
Code snippet(c#):
using (FileStream imageFile = File.OpenWrite("\\Liquid.jpg")
{
imageFile.Write(ms.ToArray(), 0, (int)ms.Length);
ms.Close();
}
First we will open the stream to a file, the method creates a new file if it is not already exists. imageFile object hold the stream instance of the file.
using (FileStream imageFile = File.OpenWrite("Liquid.jpg")
Write() method writes all the bytes to an imagefile stream instance object, using data from buffer.
imageFile.Write(ms.ToArray(), 0, (int)ms.Length);
See you in the next post,
The-Liquid.
Source Code:
Download
thanks it was very helpful
ReplyDelete