How to read image from database - c#

OleDbCommand and = new OleDbCommand();
c.Open();
and.Connection = c;
and.CommandText = "SELECT * FROM MaleShoes WHERE IDhere=ID ";
OleDbDataReader read = and.ExecuteReader();
while (read.Read())
{
label6.Text = (read[1].ToString());
textBox1.Text = (read[2].ToString());
pictureBox1.Image = (read[3].ToString());
}
c.Close();
I got this error:
Error 1 Cannot implicitly convert type 'string' to 'System.Drawing.Image'
How should I fix it?
My pictures are in my database on the third column.

If you your database column contains the path to the image file, you should write:
pictureBox1.Image = Image.FromFile((string)read[3]);
If it is the image data (binary), you should write:
var bytes = (byte[])read[3];
using(MemoryStream ms = new MemoryStream(bytes))
{
pictureBox1.Image = Image.FromStream(ms);
}

Hope this help (in case you are storing a binary):
pictureBox1.Image = byteArrayToImage((byte[])read[3]);
And your method
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}

you can also use this
byte[] imagebyte = (byte[])read[3].ToString();
MemoryStream ms = new MemoryStream();
ms.Write(imagebyte, 0, imagebyte.Length);
Bitmap bmp = new Bitmap(ms);
pictureBox1.Image = bmp;

You can try this:
MemoryStream ms = new MemoryStream((byte[])read[1]);
pictureBox1.Image = Image.FromStream(ms);

Related

Not able to get more then one results with images in WPF datagrid from Mysql Database in C#

With this code i am able to get one image from Mysql database in C# in WPF. But i have a table in database that contaon all countries's names and their
flag etc. When i query to select many or all countries folling error occur
"Cannot set the initializing state more than once" at this line "bi.BeginInit()".
Thanks in advance.
string co = null;
string na = null;
string le = null;
string gn = null;
string A = "pak";
BitmapImage bi = new BitmapImage();
try
{
MySqlCommand cmd = new MySqlCommand("Select Code,Name,LifeExpectancy,GNP,flg from country where Name REGEXP '" + A + "'", connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
co = dataReader["Code"].ToString();
na = dataReader["Name"].ToString();
le = dataReader["LifeExpectancy"].ToString();
gn = dataReader["GNP"].ToString();
Byte[] bindata = (Byte[])dataReader["flg"];
MemoryStream strm = new MemoryStream();
strm.Write(bindata, 0, bindata.Length);
strm.Position = 0;
System.Drawing.Image img = System.Drawing.Image.FromStream(strm);
bi.BeginInit();
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Seek(0, SeekOrigin.Begin);
bi.StreamSource = ms;
bi.EndInit();
dt.Rows.Add(co, na, le, gn, bi);
dataGridCustomers.ItemsSource = dt.DefaultView;
}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.ToString());
}
The reason for this is because you are creating the BitmapImage outside of the loop. So Once you get in the loop it keeps trying to set the initializing state on the same image. As your error states you can't do this. What you need to do is create a new BitmapImage on each iteration. Which can be accomplished by moving the line
BitmapImage bi = new BitmapImage();
To the inside of the loop. Unless there is a specific reason you are initializing it where you are.
string co = null;
string na = null;
string le = null;
string gn = null;
string A = "pak";
try
{
MySqlCommand cmd = new MySqlCommand("Select Code,Name,LifeExpectancy,GNP,flg from country where Name REGEXP '" + A + "'", connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
BitmapImage bi = new BitmapImage();
co = dataReader["Code"].ToString();
na = dataReader["Name"].ToString();
le = dataReader["LifeExpectancy"].ToString();
gn = dataReader["GNP"].ToString();
Byte[] bindata = (Byte[])dataReader["flg"];
MemoryStream strm = new MemoryStream();
strm.Write(bindata, 0, bindata.Length);
strm.Position = 0;
System.Drawing.Image img = System.Drawing.Image.FromStream(strm);
bi.BeginInit();
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Seek(0, SeekOrigin.Begin);
bi.StreamSource = ms;
bi.EndInit();
dt.Rows.Add(co, na, le, gn, bi);
dataGridCustomers.ItemsSource = dt.DefaultView;
}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.ToString());
}
EDIT: In the code above, the System.Drawing.Image is entirely redundant. You should directly create the BitmapImage from the byte array like this:
var bindata = (byte[])dataReader["flg"];
var bi = new BitmapImage();
using (var stream = new MemoryStream(bindata))
{
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.StreamSource = stream;
bi.EndInit();
}

Converting Byte to Bitmap image

I am getting the byte in database but I cannot convert it to bitmap, I got an exception in Parameter. This is what I've done so far.
con.ConnectionString = MyConnectionString;
con.Open();
OdbcCommand cmds = new OdbcCommand("Select ID from try where kalabaw = 5", con);
OdbcDataAdapter da = new OdbcDataAdapter(cmds);
byte[] image = (byte[])cmds.ExecuteScalar();
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap bitmap = (Bitmap)tc.ConvertFrom(image);
pictureBox2.Image = bitmap;
con.Close();
I totally stole this answer from convert array of bytes to bitmapimage
public BitmapImage ToImage(byte[] array)
{
using (var ms = new System.IO.MemoryStream(array))
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad; // here
image.StreamSource = ms;
image.EndInit();
return image;
}
}
try the below. I expect it should work.
byte[] bytes = GetBytesArrayFromDatabase();
using (MemoryStream ms = new MemoryStream(bytes))
{
ms.Position = 0;
Bitmap obj = new Bitmap(ms);
// use the Bitmap object `obj` here
}

