I want to convert an image to base64 and back to image again. Here is the code which i tried so far and the error also. Any suggestions please?
public void Ba
The MemoryStream.Read Method reads bytes from the MemoryStream into the specified byte array.
If you want to write the byte array to the MemoryStream, use the MemoryStream.Write Method:
ms.Write(imageBytes, 0, imageBytes.Length);
ms.Seek(0, SeekOrigin.Begin);
Alternatively, you can simply wrap the byte array in a MemoryStream:
MemoryStream ms = new MemoryStream(imageBytes);
You are reading from an empty stream, rather than loading the existing data (imageBytes
) into the stream. Try:
byte[] imageBytes = Convert.FromBase64String(coded);
using(var ms = new MemoryStream(imageBytes)) {
finalImage = System.Drawing.Image.FromStream(ms);
}
Also, you should endeavour to ensure that finalImage
is disposed; I would propose:
System.Drawing.Image finalImage = null;
try {
// the existing code that may (or may not) successfully create an image
// and assign to finalImage
} finally {
if(finalImage != null) finalImage.Dispose();
}
And finally, note that System.Drawing is not supported on ASP.NET; YMMV.
Caution
Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions. For a supported alternative, see Windows Imaging Components.