2011-11-02 77 views
0

我从客户端获取图像将其转换为byte []并将其发送到服务器。并将byte []转换为Base64String并插入到数据库中。从silverlight中以字节[]的形式显示数据库中的图像

而且我倒转显示图像。但我不能看到图像。为什么???

//Convert to byte array 
public static byte[] ImageToByteArray(WriteableBitmap bitmap) 

{ 
      int[] p = bitmap.Pixels; 
      int len = p.Length << 2; 
      byte[] result = new byte[len]; 
      Buffer.BlockCopy(p, 0, result, 0, len); 
      return result; 
} 

//Converter 
public object Convert(object value, Type targetType, object parameter,System.Globalization.CultureInfo culture) 
     { 
      if (value == null) 
      { 
       return null; 
      } 

      BitmapImage image = new BitmapImage(); 

      MemoryStream stream = new MemoryStream(); 
      stream.Write((byte[])value, 0, ((byte[])value).Length); 
      image.SetSource(stream); 


      return image; 
     } 

//While writing to database 
else if (value.GetType() == typeof(byte[])) 
      { 
       return "'" + Convert.ToBase64String((byte[])value) + "'"; 
      } 

else if ((type == typeof(byte[]))) 
      { 
       return Convert.FromBase64String((string)value); 
      } 

回答

0

我使用了BinaryReader并解决了问题。

我的问题是没有读取正确的图像。使用BinaryReader读取图像并解决问题。

   BinaryReader reader = new BinaryReader(fileInfo.OpenRead()); 

       byte[] tempImage = new byte[reader.BaseStream.Length]; 

       reader.Read(tempImage, 0, tempImage.Length); 
1

我有以下代码为一个字节数组直接转换为图像:

var bitmapImage = new BitmapImage(); 
bitmapImage.SetSource(new MemoryStream(imageData)); 
newImage.Source = bitmapImage; 

所以只要转换和从Base64String工作,这应该是你所需要的。

另外,您不需要转换为Base64String来存储在数据库中。您只需要将列类型设置为image(假设您正在使用MS SQL Server)

+0

克里斯 - 嗨。我使用MS-SQL,但我通过反射和查询对象使用元数据映射。在这个领域模型中,我不能将图像数据添加为图像。而我却无法让事情奏效。 – turgut

+0

@turgut - 我认为你需要解决问题。是图像转换为字符串失败吗?或者也许是字符串在数据库中的存储?验证每一步的数据。从byte [] - > string - > byte []进行转换,并检查结果是否与输入相同。 – ChrisF

+0

转换前和转换后匹配的数据令人惊讶。 – turgut

1
public class Base64StringToImageConverter : IValueConverter { 
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { 
      if (!(value is string)) return DependencyProperty.UnsetValue; 

      BitmapImage bitmapImage = new BitmapImage(); 
      bitmapImage.SetSource(new MemoryStream(System.Convert.FromBase64String((string)value))); 
      return bitmapImage; 
     } 

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { 
      // TODO: Implement this method 
      throw new NotImplementedException(); 
     } 
    } 
相关问题