如何使用c#将图像转换为Windows Phone 8.1中的字节数组

时间:2014-05-22 07:48:24

标签: c# windows-phone-8.1

我正在使用此代码

MemoryStream ms = new MemoryStream();
WriteableBitmap wb = new WriteableBitmap(myimage);
wb.SaveJpeg(ms, myimage.PixelWidth, myimage.PixelHeight, 0, 100);
byte [] imageBytes = ms.ToArray();

来自Convert image to byte array on Windows Phone 7 No System.Drawing Dll any other way?,但WriteableBitmap在Windows Phone 8.1环境中不包含SaveJpeg方法。

3 个答案:

答案 0 :(得分:3)

Windows Phone 8.1 Silverlight应用程序上,您的代码运行正常,我认为myImageBitmapImage。唯一必须做的就是等待BitmapImage加载完整:

using System.IO;
using System.Windows.Media.Imaging;
...
myImage = new BitmapImage(new Uri("http://i.stack.imgur.com/830Ke.jpg?s=128&g=1", UriKind.Absolute));
myImage.CreateOptions = BitmapCreateOptions.None;
myImage.ImageOpened += myImage_ImageOpened;
...
void myImage_ImageOpened(object sender, RoutedEventArgs e)
{
    MemoryStream ms = new MemoryStream();
    WriteableBitmap wb = new WriteableBitmap(myImage);
    wb.SaveJpeg(ms, myImage.PixelWidth, myImage.PixelHeight, 0, 100);
    byte[] imageBytes = ms.ToArray();
}

我刚刚测试了该代码,它在WP8.1上完美运行。

但是当您评论另一篇文章时,您无法引用Microsoft.Phone,您可能正在使用Windows Phone 8.1商店应用,在这种情况下,您可以使用以下代码:

using Windows.UI.Xaml.Media.Imaging;
using Windows.Storage.Streams;
using System.Runtime.InteropServices.WindowsRuntime;
...
BitmapImage bitmapImage = new BitmapImage(new Uri("http://i.stack.imgur.com/830Ke.jpg?s=128&g=1"));
RandomAccessStreamReference rasr = RandomAccessStreamReference.CreateFromUri(bitmapImage.UriSource);
var streamWithContent = await rasr.OpenReadAsync();
byte[] buffer = new byte[streamWithContent.Size];
await streamWithContent.ReadAsync(buffer.AsBuffer(), (uint)streamWithContent.Size, InputStreamOptions.None);

答案 1 :(得分:2)

我怀疑你定位Windows Runtime Apps,因为你还没找到the namespace suggested in this answer (which will work for WP8.1 Silverlight)

在Windows运行时应用中,您可以使用Encoder - 示例代码如下所示:

// lets assume that you have your image in WriteableBitmap yourWb
using (MemoryStream ms = new MemoryStream())
{
    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, ms.AsRandomAccessStream());
    encoder.SetPixelData(BitmapPixelFormat.Bgra8,
        BitmapAlphaMode.Ignore,
        imageWidth,
        imageHeight,
        horizontalDPI,
        verticalDPI,
        yourWb.PixelBuffer.ToArray());

    await encoder.FlushAsync();
}

答案 2 :(得分:0)

SaveJpeg是一种扩展方法(http://msdn.microsoft.com/en-US/library/windowsphone/develop/system.windows.media.imaging.extensions.savejpeg(v=vs.105).aspx)。您是否在项目参考中引用了Microsoft.Phone并将using System.Windows.Media.Imaging;添加到.cs文件中?