how to "convert a system.windows.control.image" to "System.Drawing.Image" in c#

Hello friends i want to "convert a system.windows.control.image" to "System.Drawing.Image",but i am unable to do so.I am using below code for this
var e = (MouseButtonEventArgs)sender;
var device = e.MouseDevice.DirectlyOver;
System.Windows.Controls.Image img = (System.Windows.Controls.Image)device;
I have "img" i.e of type "system.windows.control.image" i need to convert it to bitmap or drawing type.
Try this....
Use your img variable in this code...
MemoryStream ms = new MemoryStream();
System.Windows.Media.Imaging.BmpBitmapEncoder bbe = new BmpBitmapEncoder();
bbe.Frames.Add(BitmapFrame.Create(new Uri(img.Source.ToString(),UriKind.RelativeOrAbsolute)));
bbe.Save(ms);
System.Drawing.Image img2 = System.Drawing.Image.FromStream(ms);
button1.Image = img2;
convert from byte[] to image
MemoryStream ms = new MemoryStream(imageByte);
Image image = Image.FromStream(ms);
it may help you..

Converting image from project folder

I am trying to convert a image in my image folder and the image name defaultImage and update into my database table.
But now I am having problem in this line of code:
I change the code using this:
Image uploaded6 = Image.FromFile("/image/defaultImage.jpg");
instead of this:
System.Drawing.Image uploaded = System.Drawing.Image.FromStream(~/images/defaultImage);
I now getting the error of FileNotFoundException was unhandled by user code
I have tried this method using fileupload control and it working fine but not sure how to convert image in a folder.
How do I get the image from the folder in order to convert it using the method shown below.
Image uploaded6 = Image.FromFile("/image/defaultImage.jpg");
//System.Drawing.Image uploaded = System.Drawing.Image.FromStream();
System.Drawing.Image newImage = new Bitmap(1024, 768);
using (Graphics g = Graphics.FromImage(newImage))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(uploaded, 0, 0, 1024, 768);
}
byte[] results;
using (MemoryStream ms = new MemoryStream())
{
ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
EncoderParameters jpegParms = new EncoderParameters(1);
jpegParms.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
newImage.Save(ms, codec, jpegParms);
results = ms.ToArray();
}
string sqlImage = "update MemberReport set image1 = #Data where memberreportid = '" + Session["memberreportid"] + "'";
SqlCommand cmdImage = new SqlCommand(sqlImage);
cmdImage.Parameters.AddWithValue("#Data", results);
InsertUpdateData(cmdImage);
I guess your problem is with relative paths, instead of
Image uploaded6 = Image.FromFile("/image/defaultImage.jpg");
you should provide the local path, which you can get it this way:
Image uploaded6 = Image.FromFile(Server.MapPath("~/image/defaultImage.jpg"));
System.Drawing.Image.FromStream requires 'MemoryStream' as parameter.
byte[] file = null;
MemoryStream memoryStream = new MemoryStream();
memoryStream = new MemoryStream(file, false);
System.Drawing.Image objTempImg = System.Drawing.Image.FromStream(memoryStream)
byte[] file is based64 image
System.Drawing.Image.FromStream(Stream)
You must to send a Stream parameter in this method.

Error" Parameter is not valid " while converting Bytes into Image

I am converting bytes into an image but I get an error
Parameter is not valid
I am pasting my code. Kindly check the code and suggested that was I am doing right or wrong.
Image arr1 = byteArrayToImage(Bytess);
This is the function.
public static Image byteArrayToImage(byte[] byteArrayIn)
{
if (null == byteArrayIn || byteArrayIn.Length == 0)
return null;
MemoryStream ms = new MemoryStream(byteArrayIn);
try
{
Process currentProcess1 = Process.GetCurrentProcess();
Image returnImage = Image.FromStream(ms);
return returnImage;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I applied many techniques and solutions but it did not work for me
Your answer would be appreciated.
Thanks
try this
public Image byteArrayToImage(byte[] byteArrayIn)
{
System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
Image img = (Image)converter.ConvertFrom(byteArrayIn);
return img;
}
After trying many things I found a way which has a little bit more control.
In this example you can specify the pixel format and copy the bytes to a Bitmap.
byte[] buffer = GetImageBytes();
var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
var bitmap_data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
Marshal.Copy(buffer, 0, bitmap_data.Scan0, buffer.Length);
bitmap.UnlockBits(bitmap_data);
var result = bitmap as Image;
The problem is because, you are bringing it incorrectly from database. Try changing your code like this:
while (registry.Read())
{
byte[] image = (byte[])registry["Image"];
}
In my case I got the error since my base64 string had wrong encoding before calling Image.FromStream.
This worked for me in the end:
byte[] bytes = System.Convert.FromBase64String(base64ImageString);
using (MemoryStream ms = new MemoryStream(bytes))
{
var image = Image.FromStream(ms);
image.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
}
cmd.CommandText="SELECT * FROM `form_backimg` WHERE ACTIVE=1";
MySqlDataReader reader6= cmd.ExecuteReader();
if(reader6.Read())
{
code4 = (byte[])reader6["BACK_IMG"]; //BLOB FIELD NAME BACK_IMG
}
reader6.Close();
MemoryStream stream = new MemoryStream(code4); //code4 is a public byte[] defined on top
pictureBox3.Image = Image.FromStream(stream);
try this,
public Image byteArrayToImage(byte[] byteArrayIn)
{
Image returnImage = null;
using (MemoryStream ms = new MemoryStream(byteArrayIn))
{
returnImage = Image.FromStream(ms);
}
return returnImage;
}

Categories