如何Base64编码字符串转换成图像,然后将其绑定到GridView控件中的Metro风格应用? [英] How to convert Base64 string to image, then bind it to GridView in a Metro Style App?
问题描述
我已经从web服务的产品集合,我预览网格视图这个产品,但我得到的产品为Base64字符串的图像。我怎样才能将其转换为图像,并将其绑定到网格视图的图像?
I have collection of products from web service, I preview this product in Grid View, but I get the images of the products as Base64 strings. How can I convert it to images and bind it to the images in the Grid View?
任何一段代码,这将帮助我在这个问题上。
Any piece of code that will help me in this issue.
推荐答案
在WPF /地铁/ Silverlight的,形象是一个UI控件。它的源设置为的BitmapSource。的BitmapSource是一个数据结构来保存的图像数据。
In WPF/Metro/Silverlight, Image is a UI control. Its source is set to BitmapSource. BitmapSource is a data structure to hold image data.
以下是从字节数组检索的BitmapImage的代码。
Following is the code to retrieve BitmapImage from byte array.
public BitmapImage ImageFromBuffer(Byte[] bytes)
{
MemoryStream stream = new MemoryStream(bytes);
BitmapImage image = new BitmapImage();
image.SetSource ( stream.AsRandomAccessStream());
return image;
}
注意stream.AsRandomAccessStream是不是在API可用这是一个扩展方法。我发现它从 IDWMaster 本的 SO质疑
下面是扩展方法
public static class MicrosoftStreamExtensions
{
public static IRandomAccessStream AsRandomAccessStream(this Stream stream)
{
return new RandomStream(stream);
}
}
class RandomStream : IRandomAccessStream
{
Stream internstream;
public RandomStream(Stream underlyingstream)
{
internstream = underlyingstream;
}
public IInputStream GetInputStreamAt(ulong position)
{
internstream.Position = (long)position;
return internstream.AsInputStream();
}
public IOutputStream GetOutputStreamAt(ulong position)
{
internstream.Position = (long)position;
return internstream.AsOutputStream();
}
public ulong Size
{
get
{
return (ulong)internstream.Length;
}
set
{
internstream.SetLength((long)value);
}
}
public bool CanRead
{
get { return internstream.CanRead; }
}
public bool CanWrite
{
get { return internstream.CanWrite; }
}
public IRandomAccessStream CloneStream()
{
//HACK, this is not clone, proper implementation is required, returned object will share same internal stream
return new RandomStream(this.internstream);
}
public ulong Position
{
get { return (ulong)internstream.Position; }
}
public void Seek(ulong position)
{
internstream.Seek((long)position, SeekOrigin.Current);
}
public void Dispose()
{
internstream.Dispose();
}
public Windows.Foundation.IAsyncOperationWithProgress<IBuffer, uint> ReadAsync(IBuffer buffer, uint count, InputStreamOptions options)
{
throw new NotImplementedException();
}
public Windows.Foundation.IAsyncOperation<bool> FlushAsync()
{
throw new NotImplementedException();
}
public Windows.Foundation.IAsyncOperationWithProgress<uint, uint> WriteAsync(IBuffer buffer)
{
throw new NotImplementedException();
}
}
最后3个方法不落实
Last 3 methods are not implemented
我没有测试过,但上面的应该主要工作(可能是一些细化后)。
I have not tested but above should work in principal (may be after some refinement).
这篇关于如何Base64编码字符串转换成图像,然后将其绑定到GridView控件中的Metro风格应用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!