繁体   English   中英

如何将Image.Source转换为字节数组?

[英]How to convert Image.Source to byte array?

我的WP7应用程序具有一个Image控件,其Source在XAML中设置为将Build Action设置为Content的图像:

<Image x:Name="MyImage" Source="/Images/myimage.png"/>

我需要将此图像作为字节数组存储在SqlCe数据库中。 这是我当前要转换为byte []的代码:

public byte[] ImageToArray() {
    BitmapImage image = new BitmapImage();
    image.CreateOptions = BitmapCreateOptions.None;
    image.UriSource = new Uri( "/Images/myimage.png", UriKind.Relative );
    WriteableBitmap wbmp = new WriteableBitmap( image );
    return wbmp.ToArray();
}

字节数组保存到数据库,但是当我检索并且我的转换器尝试将其转换回(在另一页上)时,出现“未指定的错误”。 这是我的转换器:

public class BytesToImageConverter : IValueConverter {
    public object Convert( object Value, Type TargetType, object Parameter, CultureInfo Culture ) {
        if( Value != null && Value is byte[] ) {
            byte[] bytes = Value as byte[];

            using( MemoryStream stream = new MemoryStream( bytes ) ) {
                stream.Seek( 0, SeekOrigin.Begin );

                BitmapImage image = new BitmapImage();
                image.SetSource( stream ); // Unspecified error here
                return image;
            }
        }

        return null;
    }

    public object ConvertBack( object Value, Type TargetType, object Parameter, CultureInfo Culture ) {
        throw new NotImplementedException( "This converter only works for one way binding." );
    }
}

我已经做了很多搜索。 至于转换器,我的代码很标准。 我看过提到了stream.Position = 0; 是必要的,但我的理解是stream.Seek的。 我都尝试过。

因为我的转换器与我现在在大约十二个项目中使用的转换器相同,所以我相当确信问题出在将Image控件的Source转换为字节数组,因此我的图像数据已损坏。 在上面的代码中,我正在对Uri进行硬编码,但我也尝试过

BitmapImage image = MyImage.Source as BitmapImage;

没有运气。 我已经在这里呆了几个小时,而且机智已尽。 我想念什么?

我认为问题出在您的ImageToArray()方法中。 您正在将WriteableBitmap对象转换为数组,而不是图像本身。 尝试用以下方法替换您的方法:

    public byte[] ImageToArray()
    {
        BitmapImage image = new BitmapImage();
        image.CreateOptions = BitmapCreateOptions.None;
        image.UriSource = new Uri("/Images/myimage.png", UriKind.Relative);
        WriteableBitmap wbmp = new WriteableBitmap(image);
        MemoryStream ms = new MemoryStream();
        wbmp.SaveJpeg(ms, wbmp.PixelWidth, wbmp.PixelHeight, 0, 100);
        return ms.ToArray();
    }

该方法将图像作为jpg写入流,并返回字节。 我没有尝试过代码,但是使用转换器将其转换回BitmapImage应该没有问题。

image.UriSource中的byte []可以是base64基数。您可以在SQL故事中浏览byte []或数据。 如果基数错误,则不能从byte []转换为流。因此,如果基数为64,则必须转换为16基数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM