title: Image retrieve gives error Index was outside the bounds of the array
body: <p>I am trying to get image at pageload from database to a img control but i receive this error.
  "Index was outside the bounds of the array." at line "long retrievedBytes = reader.GetBytes(1, startIndex, buffer, 0, ChunkSize);"</p>
  
  <pre><code>&lt;img runat="server" id="image" alt="" height="100" width="100"/&gt;
  
  protected void LoadImages()
  {
      SqlCommand cmd = new SqlCommand("sps_getimage", con);
      cmd.CommandType = CommandType.StoredProcedure;
      cmd.Parameters.AddWithValue("@ad_id", 10010);
      con.Open();
      SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.SequentialAccess);
      if (reader.HasRows)
      {
          reader.Read();
          MemoryStream memory = new MemoryStream();
          long startIndex = 0;
          const int ChunkSize = 256;
          while (true)
          {
              byte[] buffer = new byte[ChunkSize];
              long retrievedBytes = reader.GetBytes(1, startIndex, buffer, 0, ChunkSize);
              memory.Write(buffer, 0, (int)retrievedBytes);
              startIndex += retrievedBytes;
              if (retrievedBytes != ChunkSize)
                  break;
          }
  
          byte[] data = memory.ToArray();
          memory.Dispose();
          image.Src = "data:image/png;base64," + Convert.ToBase64String(data);
      }
      con.Close();
  }
  </code></pre>