Loading Image from a string
See the question and my original answer on StackOverflowBase64 would add 30% size to the string. I don't think it's necessary here. You can safely "cast" bytes to chars and vice versa for this particular binary need, as long as you don't do anything with the string. Here is some code that seems to work:
// usage example
string encoded = FileToString("myimage.png");
Console.WriteLine(s.Length);
FileFromString(encoded, "copy.png");
public static void FileFromString(string input, string filePath)
{
if (input == null)
throw new ArgumentNullException("input");
if (filePath == null)
throw new ArgumentNullException("filePath");
using (FileStream stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
byte[] buffer = FromString(input);
stream.Write(buffer, 0, buffer.Length);
}
}
public static byte[] FromString(string input)
{
if (input == null)
throw new ArgumentNullException("input");
char[] cbuffer = input.ToCharArray();
byte[] buffer = new byte[cbuffer.Length];
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = (byte)cbuffer[i];
}
return buffer;
}
public static string FileToString(string filePath)
{
if (filePath == null)
throw new ArgumentNullException("filePath");
using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Write))
{
return ToString(stream);
}
}
public static string ToString(Stream input)
{
if (input == null)
throw new ArgumentNullException("input");
StringBuilder sb = new StringBuilder();
byte[] buffer = new byte[4096];
char[] cbuffer = new char[4096];
int read;
do
{
read = input.Read(buffer, 0, buffer.Length);
for (int i = 0; i < read; i++)
{
cbuffer[i] = (char)buffer[i];
}
sb.Append(new string(cbuffer, 0, read));
}
while (read > 0);
return sb.ToString();
}
However, it's possible the system where you store strings may not like strings that contains the 0 or other special numbers. In this case, base64 is still an option.