4

我有一个返回 varbinary(max) 类型数据的存储过程。我想将该数据转换为图像。

但我对这条线有问题:

public Image CargarAvatar(string login)
        {
            System.Object[] Args = new System.Object[1];
            Args[0] = login;

            DataTable X = new DataTable();
            X = TraerDataTable("sp_CargarAvatarUsuario", Args);

            byte[] ImagemByte = Convert.to (X.Rows[0][0].ToString());


            MemoryStream ms = new MemoryStream();
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }

请帮忙!:D

4

4 回答 4

12

varbinary 字段作为字节数组返回,因此您只需将其转换:

byte[] ImagemByte = (byte[])X.Rows[0][0];

然后使用数组创建内存流:

MemoryStream ms = new MemoryStream(ImagemByte);
于 2009-08-31T14:24:30.570 回答
0

这用于将图像转换为字节数组,它可以按如下方式插入数据库:

public byte[] imageToByteArray(BitmapImage myimage)
    {
        MemoryStream ms = new MemoryStream();
        WriteableBitmap wb = new WriteableBitmap(myimage);
        wb.SaveJpeg(ms, myimage.PixelWidth, myimage.PixelHeight, 0, 100);
        byte[] imageBytes = ms.ToArray();
        return imageBytes;
    }

这是后路:

public static BitmapImage ByteArraytoBitmap(Byte[] byteArray)
    {
        MemoryStream stream = new MemoryStream(byteArray);
        BitmapImage bitmapImage = new BitmapImage();
        bitmapImage.SetSource(stream);
        return bitmapImage;
    }
于 2013-09-18T18:05:22.697 回答
0

您正在尝试从空的内存流创建图像。将字节数组作为参数传递给 MemoryStream 构造函数:

MemoryStream ms = new MemoryStream(ImagemByte);
于 2009-08-31T14:30:57.877 回答
0

在这种情况下,我不确定是否将 Int 转换为 byte[],因为我在任何地方都看不到 int。当然可以,我只是在这种情况下看不到应用程序。

你有两个真正的问题。一个是创建 byte[],显然你知道它不会编译。第二个是将这些字节放入流中。

public Image CargarAvatar(string login)
{
    System.Object[] Args = new System.Object[1];
    Args[0] = login;

    DataTable X = TraerDataTable("sp_CargarAvatarUsuario", Args); // No need to create a new DataTable and overwrite it with the return value of TraerDataTable. One assignment will do.

    byte[] ImagemByte = (byte[])X.Rows[0][0]; // If this is an Image in the database, then this is already a byte[] here and just needs to be casted like so.             

    MemoryStream ms = new MemoryStream(ImagemByte); // You need to pass the existing byte[] into the constructor of the stream so that it goes against the correct data
    Image returnImage = Image.FromStream(ms);

    return returnImage;
}
于 2009-08-31T14:23:08.640 回答