2

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.

Simple Code
  • 558
  • 9
  • 24

1 Answers1

2

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.

CodingYoshi
  • 25,467
  • 4
  • 62
  • 64
  • The Byte converter is workinf fine i have saved the images and re-wrote it using other page it converted to the bytes saved in the database then re-wrote it perfectly but if i stay in the same page that's where it doesn't work. – Simple Code Oct 06 '17 at 15:15