How to convert image to character stream

I found that the image can be saved as some string. To give an example, I included the part of the word ms containing the image. I saved the image file and saved it as an XML format. When I opened the xml file in notepad, I got the following section. This should be an image that is stored as some stream of text. Is there a similar way to do this 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 tried the following way

 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 these were characters, I could use it in different ways, for example, save in xml format using sql insert to insert the image into the varchar insead blob. and etc.

+3
4

Base64

Convert.ToBase64String(b);
+9

, , -64. , -64, , :

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

. Base64FormattingOptions.InsertLineBreaks, , , , XML, .

+2

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

However, note that this encoding slightly increases the size of the data and includes an additional step. If you can store data as bytes directly, it is more efficient. but of course you will need an encoding for XML.

0
source

Source: https://habr.com/ru/post/1765228/


All Articles