Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Problem

How to convert images jpg from path to varbinary(MAX) in database ?

Details

I have Table ImagesData have two fields

SpecialCode nvarchar(20)

imagebinary varbinary(max)

I need to update images from path D:/Images to ImagesData Table based on SpecialCode

to show more clear

1- in my hard disk i have drive D have Folder Images so that path will be D:/Images

2- In D:/Images Folder i have pictures JPG may be 100 images as following

images Names in D:/Images Path as following

0001-1

000002-5

00001-3

0004-2

008523-1

In my path ImagesData Table my data as follwoing

SpecialCode imageBinary

0001/1

000002/5

00001/3

0004/2

actually when images Name exist on image path D:/Images matches specialcode in table

update field imagebinary to binary by convert image on path D:/Images to binary then update it on field imagebinary when specialcode of image on path D:/images matches SpecialCode on table ImagesData

if not matches not update it .

Example

if((imagepath 0001-1 == 0001/1 from table imagesData)

{

update field imagebinaryon table imagesData by convert image to binary it because it matches

}

else

{

not update because it not matched

}

Can you help me please on that

to summarize what i need

i need to update field as binary when matched specialcode on table to images name on path D:/Images


What I have tried:

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
 MemoryStream ms = new MemoryStream();
 imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
 return  ms.ToArray();
}
Posted
Updated 22-Jun-19 23:58pm

1 solution

Try:
C#
byte[] bytes = File.ReadAllBytes(pathToFile);
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("UPDATE ImagesData SET imagebinary=@BD WHERE SpecialCode=@SC", con))
        {
        cmd.Parameters.AddWithValue("@SC", specialCodeIdentifier);
        cmd.Parameters.AddWithValue("@BD", bytes);
        cmd.ExecuteNonQuery();
        }
    }
 
Share this answer
 
Comments
Maciej Los 24-Jun-19 12:31pm    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900