Convert Bytes to Image ASP.NET c# and use it in Image1.Url

淺唱寂寞╮ 提交于 2019-12-08 00:57:41

问题


I have a WEB-APP that is a Web-Cam App that takes images and stores into a database as bytes, Now with that being said I also don't want to save the images those are taken and save it in any kind of folder right now the only way to show the image that is captured for me to save it and view it again to do that I have a input stream that's fired when the capture image is clicked.

using (StreamReader reader = new StreamReader(Request.InputStream))
{
    hexString = Server.UrlEncode(reader.ReadLine());
    string imageName = DateTime.Now.ToString("dd-MM-yy hh-mm-ss");
    string imagePath = string.Format("~/Pictures/{0}.png", imageName);
    File.WriteAllBytes(Server.MapPath(imagePath), ConvertHexToBytes(hexString));
    Session["Byte"] = hexString;
    //   Session["CapturedImage"] = ResolveUrl(imagePath);
    Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(ConvertHexToBytes(hexString));

}

I have a method that converts that hex string to bytes:

private static byte[] ConvertHexToBytes(string hex)
{
    // MemoryStream stream = new MemoryStream();
    byte[] bytes = new byte[hex.Length / 2];
    for (int i = 0; i < hex.Length; i += 2)
    {
        bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
    }
    return bytes;
}

I want to Display that image using the bytes, I don't want to save the image in any folder. How do I take those bytes and put them into a image?

I have a slandered image tag Image1.imageUrl =? I tried the base64 version but it doesn't work.


回答1:


How do I take those bytes and put them into a image?

Note: I am making the assumption as per your question that your question is not about converting hex to bytes.

Imagine you have this in your aspx page:

<asp:Image ID="Image1" runat="server" />

In the code below GetImageBytes returns a byte[]. Then, to serve the image (without saving it to a file), all we need to do is this:

using (MemoryStream ms = new MemoryStream(GetImageBytes()))
{
    // Image1 is instance of System.Web.UI.WebControls
    this.Image1.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray());
}

private byte[] GetImageBytes()
{
    return System.IO.File.ReadAllBytes(Server.MapPath("~/Content/someImage.jpg"));
}

Try that out by placing an image in your Content folder to test it out. Now that you know it works, you need to make sure it can work with your ConvertHexToBytes method. If it does not, then clearly something is wrong with ConvertHexToBytes method.



来源:https://stackoverflow.com/questions/46536653/convert-bytes-to-image-asp-net-c-sharp-and-use-it-in-image1-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!