如何在WP7中将图像存储到SQL数据库中

3

我正在拼命地尝试将一张图片保存到SQL数据库中,并在我的WP上加载它。所有在线指南都说要将图像转换为字节数组,存储它,然后再将其加载回图像。

到目前为止,我已经能够使用以下方法将图像保存到字节数组中:

    public static byte[] ConvertToBytes(Stream photoStream)   
    {   
        byte[] a = new Byte[photoStream.Length];   
        for (int i = 0; i < photoStream.Length; i++)   
        {   
            a[i] = (Byte)photoStream.ReadByte();   
        }   
        return (a);
    } 

这会生成一个字节数组,大小与我保存的图像类似。
建议加载图像的方法是:
    1 public static BitmapImage ConvertToImage(Byte[] inputBytes)   
    2 {   
    3     MemoryStream stream = new MemoryStream(inputBytes);   
    4     BitmapImage image = new BitmapImage();   
    5     image.SetSource(stream);   
    6     return (image);   
    7 }  

这个不起作用。

我在第5行遇到了这个错误:"未指定的错误"。

有没有人有什么想法来解决这个问题或者提供替代的方法/代码?

我知道有很多信息可以在线获取 - 我向你保证我已经长时间搜索并尝试了各种方法,但都无法解决问题。

非常感谢任何帮助!


请展示如何从数据库中获取输入字节。 - Davide Piras
请尝试此链接 http://www.redmondpie.com/inserting-in-and-retrieving-image-from-sql-server-database-using-c/ 我相信它会有所帮助。 - MethodMan
为了测试目的,我甚至没有使用数据库。我将一张图片转换为字节,然后将这些字节发送到ConvertToImage函数中。现在我正在查看你的链接 DJ KRAZE。 - Cameron
@CameronFisher:所以你现在的主要问题是如何显示图像? - Gert Arnold
如果他将图像保存到一个位置和名称,例如something.jpg,我相信它会起作用。如果我错了,请纠正我,GertArnold。 - MethodMan
显示剩余2条评论
2个回答

2
我用以下方法解决了这个问题:
public static byte[] ConvertToBytes(String imageLocation)
    {
        StreamResourceInfo sri = Application.GetResourceStream(new Uri(imageLocation, UriKind.RelativeOrAbsolute));
        BinaryReader binary = new BinaryReader(sri.Stream);

        byte[] imgByteArray = binary.ReadBytes((int)(sri.Stream.Length));

        binary.Close();
        binary.Dispose();
        return imgByteArray;
    }

    public static WriteableBitmap ConvertToImage(Byte[] inputBytes)
    {
        MemoryStream ms = new MemoryStream(inputBytes);
        WriteableBitmap img = new WriteableBitmap(400, 400);

        img.LoadJpeg(ms);

        return (img);
    }

感谢大家的帮助。

-1

我用了那段代码

  byte[] Arr = Convert.FromBase64String(Im); >> i think you need that steep 
 Stream memStream = new MemoryStream(Arr);

                                    WriteableBitmap wbimg = PictureDecoder.DecodeJpeg(memStream);

                                    image2.Source = wbimg;
                                    image2.Tag = IlbumID;

如果那不起作用

尝试

memStream.Read (Arr ,0, Arr.Length );

im是来自SQL数据库的一个值。 - raed
谢谢,但我得到了“COMException未处理”...“未指定的错误”。 “memStream.Read(Arr,0,Arr.Length);”返回一个整数? - Cameron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接