4

Can anybody tell me that how to convert an image (stored in a file path) into bytes to store in a database?

1
  • 1
    Vote to close - sorry, i simply can not make any sense out of the question. Commented Oct 4, 2010 at 8:10

2 Answers 2

1

Why do you want to store the path as bytes? Why don't you just store it as a string? Unless you mean you want to store the image data as bytes in the database, in which case, look into the Image data type.

Sign up to request clarification or add additional context in comments.

Comments

1

To convert an image stored locally to bytes you can use IO.File.ReadAllBytes(). To convert an image on the web you can use Net.WebClient.DownloadData(). The IMAGE data type is going away in SQL Server, so use VARBINARY(MAX) to store it.

Code:

Dim url As String = "http://example.com/image.png",
    file As String = "c:\image.png"

Using connection As New Data.SqlClient.SqlConnection("your connection string"),
    saveImage As New Data.SqlClient.SqlCommand("dbo.saveImage", connection)

    connection.Open()
    saveImage.CommandType = Data.CommandType.StoredProcedure

    'use only one of these
    saveImage.Parameters.AddWithValue("@imageData", New Net.WebClient().DownloadData(url)) 'get file from url
    'saveImage.Parameters.AddWithValue("@imageData", IO.File.ReadAllBytes(file)) 'get file locally

    saveImage.ExecuteNonQuery()

End Using

Procedure:

CREATE PROCEDURE [dbo].[saveImage] ( @imageData AS VARBINARY(MAX) )
AS
INSERT INTO dbo.myImage ( imageData ) VALUES ( @imageData )

Table:

CREATE TABLE [dbo].[myImage](
    [imageData] [varbinary](max) NOT NULL
) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.