开发者

How to convert an image in to a stream of characters

I have found that an image can be stored as some string. To give an example I have included a ms word part that has an image. I saved a word file with image and saved it as xml format. When I opened the xml file in a notepad I got the following section. It must be the image being stored as some stream of text. Is there a similar way to do it in .net?

<pkg:part pkg:name="/word/media/image1.png" pkg:contentType="image/png" pkg:compression="store">
    <pkg:binaryData>
      iVBORw0KGgoAAAANSUhEUgAAAMgAAAA2CAMAAAC1HibFAAADAFBMVEWlweL95Mn90qXs8vn7woTi
      6/b7unT94sO8oIP93br4okTJjExJgsS9mXT5rVr7xYr4mzaStdz+/v/5qlT3kiT7vnuCqdb7zZv8
      1aqXqb5GgMP4nTt6mLpMhMX//Pn/+vT/s1n/4rU+fMH+8eXT4fH1+PyTqsb++PGXl5n3lSpQh8b9
      6tVLg8T3iRP6sWO80el5o9OpxOP+7t3+9uz+2rLC1ez+7Nmbut6yyub+9On5pUqQt+P3jh2SmqNE
      ...Truncated for easy reading...
      ex9vtLWG320M9N9gHow3tv8BO9hrVo7LVzgAAAAASUVORK5CYII=
    </pkg:binaryData>
</pkg:part>

I have tried the following wa开发者_开发问答y

 Bitmap bmp = new Bitmap(@"D:/bmp.bmp");
    MemoryStream mem = new MemoryStream();
    byte[] b = mem.ToArray();

But it gives me a byte array instead of characters. If it was characters, I could use it in many ways such as saving in xml format, using sql insert to insert image in a varchar instead of a blob, etc.


Base64 encode your byte array

Convert.ToBase64String(b);


The encoding you are seeing is called base-64. You can use the following code to turn any file into base-64, irrespective of whether it’s an image or not:

byte[] fileContents = File.ReadAllBytes(@"D:/bmp.bmp");
var base64 = Convert.ToBase64String(fileContents);

This will generate a long, single-line string. You can additionally specify Base64FormattingOptions.InsertLineBreaks if you want it to be broken into several lines, like in the XML file you saw.


This is probably image saved in base64 String.

Here is a description of conversion:

http://www.dailycoding.com/Posts/convert_image_to_base64_string_and_base64_string_to_image.aspx


Binary data must be encoded to be stored as character data, using BASE64 encoding, for example. There are encoders in the framework to do that with the byte array you have there.

However, note that this encoding increases the size of the data slightly, and involves an extra step. If you can store the data as bytes directly, that's more efficient. but of course you'll need the encoding for XML.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