簡體   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