Results 1 to 3 of 3

Thread: Saving a image to a sql server database

  1. #1

    Thread Starter
    Member
    Join Date
    Sep 2002
    Location
    Cincinnati, OH
    Posts
    44

    Saving a image to a sql server database

    Hi everyone,

    I want to create a little front end app that does the following:

    1) During load it populates a list box perhaps with the files located in a given folder

    2) The user can then select the file name and click save and the actual image will be stored in a sql server database.

    Note: If the file does not exist in the list box, the user would than be able to browse to a different image file.

    Any guidance would be appreciated Thanks in advance!

  2. #2
    Hyperactive Member scuzymoto's Avatar
    Join Date
    Aug 1999
    Location
    Washington State
    Posts
    316
    This code will save an image file to SQL Server. The key is that the image datatype in SQL Server is equivalent to a byte array in .net.

    Code:
    ' dimension an image variable
    myImage as New Bitmap
    myImage.FromFile("c:\test.jpg")
    
    ' dimension a memory stream to hold contents of image
    Dim myStream As New IO.MemoryStream()
    
    ' load imagebox image into memory stream
    myImage.Save(myStream, Drawing.Imaging.ImageFormat.Jpeg)
    
    ' establish database connection
    Dim cn As New SqlClient.SqlConnection("data source=MYDATASOURCE;initial catalog=MYDATABASE;persist security info=False;user id=sa;workstation id=SHX20476;packet size=4096;password=mypassword")
    
    ' create SQL statement with image parameter
    Dim cmd As New SqlClient.SqlCommand("Insert Into ImageTable (imageid, image) Values ('12345',@Picture)", cn)
    
    ' define image parameter content from memory stream
    Dim P As New SqlClient.SqlParameter("@Picture", SqlDbType.Image, myStream.ToArray.Length, ParameterDirection.Input, False, 0, 0, Nothing, DataRowVersion.Current, myStream.ToArray())
    
    ' add parameter
    cmd.Parameters.Add(P)
    
    ' open database and execute command to store image
    cn.Open()
    cmd.ExecuteNonQuery()
    cn.Close()
    SCUZ

  3. #3

    Thread Starter
    Member
    Join Date
    Sep 2002
    Location
    Cincinnati, OH
    Posts
    44

    Resolved

    Thanks Scuz
    Jim Webster

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width