skip to Main Content

I have an ASP.NET control on a form. Declared as:

<asp:imagebutton runat="server" Id="myImage1"/>

In the code behind, I get an image from a Redis database. I read the image into memory. Like so:

Dim myByteArray() As Byte = myRedisDb.StringGet(myImageName)

I have tested the byte array by writing it to disk and then opening the disk file. Using the following code:

System.IO.File.WriteAllBytes("D:TempmyImage.png", myByteArray)
myImage1.ImageUrl = "D:TempmyImage.png"

How do I assign this byte to the control without having to write it to disk first?
The whole point of using Redis is to speed up performance. The disk write and disk read are not efficient.

2

Answers


  1. You can read all the image bytes, convert them to Base64, and then use a data URI (https://en.m.wikipedia.org/wiki/Data_URI_scheme). The image will be full inline on the HTML, which, of course, will make it bigger.
    For an example for ASP.NET Core, but that you can turn to WebForms (just set the data URI to the ImageUrl property), please have a look at https://weblogs.asp.net/ricardoperes/inline-images-with-asp-net-core.

    Login or Signup to reply.
  2. You can pull the raw image from the database like this:
    (I’m using SQL Server, but the idea for any database is quite much the same).

    So, say this markup with a button:

            <asp:ImageButton ID="B1" runat="server"
                OnClick="B1_Click"
                width="128"/>
    

    And on page load to set the image from a binary column (image) from the database, then code behind is thus:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    
        If Not IsPostBack Then
    
            Dim dtFiles As DataTable
            dtFiles = MyRst("SELECT Preview FROM MyUpLoadFiles WHERE Filename = 'b2.png'")
    
            B1.ImageUrl =
                 "Data:Image/png;base64," + Convert.ToBase64String(dtFiles.Rows(0)("Preview"))
    
        End If
    
    End Sub
    

    And the result is a button with a image from the database.

    enter image description here

    And the routine MyRst is part of my global helper routines (since one becomes fast tired of typing connection strings and code over and over. Hence, MyRst was this in my global general routines:

    Public Function MyRst(strSQL As String) As DataTable
    
        Dim rstData As New DataTable
        Using conn As New SqlConnection(My.Settings.TEST4)
            Using cmdSQL As New SqlCommand(strSQL, conn)
                conn.Open()
                rstData.Load(cmdSQL.ExecuteReader)
                rstData.TableName = strSQL
            End Using
        End Using
        Return rstData
    End Function
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search