H.A.M
H.A.M

Reputation: 51

I want to save image in database

I have an image on a page, e.g <img id="img3" runat="server" src="image.jpg" width="200" height="200"/> and I'd like to save the image referenced by the src attribute in my database using stored procedure.

I should convert the image to binary first. Here is what I have so far:

    Stream fs = FileUpload1.PostedFile.InputStream;

    BinaryReader br = new BinaryReader(fs);
    Byte[] bytes = br.ReadBytes((Int32)fs.Length);

    cmd.Parameters.AddWithValue("@img", byte);

But the thing is that I don't want to save the uploaded image FileUpload1.PostedFile.InputStream, I want to save the image that I had its src.

Is there a way to put the image src in stream so that I can save it or what is the right way for doing that?

Upvotes: 0

Views: 2225

Answers (2)

Shaked Dahan
Shaked Dahan

Reputation: 402

Saving an image in the database is not recommanded, but if you insist on saving it in your database you can convert the image to base64, then save the base64 string in your database.

using (Image image = Image.FromStream(FileUpload1.PostedFile.InputStream))
{                 
    using (MemoryStream m = new MemoryStream())
    {
        image.Save(m, image.RawFormat);
        byte[] imageBytes = m.ToArray();

        // Convert byte[] to Base64 String
        string base64String = Convert.ToBase64String(imageBytes);
        //Now save the base64String in your database
    }                  
}

And to convert it back from base64 to an image:

public Image GetImageFromBase64String(string base64String)
{
    byte[] bytes = Convert.FromBase64String(base64String);
    Image image;

    using (MemoryStream ms = new MemoryStream(bytes))
    {
        image = Image.FromStream(ms);
    }

    return image;

I combined some code from converting a base 64 string to an image and saving it and from Convert image path to base64 string .

Upvotes: 1

Amnesh Goel
Amnesh Goel

Reputation: 2655

Generally it is not recommended to store images in Database or any other type of files in RDBMS. What is most effective way, to store the file over disk on server, and store that path in your table.

So whenever you need to reference that image/file, then fetch the path from the database, and read the file from disk. This broadly has following two benefits.

  1. Removes the extensive conversion process (from image to binary and vice-versa).
  2. Helps to read the image directly (soft-read).

Upvotes: 3

Related Questions