将位图图像序列化为base64?

时间:2011-02-28 23:00:52

标签: serialization windows-mobile resx

我一直在玩Windows Mobile 6的resco API:http://www.resco.net/他们做的一件事就是序列化位图图像,并在.resx文件中对它们进行base64编码,例如:

<data name="buttonCell2.ImagePressed" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
    <value>
      iVBORw0KGgoAAAANSUhEUgAAAEMAAAAaCAMAAADblRF+AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8
      YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAYZQTFRFtgAA////
      wAAAygAA2wAA2AAA0gAAuQAAvQAAsQAAwwAAzgAAxgAA1QAA3wAA4gAAswAArgAA5QAA5wAArAAA6gAA
      nQAA2QAAgAAA/wD/5AAApwAAxwAAugAA4AAAoQAAlQAAqgAAqAAAmgAAwgAAsAAAzQAA6AAA1wAA3gAA
      dQAAfAAAogAAvgAAsgAA/fTprQAAzwAAqwAAfwAAzAAAxAAAkQAAxQAAtAAAtQAA9M6Rz4SEsSoq+PDw
      agAAggAApAAAtDAw//36ZgAAewAAyX5+67uCbgAAdAAAyQkJjAAA+uO8qQYGoRsXtCwqeAAAYwAA1pld
      fCQWZQcEkwAA2qlqtWU/dRgP/fXmnCcnqGU/+d24mwAApQAAqicnjgAA/Pn5/fTneCQVigAA4qtxhx0b
      bAAA/fLkgCYY//38rB4edAcEp2E6owAAjx8UlwAA/ffucgAAcwAA0X94dgAAuXp2cAAAhQAAZQAAngAA
      aAAAnwAAxzAwgiQejQAA6s/PrGpDfx8Ulyx+wgAAASBJREFUOE+l1dVWw1AUBNBzkhYIUigUuUnapO7u
      WHF3d3d31z8nXYsvuGe/zzzOAGNs7fchnG7jkL5aMuIM2OJyWFck4CIpkwfljrlSj5AMtHIJJIWpdgY/
      05G8SfY3c/HLpvw9g5Ntu1lu4iabP8bh/F21yI3cZMfoCowoGUc9gSPTByGnL2ghCPoQQopoIhER7jZV
      M4mKcHuZrSPJIjxpngoSD8Lwa7SGJIpw5LaLJHaE7muoJQGEN71QTVJA6F+QBBIJ4SVnrSKxIsx8OStJ
      nAjz+0qRa8P+Q8UJhL1nLdZAEOs9hYsBd8IrcfMmOo6BfY5FbFZuts4dY5NnD3OaK2XjknKdfe8aHWzo
      cVXfaOGyNdh1U/4Gw3ocOcXL8T+dxW1D92ffagAAAABJRU5ErkJggg==
    </value>
  </data>

它会像这样加载:

this.buttonCell1.ImagePressed = ((System.Drawing.Image)(resources.GetObject("buttonCell1.ImagePressed")));

当我对64值进行解码时,我得到一个.bin,我可以在绘画中加载它,它看起来像是按钮图像。

我的问题是:如何将位图图像(或任何图像真实地)序列化为文本,然后对其进行base64编码,以便将其添加到Windows Mobile项目中的resx文件中。

2 个答案:

答案 0 :(得分:2)

你可以这样做。将第一行替换为更有效的一行:)

var myImage = new Bitmap(50,50);
var ms = new MemoryStream();
myImage.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] data = new byte[ms.Length];
ms.Read(data, 0, data.Length);

var base64ConvertedString = Convert.ToBase64String(data);

答案 1 :(得分:0)

public BitmapImage Base64ToImage(string base64String)
    {
        byte[] imageBytes = Convert.FromBase64String(base64String);
        MemoryStream ms = new MemoryStream(imageBytes, 0,imageBytes.Length);
        BitmapImage image2 = new BitmapImage();
        image2.SetSource(ms);
        ms.Close();
        return image2;
    }

调用这个函数,

        BitmapImage test = new BitmapImage();
        test = Base64ToImage(split[3].ToString());
        ImageBrush berriesBrush = new ImageBrush();
        berriesBrush.ImageSource = test;
        button1.Backgroud=berriesBrush;