开发者

Convert image into bytes to store in database

开发者 https://www.devze.com 2023-01-18 10:09 出处:网络
Can anybody tell me that how to convert an image (st开发者_开发问答ored in a file path) into bytes to store in a database?Why do you want to store the path as bytes? Why don\'t you just store it as a

Can anybody tell me that how to convert an image (st开发者_开发问答ored in a file path) into bytes to store in a database?


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.


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
) 
0

精彩评论

暂无评论...
验证码 换一张
取 消