我需要从用户的图像文件路径,并将图像存储在我的sql服务器数据库。如何将ImageSource转换为byte []并返回ImageSource?
我从用户的文件,并转换为byte []使用方法
public static byte[] ImageToByteArray(BitmapSource bitmapSource)
{
byte[] imgAsByteArray = null;
if(bitmapSource != null)
{
imgAsByteArray = (new WriteableBitmap((BitmapSource)bitmapSource)).Pixels.SelectMany(p => new byte[]
{
(byte) p ,
(byte)(p >> 8 ),
(byte)(p >> 16),
(byte)(p >> 24)
}).ToArray();
}
return imgAsByteArray;
}
,但现在我不能将其转换回的BitmapSource。 是我写的代码,以将其转换回抛出异常
代码:
public static BitmapSourcebyteArrayToImage(byte[] imageBytes)
{
BitmapImage bitmapImage = null;
using(MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
bitmapImage = new BitmapImage();
bitmapImage.SetSource(ms);
}
return (BitmapSource)bitmapImage;
}
我上线bitmapImage.SetSource(MS)除外;
异常信息是“catastropic失败”
哪一行导致异常? – ZoolWay 2011-05-05 07:38:35
line bitmapImage.SetSource(ms); – Yanshof 2011-05-05 07:41:44
图像格式为JPG – Yanshof 2011-05-05 08:04:42