在图像控件中绘制一个字节数组

时间:2013-05-15 15:03:31

标签: c# asp.net

是否有将字节数组转换为图像并直接在图像控件中显示而不将其保存在磁盘上?

这是我到目前为止开发的代码:

    protected void btnShow_Click(object sender, System.EventArgs e)
    {
        Byte[] blobEncryptedImage = Signature.Get(txSaleGUID.Text);
        Crypto crypto = new Crypto("mypass");
        Byte[] decryptedImage = Encoding.ASCII.GetBytes(crypto.Decrypt(blobEncryptedImage));

        MemoryStream ms = new MemoryStream(decryptedImage);
        Image img = Image.FromStream(ms);
        //Image1.ImageUrl = System.Drawing.Image.FromStream(ms);
    }

    public static Image byteArrayToImage(byte[] data)
    {
        using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
        {
            return new System.Drawing.Bitmap(Image.FromStream(ms));
        }
    }

更新1

这是我的加密课程:

    public class Crypto
{
    private ICryptoTransform rijndaelDecryptor;
    // Replace me with a 16-byte key, share between Java and C#
    private static byte[] rawSecretKey = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                          0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

    public Crypto(string passphrase)
    {
        byte[] passwordKey = encodeDigest(passphrase);
        RijndaelManaged rijndael = new RijndaelManaged();
        rijndaelDecryptor = rijndael.CreateDecryptor(passwordKey, rawSecretKey);
    }

    public string Decrypt(byte[] encryptedData)
    {
        byte[] newClearData = rijndaelDecryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
        return Encoding.ASCII.GetString(newClearData);
    }

    public string DecryptFromBase64(string encryptedBase64)
    {
        return Decrypt(Convert.FromBase64String(encryptedBase64));
    }

    private byte[] encodeDigest(string text)
    {
        MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
        byte[] data = Encoding.ASCII.GetBytes(text);
        return x.ComputeHash(data);
    }
}

任何人都可以提供线索吗?

2 个答案:

答案 0 :(得分:2)

使用George在评论中所说的内容,您需要有一个页面或最好是一个简单的处理程序(.ashx),它将返回响应流中的图像。然后,您可以将该代码放在该处理程序中,但不要将字节数组转换为图像,只需将字节写入响应流即可。

然后,在.aspx页面中,设置图像的URL以调用该处理程序。

示例:<img src="~/GetImage.ashx?ImageID=1" />

GetImage.ashx是将返回图像字节的处理程序。

答案 1 :(得分:0)

您可以使用以下方法直接将图像数据嵌入到html中:

<img src="data:image/gif;base64,RAAA...more data.....">

如果您对此感兴趣,请参阅该链接: Html - embed image directly in html (old school style)

但我认为使用处理程序更好,因为我不确定每个浏览器是否接受这类事情。

相关问题