How to convert byte array to image file? - c#

I have browsed and uploaded a png/jpg file in my MVC web app.
I have stored this file as byte[] in my database.
Now I want to read and convert the byte[] to original file.
How can i achieve this?

Create a MemoryStream passing the array in the constructor.
Read the image from the stream using Image.FromStream.
Call theImg.Save("theimage.jpg", ImageFormat.Jpeg).
Remember to reference System.Drawing.Imaging and use a using block for the stream.

Create a memory stream from the byte[] array in your database and then use Image.FromStream.
byte[] image = GetImageFromDatabase();
MemoryStream ms = new MemoryStream(image);
Image i = Image.FromStream(ms);

May you have trouble with the mentioned solutions on DotNet Core 3.0 or higher
so my solution is:
using(var ms = new MemoryStream(yourByteArray)) {
using(var fs = new FileStream("savePath", FileMode.Create)) {
ms.WriteTo(fs);
}
}

Or just use this:
System.IO.File.WriteAllBytes(string path, byte[] bytes)
File.WriteAllBytes(String, Byte[]) Method (System.IO) | Microsoft Docs

Related

Download from byte array from CRM

In Microsoft CRM we have an attachment that should be fetched and downloaded. So I have a byte array that represents the fetched file:
byte[] fileContent = Convert.FromBase64String(query.DocumentBody);
If I use this code, of course it can be downloaded but the file path should be hardcoded (like C:/<folder name>/) and I don't want it like that.
using (FileStream fileStream = new FileStream(path + query.FileName, FileMode.OpenOrCreate))
{
byte[] fileContent = Convert.FromBase64String(query.DocumentBody);
fileStream.Write(fileContent, 0, fileContent.Length);
//Response.OutputStream.WriteByte(fileContent);
}
How can I download the file from a byte array? I've tried searching for ways but it all needs a file path, and I can't provide that file path since the object is a byte array.
I'm not sure what exactly is your problem, but following should write byte array to output stream. You may need "content-disposition" header for file name and "content-type" to let browser offer "download" instead of trying to open directly:
Response.OutputStream..Write(fileContent , 0, fileContent .Length);

Convert 64base byte array to PDF and show in webBroswer compont

This is what i would like to do:
Get a 64base byte array from database (which is actually in pdf format). This works.
Then i would like to show the pdf in a webbrowser component.
I first started with saving the pdf to a file.pdf and then open it:
byte[] bitjes = isc.GetFileById(fileid); // Getting the bytes
FileStream stream = new FileStream(#"C:\NexusPDF\" + filename, FileMode.CreateNew);
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(bitjes, 0, bitjes.Length);
writer.Close();
webBrowser.Navigate(#"C:\NexusPDF\" + filename);
But that gave me all sorts of problems involving read/write acces. So i figured i have to use the memorystream class to solve this problem.
byte[] bitjes = isc.GetFileById(fileid);
MemoryStream memstream = new MemoryStream(bitjes);
BinaryWriter writer = new BinaryWriter(memstream);
writer.Write(bitjes, 0, bitjes.Length);
writer.Close();
But here's where i'm stuck! I can't just show this in a webBrowser component can i?
Do i have to use the binaryreader before i can show the pdf?
Am i approaching this problem the right way, or are there better alternatives?
Main thing is that i don't want to save the file on disk.
Any help will be appreciated.
You may be able to use the data URL scheme. This URL scheme specifies the content inline.
webBrowser.Navigate("data:application/pdf;base64," + X);
Where X is the base 64 string.
No need to convert the base 64 PDF string into a byte array!
See http://www.ietf.org/rfc/rfc2397.txt for more details.

Save a file to SQL database using Silverlight and LINQ

What is the best way to save a file to my SQL database using Silverlight and LINQ?
I have read through some articles, some of them here on StackOverflow and there is so much information that I am not sure what is the best.
I have something that works using:
// Read the file
var reader = new StreamReader(openFileDialog.File.OpenRead());
contents = reader.ReadToEnd();
reader.Close();
// Convert to byte[]
byte[] inputbuffer;
var encoding = new UTF8Encoding();
inputBuffer = encoding.GetBytes(contents);
but according to something I read here on StackOverflow, using UTF8Encoding is not a good idea.
Also I can get the file from the database using LINQ when I need it, but how do I convert it back from the byte[] to the actual file?
Or would using WCF to save and retrieve a file be better?
Any ideas are greatly appreciated.
yes UTF8Encoding is not a good option.
You can use the FileStream's copyto method to copy the files bytes into a memorystream and use it's ToArray method to get all bytes instead.
If you can access the DB directly from Silverlight than this should be ok but the second part of your questions indicates that you might not be sure(?) - if so please put this into another question.
Here is a snippet to return the bytes from the file:
var stream = openFileDialog.File.OpenRead();
using (var memStream = new System.IO.MemoryStream())
{
stream.CopyTo(memStream);
return memStream.ToArray();
}
To save it back you will have to use the SaveFileDialog class in silverlight

Reverse MemoryStream.ToArray()

I am getting an httpwebresponse stream (of a flash file), and I would like to save it as binary and later access that binary and display it as flash. Right now, I am writing the response stream to a MemoryStream and then calling ToArray() on the MemoryStream. I get a handy byte[].
How do I reverse that function? How do I get the stream of the flash file from the byte[] I've generated?
Thanks!
Super easy:
Stream s = new MemoryStream(byteArray);
More info: http://msdn.microsoft.com/en-us/library/e55f3s5k.aspx
You can use this:
var s = new MemoryStream(byteArray);

Byte array to a file

I have a byte array for a file, is there a way to take that and save it has a file to a remote file server?
File.WriteAllBytes(#"\\server\public_share\MyFile.txt", byteArray);
Writing your data to file is the simple part and #aaron has shown you how...
i.e. File.WriteAllBytes(....etc
But something to be aware of, if you're transferring binary data over the wire and if your data contains bytes that could be interpreted as control characters then your data transfer will be problematic.
What you may need to do is encode your data first so that you can transfer it safely, typically you would use something like Base64 encoding.
You can use the Convert helper class to do that...
Convert.ToBase64String("file contents");
If you are doing this in the codebehind then you will need to use the FileStream and BinaryWriter objects.
Something like this;
FileStream filestream = new FileStream("myfile.txt", FileMode.Open);
BinaryReader br = new BinaryReader(filestream);
String msg = br.ReadString();
br.Close();
filestream.Close();
FileStream networkStream = new FileStream(#"\\server\share\file.txt", FileMode.Create);
BinaryWriter bw = new BinaryWriter(filestream);
bw.Write(msg);
bw.Close();
networkStream.Close();
If you're passing it through Javascript maybe using a HTML browse button then you'll need to do the same sort of thing but you will get the file stream from the post form request.
You may have an issue writing to the network location, if you're using IIS then you could set up a virtual directory and set the credentials in IIS. The alternative is that you will need to do impersonation to write the file to the network server.
Mike

Categories

Resources