2

my application gets image from clipboard and saves it to server. getting image is done through java and javascript. my aspx codebehind receives this data (base64) and writes to file. here is my code

  byte[] buffer = new byte[Request.InputStream.Length];
    int offset = 0;
    int cnt = 0;
    while ((cnt = Request.InputStream.Read(buffer, offset, 10)) > 0)
    {
        offset += cnt;
    }
    fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".png";
    string base64 = System.Text.Encoding.UTF8.GetString(buffer);

    byte[] bytes = Convert.FromBase64String(base64);
    System.IO.FileStream stream = new FileStream(@"D:\www\images\" + fileName, FileMode.CreateNew);
    System.IO.BinaryWriter writer =new BinaryWriter(stream);
    writer.Write(bytes, 0, bytes.Length);
    writer.Close(); 

my problem is base64 . i get this string as utf8 encoded. seems this tampers the image and i am not able to open or view them.

[EDIT] Here is the java code that creates the data

StringBuffer sb = new StringBuffer();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
sb.append("data:image/").append("png").append(";base64,").append(Base64.encode(stream.toByteArray()));

so i will get a string like this data:image/png;base64,iVBORw0KGgoA.. and using ajax i posts this string to my aspx page

Girish K G
  • 407
  • 5
  • 11
  • 19
  • 1
    It is impossible to tell you how to decode the data if we do not know how it was encoded in the first place. Can you provide the java/javascript code that turns your images into base64 in the first place? – dodexahedron Jun 11 '12 at 05:56
  • [enter link description here][1] [1]: http://stackoverflow.com/questions/8645088/how-to-decode-a-string-of-text-from-a-base64-to-a-byte-array-and-the-get-the-st/30916342#30916342 this will help you, you wont get a corrupt file – Tshepo Kwienana Jun 18 '15 at 14:49

1 Answers1

4

You should remove the data:image/png;base64, prefix when you read the input stream before base64 decoding. For example you could split at the ,:

byte[] buffer = new byte[Request.InputStream.Length];
Request.InputStream.Read(buffer, 0, buffer.Length);
string data = Encoding.Default.GetString(buffer);
string[] tokens = data.Split(',');
if (tokens.Length > 1)
{
    byte[] image = Convert.FromBase64String(tokens[1]);
    string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".png";
    string path = Path.Combine(@"D:\www\images", fileName);
    File.WriteAllBytes(path, image);
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I have a very similar problem, but I can not figure it put... any help would be apreciated: http://stackoverflow.com/questions/11472731/base64-inputstream-to-string/11472877#comment15148464_11472877 – Blanca Hdez Jul 16 '12 at 07:52