Hi everybody,
I am creating an image(jpeg) file from stored bytes[] in sql database, Varbinary datatype, (I used Image datatype also same result), I am using this jpeg image file to set to a Image web control, what seems the problem and how to fix this problem Do I have proper datatype in sql to store converted jpeg file data Please provide codes. Thanks.
[code]
string sqlText = "Select * From PictureImages Where ImageName = @ImgName";
SqlCommand cmd = new SqlCommand(sqlText, conn);
cmd.Parameters.Add("@ImgName", SqlDbType.VarChar, 20, "ImageName").Value = txtImgName.Text.Trim();
if (conn.State == ConnectionState.Closed)
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
string filePath = Request.PhysicalApplicationPath + txtImgName.Text + ".jpg";
FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
byte[] storedByte = null;
while (dr.Read())
{
lblImgNo.Text = dr["ImageNo"].ToString();
txtImgDesc.Text = dr["Description"].ToString();
txtImgUrl.Text = dr["ImageUrl"].ToString();
storedByte = (byte[])dr["ImageData"];
}
MemoryStream ms = new MemoryStream(storedByte);
Bitmap img = (Bitmap)System.Drawing.Image.FromStream(ms); <<-- Error Occurred Here
img.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Close();
img.Dispose();
[/code]
Nobody seems to know how to solve this
den2005![]()

