Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim con As New SqlConnection
    Dim img As New Image
    con.ConnectionString = ("Initial Catalog=test; Data Source=LAPTOP-DJ6MPGR2\ROOT123;User ID=SA;Password=root;Integrated Security=False;MultipleActiveResultSets=True")
    con.Open()
    Dim cmd As New SqlCommand("select  image from Images ", con)
    cmd.Connection = con
    Dim dr As SqlDataReader = cmd.ExecuteReader()
    If (dr.HasRows) Then
        While (dr.Read)
            Dim bytes As Byte() = DirectCast(dr("image"), Byte())
            Image1.ImageUrl = Convert.ToBase64String(bytes)
        End While
    End If
    con.Close()
End Sub
I have written a vb.net code to display image in the image control but not able to display the image
- 
                    3A base64 image URL contains more than just the base64 string itself... have a look at https://stackoverflow.com/questions/8499633/how-to-display-base64-images-in-html – ADyson Dec 08 '21 at 14:30
- 
                    (You don't need `MultipleActiveResultSets=True` - it would be better to remove that.) – Andrew Morton Dec 08 '21 at 16:20
- 
                    1Also, it needs an extra command after `con.Close()`: `con.Dispose()`. – Andrew Morton Dec 08 '21 at 16:26
- 
                    1Note that `select image from Images` will select *all* the values of image, and the `While (dr.Read)` will iterate over all those images, so the Image1.ImageUrl property will end up being only the last of the values. Either add a suitable `WHERE` clause to the select so that only one result will be returned, or you could limit it to one result with `SELECT TOP 1 [image] FROM [Images]`. – Andrew Morton Dec 08 '21 at 16:32
- 
                    2Use `Using` blocks. replace `Dim con As New SqlConnection` with `Using con As New SqlConnection()` and replace `con.Close()` with `End Using`. Same goes for `Dim cmd ...`. Then you won't need to call Dispose – djv Dec 08 '21 at 18:59
- 
                    `Dim img As New Image` is not used, and in my environment this defaults to `System.Drawing.Image` which is abstract and can't be constructed. Also `Image1` is not declared in your code. Perhaps they are the same thing? – djv Dec 08 '21 at 19:01
- 
                    1I could really really of base too I admit because I'm not really too sure what you've got in your DB. Image1.ImageUrl is the PATH to an image, not the image itself – Hursey Dec 08 '21 at 20:45
- 
                    @Hursey yes but in html an image URL can also be valid as a base64 string of the image, plus the required info at the start - see the link I posted earlier, above – ADyson Dec 08 '21 at 22:48
- 
                    1@djv My guess is that Image1 is a control on a page. – Mary Dec 09 '21 at 07:49
1 Answers
The following will show how to both upload an image to a SQL Server database as well as how to retrieve and image from the database and display it on an ASP.NET web page.
Create a table in the database:
Create Table Images(Id int IDENTITY(1, 1) Not null,
Image varbinary(max),
Constraint PK_Images_Id PRIMARY KEY(Id));
The SQL Server 'sa' user really shouldn't be used to access the database as this creates a security issue. Instead create a user for your application.
Create a Database User
- Open Microsoft SQL Server Management Studio
- Expand Security
- Right-click Logins
- Select New Login
- Select SQL Server authentication
- Login name: <desired login name> (ex: appUser)
- Enter your desired password
- Uncheck "User must change password at next login"
- Select the desired default database (ex: testDR)
- Click OK
Add User to Database
- Open Microsoft SQL Server Management Studio
- Expand Databases
- Expand <desired database> (ex: testDR)
- Expand Security
- Right-click Users
- Select New User...
- Enter desired user name (ex: appUser)
- For "Login name", Click ...
- Click Browse
- Select desired user (ex: appUser)
- Click OK
- Click OK
- Leave "Default schema", blank.
- Click OK
Grant User Permissions on Table
- Open Microsoft SQL Server Management Studio
- Expand Databases
- Expand <desired database> (ex: testDR)
- Expand Tables
- Right-click <desired table> (ex: dbo.Images)
- Select Properties
- Under "Select a page", click Permissions
- Click Search
- Click Browse
- Check desired user (ex: appUser)
- Click OK
- Click OK
- Under Grant, check the following: Delete, Insert, Select, Update
- Click OK
Note: "With Grant" allows the user to grant the permissions to another user.
VS 2019:
Create a new project
- Open Visual Studio 
- Click Continue without code 
- Click File 
- Select New 
- Select Project 
- Click Next 
- Select the following: 
- Click Next 
- Enter desired project name 
- Click Create 
- Under Advanced, uncheck Configure for HTTPS 
- Click Create 
Open Solution Explorer
- In VS menu, click View
- Select Solution Explorer
Add WebForm (name: default.aspx)
- In Solution Explorer, right-click <project name>
- Select Add
- Select New Item...
- Select Web Form (name: default.aspx)
- Click Add
Add WebForm (name: DisplayImage.aspx)
- In Solution Explorer, right-click <project name>
- Select Add
- Select New Item...
- Select Web Form (name: DisplayImage.aspx)
- Click Add
Add connection string to Web.config
- In Solution Explorer, double-click Web.config
In code below, modify the code within <connectionStrings>...</connectionStrings> for your environment (ie: server, database name, user name, password).
Web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <connectionStrings>
    <add name="testDRConnection" connectionString="Server=.\SQLExpress;Database=testDR;User Id=appUser;Password=myAppPassword;" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" />
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>
In "default.aspx" we'll add the ability to upload a file to the database. When the upload is complete, we'll use "Display.aspx" to display the last uploaded image.
In Solution Explorer, double-click default.aspx.
default.aspx
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="default.aspx.vb" Inherits="DatabaseGetImage.UploadImage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="frmDefault" runat="server">
        <div>
            <asp:Label ID="LabelFileUpload" for="FileUpload1" runat="server" Text="Label">Upload a File</asp:Label>
            <p />
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="ButtonUploadFile" runat="server" Text="Upload" OnClick="ButtonUploadFile_Click" />
            <p />
            <asp:Label ID="LblMsg" runat="server" Text=""></asp:Label>
        </div>
    </form> 
</body>
</html>
Below is the code that uploads an image to the database.
In Solution Explorer, right-click default.aspx. Select View Code
default.aspx.vb
Imports System.Configuration
Imports System.Data.SqlClient
Public Class UploadImage
    Inherits System.Web.UI.Page
    'Private _connectionStr As String = "Server=.\SQLExpress;Database=testDR;User Id=appAdmin;Password=appPass;"
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    End Sub
    Protected Function UploadImage(imageBytes As Byte()) As Integer
        Dim rowsAffected As Integer = 0
        Dim connectionStr As String = ConfigurationManager.ConnectionStrings("testDRConnection").ConnectionString
        Dim sqlText As String = "INSERT INTO Images(Image) VALUES(@img);"
        Using con As SqlConnection = New SqlConnection(connectionStr)
            'open
            con.Open()
            Using cmd As SqlCommand = New SqlCommand(sqlText, con)
                'size = -1 is needed to exceed 8000 bytes; it maps to varbinary(max)
                cmd.Parameters.Add("@img", SqlDbType.VarBinary, -1).Value = imageBytes
                'execute
                rowsAffected = cmd.ExecuteNonQuery()
            End Using
        End Using
        Return rowsAffected
    End Function
    Protected Sub ButtonUploadFile_Click(sender As Object, e As EventArgs)
        If FileUpload1.HasFile() Then
            LblMsg.Text = "Filename: " & FileUpload1.FileName & " File bytes: " & FileUpload1.FileBytes.Length
            'upload image to database
            Dim rowsAffected As Integer = UploadImage(DirectCast(FileUpload1.FileBytes, Byte()))
            Response.Redirect("DisplayImage.aspx")
        End If
    End Sub
End Class
Next, we'll modify "DisplayImage.aspx" so that it will display an image.
In Solution Explorer, double-click DisplayImage.aspx
DisplayImage.aspx
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="DisplayImage.aspx.vb" Inherits="DatabaseGetImage.displayImage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
<div>
    <asp:Image ID="Image1" runat="server" ></asp:Image>
    <p />
    <asp:Label ID="LblMsg" runat="server" Text=""></asp:Label>
    </div>
</body>
</html>
The code below retrieves an image from the database and displays it.
In Solution Explorer, right-click DisplayImage.aspx. Select View Code
DisplayImage.aspx.vb
Imports System.Configuration
Imports System.Data.SqlClient
Public Class displayImage
    Inherits System.Web.UI.Page
    'Private _connectionStr As String = "Server=.\SQLExpress;Database=testDR;User Id=appAdmin;Password=appPass;"
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim imagesBytes As Byte() = GetImage(id:=1) 'get image with id = 1
        If imagesBytes IsNot Nothing Then
            'LblMsg.Text = "Base64 String: " & Convert.ToBase64String(imagesBytes)
            Image1.ImageUrl = "data:image/jpeg;base64," & Convert.ToBase64String(imagesBytes)
        End If
    End Sub
    Protected Function GetImage(id As Integer) As Byte()
        Dim imageBytes As Byte() = Nothing
        Dim connectionStr As String = ConfigurationManager.ConnectionStrings("testDRConnection").ConnectionString
        Dim sqlText As String = "SELECT * from Images where Id = (SELECT max(Id) from Images)"
        Try
            Using con As SqlConnection = New SqlConnection(connectionStr)
                con.Open() 'open
                Using cmd As SqlCommand = New SqlCommand(sqlText, con)
                    cmd.Parameters.Add("@id", SqlDbType.Int).Value = id
                    Using dr As SqlDataReader = cmd.ExecuteReader()
                        If dr.HasRows Then
                            While dr.Read()
                                imageBytes = DirectCast(dr("image"), Byte())
                            End While
                        End If
                    End Using
                End Using
            End Using
        Catch ex As SqlException
            'ToDo: add desired code
            LblMsg.Text = "Error: " & ex.Message
            'Throw
        Catch ex As Exception
            'ToDo: add desired code
            LblMsg.Text = "Error: " & ex.Message
            'Throw
        End Try
        Return imageBytes
    End Function
End Class
Resources:
 
    
    - 4,117
- 3
- 13
- 24
- 
                    Cheers, this is working great so far. How do I display multiple images from database on the same page? How to add image dynamically during the run time? – divya rao Dec 15 '21 at 04:08
- 
                    The following may be helpul: https://stackoverflow.com/questions/70317980/display-varbinary-image-in-gridview/70321177#70321177 – Tu deschizi eu inchid Dec 15 '21 at 21:20
 
     
    

