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

この場合、intがどこにも表示されないため、Intをbyte[]に変換するかどうかはわかりません。確かに可能ですが、この場合はアプリケーションが表示されません。

あなたには2つの本当の問題がありました。1つはbyte[]を作成することでしたが、これはコンパイルされないことは明らかです。2つ目は、それらのバイトをストリームに取り込むことでした。

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 に答える
0

空のメモリストリームからイメージを作成しようとしています。バイト配列をパラメーターとしてMemoryStreamコンストラクターに渡します。

MemoryStream ms = new MemoryStream(ImagemByte);
于 2009-08-31T14:30:57.877 に答える
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 に答える