Creating Image File: Parameter is not valid Using C#
Bahmany
Gravy
Hi,
I hope this article http://builder.com.com/5100-6371-5766889.html will help u.
Cheers,
Nay Lin
Andreas Johansson
Yes, you are right.
Sorry for buggy code. Luckily I didn't wrote it
Cheers,
Nay Lin
jwrodriguez
Thanks for the link, Nay Lin.
The problem is solved. Some part of the codes in this link...
while (blob == 255)
{
bw.Write(outBuffer);
bw.Flush();
startIndex += 255;
bw.Flush();
bw.Close();
fs.Close();
}
It seems this goes to infinite loop, Am I right
Dennis
teddyCool
Were you ever able to solve this problem I am having the same problem right now.
Bitmap bitmap = new Bitmap(stream);
I am getting an error that says parameter is not valid.kyu5354
Here is how to display image from sql db to the picture box in windows forms app C#
Please note that this is working code.
private void dbToPictureBoxButton_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
try
{
string connectionString = ConfigurationManager.AppSettings["ExceptionLogConnectionString"];
string queryString = ConfigurationManager.AppSettings["ExceptionLogViewerQueryString"];
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
SqlCommand cmd = new SqlCommand(queryString, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "ExceptionImageTable");
int c = ds.Tables["ExceptionImageTable"].Rows.Count;
cn.Close();
if (c > 0)
{
Byte[] byteBLOBData = new Byte[0];
byteBLOBData = (Byte[])(ds.Tables["ExceptionImageTable"].Rows[c - 1]["ScreenShot"]);
MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
exceptionPictureBox.Image = Bitmap.FromStream(stmBLOBData); //picture box only takes bitmap as image type C# 2.0
}
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
this.Cursor = Cursors.Default;
}
Here is how you save image to database
SillyMS
here is how you save image to database
private int SaveImageToDatabase(string applicationId, Bitmap exceptionScreenShotImage, string exceptionInfo)
{
SqlConnection connection;
SqlCommand command;
int recordsAffected = 0;
string connectionString = ConfigurationManager.AppSettings["ExceptionLogConnectionString"];
string queryString = ConfigurationManager.AppSettings["ExceptionLogQueryString"];
MemoryStream memoryStream = new MemoryStream ();
exceptionScreenShotImage.Save(memoryStream, ImageFormat.Bmp);
byte [] bitmapBytes = memoryStream.GetBuffer();
connection = new SqlConnection(connectionString);
connection.Open();
command = new SqlCommand(queryString, connection);
SqlParameter applicationIdParameter = new SqlParameter("@applicationId", SqlDbType.NVarChar);
if (applicationId != null)
{
applicationIdParameter.Value = applicationId;
}
else
{
applicationIdParameter.Value = System.DBNull.Value;
}
command.Parameters.Add(applicationIdParameter);
SqlParameter screenShotParameter = new SqlParameter("@screenShot", SqlDbType.Image);
screenShotParameter.Value = bitmapBytes;
command.Parameters.Add(screenShotParameter);
SqlParameter exceptionInfoParameter = new SqlParameter("@exceptionInfo", SqlDbType.NVarChar);
if (exceptionInfo != null)
{
exceptionInfoParameter.Value = exceptionInfo;
}
else
{
exceptionInfoParameter.Value = System.DBNull.Value;
}
command.Parameters.Add(exceptionInfoParameter);
command.CommandTimeout = 1000;
recordsAffected = (int)command.ExecuteNonQuery();
connection.Close();
return recordsAffected;
}
yosonu
The data from my getImageData function is the files contents. So it is working.
Thankyou Mahesh819 for your code. It was helpfull but doesnt quite work in a web page.
Does anyone know how to check if the code to insert the file is working correctly I have read that sometimes illegal characters get inserted into the BLOB somehow and they cause this error...
<%@ WebHandler Language="C#" Class="print_media" %>
using System;
using System.Web;
using System.Data.Odbc;
using System.Drawing;
using System.IO;
public class print_media : IHttpHandler {
public byte[] getImageData(int media_id)
{
Int32 FileSize;
byte[] rawData;
string connectionString = "DRIVER={MySQL ODBC 3.51 Driver};SERVER=X; DATABASE=X; UID=X; PASSWORD=X;OPTION=3";
string queryString = "SELECT file, filesize FROM media WHERE media_id='" + media_id + "'";
OdbcConnection con = new OdbcConnection(connectionString);
con.Open();
OdbcCommand cmd = new OdbcCommand(queryString, con);
OdbcDataReader myData= cmd.ExecuteReader();
if (myData.HasRows)
{
myData.Read();
FileSize = myData.GetInt32(myData.GetOrdinal("filesize"));
rawData = new byte[FileSize];
myData.GetBytes(myData.GetOrdinal("file"), 0, rawData, 0, FileSize);
return(rawData);
}
con.Close();
return(null);
}
public void ProcessRequest (HttpContext context) {
byte[] buffer = getImageData(40);
if (buffer == null)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Content Length is zero");
}
else
{
context.Response.ContentType = "Image/jpeg";
//if i use this line, it writes the url to the page WTF
//context.Response.BinaryWrite(buffer);
System.IO.MemoryStream stream1 = new System.IO.MemoryStream(buffer, true);
stream1.Write(buffer, 0, buffer.Length);
Bitmap m_bitmap = (Bitmap)Bitmap.FromStream(stream1, true); //this line give the "parameter is not valid" exception
m_bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
public bool IsReusable {
get {
return false;
}
}
}
billg51
Both. It was a B File. I ended up figuring it out. I was using a fixed length for the byte array and that was messing me up. Once I removed the fixed length of the byte array it worked fine.
Thank you.
Cereal123
Please, can you give me the code that you use to save and retrieve an image from database and put the byte array into a picturebox
I'm desperating!!!
Thank you!
Miguel
Helen999888
Hi Harry,
How do you get your image file from database or from folder directory
Programm3r
in aspx file
foreach
(DataRow dr in dtPhoto.Rows){
byte[] bData = (byte[])dr["PhotoImage"]; <<-- Get Column where data is stored as binary ImageResponse.BinaryWrite(bData);
}
Then on your other aspx page where the image is to be loaded in image control
imageconreol.ImageUrl = string.Format("get_Photo.aspx id={0}", photoId);
This should work..
Swapna.R.
On your original code where you highlighted the error, don't cast it to a Bitmap, assign it to an Image instead:
System.Drawing.Image image = System.Drawing.Image.FromStream(memoryStream);
mertkan65
I am trying to display an image from the sql 2000 database on to the picture box control on windows app (VS 2.0).
I am able to pull the image in to byte array. I also am able to put the byte array in to the Memory stream by writing it like stream.Write(image, 0, image.Length)
However, when i try to create a bitmap out of the memory stream it thorows an exception stating "parameter is not valid".
The second approach I tried was to use Image.FromStream(ms1) method, but it also says "parameter is not valid" when it tries to get the image from stream (memory stream).
The third approach i tried was writing to a temporary file stream and then read from file using Image.FromFile(strfn, true). This line gets an error stating "Out of memory".
Nothing seems to be working. Please shed some light if possible. All i want to do is display an image from sql db field(image field) on to picture box in windows application using C# 2.0
Please look at the code below for detail. The line in bold where I am getting my exceptions.
// Put user code to initialize the page here
MemoryStream stream = new MemoryStream();
SqlConnection connection = new SqlConnection(@"my connection string");
try
{
connection.Open();
SqlCommand command = new SqlCommand("select image from images Where EntryDate > '2/15/2007'", connection);
byte[] image = (byte[])command.ExecuteScalar();
stream.Write(image, 0, image.Length);
Bitmap bitmap = new Bitmap(stream);
/////testing 2
MemoryStream ms1 = new MemoryStream(image);
exceptionPictureBox.Image = Image.FromStream(ms1);
///testing 3
string strfn = Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs = new FileStream(strfn, FileMode.CreateNew, FileAccess.Write);
fs.Write(image, 0, image.Length);
fs.Flush();
fs.Close();
exceptionPictureBox.Image = Image.FromFile(strfn, true);
/////testing 3
}
finally
{
connection.Close();
stream.Close();
}
Needy