Hi,
Please help,

I have a problem while loading and retrieving an image from database.
I have loaded an image in the database as of type Image. I have retrieved the data from database and passed to stream. How can I load this to a picture box or to a report viewer?

regards
Jineesh

Dani AI

Generated

Good start from — and useful examples from and showing how the raw bytes come back from a query. The posts cover the basic retrieval path; the missing pieces most people hit later are (1) why Image.FromStream can throw "Parameter is not valid", (2) how to keep the image usable after disposing the stream, and (3) how to wire a database BLOB into a ReportViewer. The checklist below focuses on practical diagnostics and safe patterns you can apply immediately.

Common causes of "Parameter is not valid"

  • The DB value is empty, NULL, or not actually the raw file bytes (for example a file path, Base64 text, or an OLE-wrapped blob). Verify the stored length at the SQL level (non-zero) and that the column type is a binary type.
  • The bytes were corrupted by a text/charset conversion when inserted or read. Binary columns must be treated as binary end-to-end; do not read/write them as strings.
  • The bytes include an unexpected wrapper/header. Quick signature checks of the first few bytes help: JPEG starts with FF D8 FF, PNG with 89 50 4E 47 0D 0A 1A 0A, BMP with 42 4D. If the header does not match a known image signature, inspect how the image was stored.

Stream lifetime and UI controls

  • Some GDI+ image objects internally reference the source stream. To avoid later exceptions or file locks, create a disconnected copy of the image (copy into a new Bitmap) and dispose the original image and stream before assigning to a PictureBox. That removes any dependency on the underlying stream.

ReportViewer (RDLC) notes

  • Use an Image control with Source = Database and Value = the dataset field that holds the bytes. Make sure the dataset/report schema declares that field as a byte[] and set the MIME type (image/jpeg, image/png) or provide a MIME column. If you prefer external images, store URLs/paths instead and set Source = External.

Storage & best practice

  • For new designs prefer varbinary(max) or FILESTREAM (SQL Server) or object storage (S3/Blob) for large volumes; keep MIME/type metadata in the DB. For MySQL use a BLOB column and avoid automatic charset conversions.

Tiebacks: ’s disk dump approach is a good debug step for verifying raw bytes, and was right that flushing a MemoryStream is unnecessary. These diagnostics cover the typical failure modes that cause the errors reported in this thread.

Recommended Answers

All 8 Replies

In database you stored the picture as byte array right?

So now to convet it back to image you need to do:

System.IO.MemoryStream ms = new System.IO.MemoryStream(byte array of the image);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);

And use the image how you like...

If your image is not stored at the DB as byte array let me know and i will tell you how to do it!

In this code the "FacilityImg" column is data type "image" on the MSSQL server.

private void button2_Click(object sender, EventArgs e)
    {
      const string connStr = "Data Source=apex2006sql;Initial Catalog=ServManLeather;Integrated Security=True;";
      const string query = "Select ImgNumber, FacilityImg From FacilityImg Where ImgNumber = 1000";
      using (SqlConnection conn = new SqlConnection(connStr))
      {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
          using (SqlDataReader dr = cmd.ExecuteReader())
          {
            using (DataTable dt = new DataTable())
            {
              dt.Load(dr);
              File.WriteAllBytes(@"C:\picture.bmp", (byte[])dt.Rows[0]["FacilityImg"]);
            }
          }
        }
      }
    }

In this code the "FacilityImg" column is data type "image" on the MSSQL server.

private void button2_Click(object sender, EventArgs e)
    {
      const string connStr = "Data Source=apex2006sql;Initial Catalog=ServManLeather;Integrated Security=True;";
      const string query = "Select ImgNumber, FacilityImg From FacilityImg Where ImgNumber = 1000";
      using (SqlConnection conn = new SqlConnection(connStr))
      {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
          using (SqlDataReader dr = cmd.ExecuteReader())
          {
            using (DataTable dt = new DataTable())
            {
              dt.Load(dr);
              File.WriteAllBytes(@"C:\picture.bmp", (byte[])dt.Rows[0]["FacilityImg"]);
            }
          }
        }
      }
    }

Hi sknake,
He didnt want to create a file of the image, he wanted to pull it from the DB to a MemoryStream and put it to a picture box or to a report viewer, so why use

File.WriteAllBytes(@"C:\picture.bmp", (byte[])dt.Rows[0]["FacilityImg"]);

Hi sknake,
He didnt want to create a file of the image, he wanted to pull it from the DB to a MemoryStream and put it to a picture box or to a report viewer, so why use

File.WriteAllBytes(@"C:\picture.bmp", (byte[])dt.Rows[0]["FacilityImg"]);

Evidently because I wasn't paying attention

private void button2_Click(object sender, EventArgs e)
    {
      const string connStr = "Data Source=apex2006sql;Initial Catalog=ServManLeather;Integrated Security=True;";
      const string query = "Select ImgNumber, FacilityImg From FacilityImg Where ImgNumber = 1000";
      using (SqlConnection conn = new SqlConnection(connStr))
      {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
          using (SqlDataReader dr = cmd.ExecuteReader())
          {
            using (DataTable dt = new DataTable())
            {
              dt.Load(dr);
              //File.WriteAllBytes(@"C:\picture.bmp", (byte[])dt.Rows[0]["FacilityImg"]);
              using (MemoryStream ms = new MemoryStream((byte[])dt.Rows[0]["FacilityImg"]))
              {
                ms.Position = 0;
                ms.Seek(0, SeekOrigin.Begin);
                pictureBox1.Image = System.Drawing.Image.FromStream(ms);
                ms.Flush();
                ms.Close();
              }
            }
          }
        }
      }
    }

does the above work for MySQL database? I try, it gives me this error:
It says "Unable to connect to any of the specified MySQL hosts". I have used the same connection string in other application, and it is able to retrieve successfully some other data from the same database and same table. Part of my code for MySQL is shown below:

private void GetImage_button_Click(object sender, EventArgs e)
{
const string connStr = "server=localhost;database=productcatalog;uid=root;password=12345678";
const string query = "SELECT Picture FROM Products WHERE ProductID = 1004";
using (MySqlConnection conn = new MySqlConnection(connStr))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
using (MySqlDataReader dr = cmd.ExecuteReader())
{
using (DataTable dt = new DataTable())
{
dt.Load(dr);
using (MemoryStream ms = new MemoryStream((byte[])dt.Rows[0]["Picture"]))
{
ms.Position = 0;
ms.Seek(0, SeekOrigin.Begin);
pictureBox1.Image = System.Drawing.Image.FromStream(ms);
ms.Flush();
ms.Close();
}
}
}
}
}


}

sorry, my above code works perfectly now.

Hi,
i got an error from this line

pictureBox1.Image = System.Drawing.Image.FromStream(ms);

the error is
"Parameter is not valid" how can i solve this problem ?

Thankyou...

Just a comment about line 20 in your code above. You don't ever have to Flush a memory stream. It doesn't do anything.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.