C# WPF Show Image from Mysql - c#

i'm a student and i am bad at programing.
I saved the images in my mysql database for each player. I created a program where I can list some soccer players from my database. When i click on a listed player in datagrid, a new window appears with the information about the player. Everything works, but now i want a picture of the selected player to be displayed on the information window from the database. Can anybody help me? My english is not the best (i'm 17) so i hope you can understand what i mean.
This is what i tried to do but i don't know how to continue. PS. It's in WPF.
MySqlCommand cmd = new MySqlCommand("SELECT Bilder FROM spieler WHERE Bilder='{8}'");
MySqlDataReader rdr1 = cmd.ExecuteReader();
try
{
conn.Open();
while (rdr1.Read())
{
// image1... I don't know what to write here
}
}
catch (Exception ex)
{
MessageBox.Show("Fehler: " + ex);
}
rdr1.Close()

Just get it using a byte[] casting beforehand:
while (rdr1.Read())
{
byte[] data = (byte[])reader[0]; // 0 is okay if you only selecting one column
//And use:
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
{
Image image = new Bitmap(ms);
}
}
UPDATE:
In WPF, use the BitmapImage:
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(data))
{
var imageSource = new BitmapImage();
imageSource.BeginInit();
imageSource.StreamSource = ms;
imageSource.CacheOption = BitmapCacheOption.OnLoad;
imageSource.EndInit();
// Assign the Source property of your image
yourImage.Source = imageSource;
}

What is column's type where you hold the image?
You could try somehing like this
Image tmp = ImageConverter.ConvertFrom(rdr1.GetStream("photo"));
where photo is name of your column

Related

Error "The byte array is not a recognized imageformat" reading image of type byte[] from database for itextSharp in C#

I hope you can help me. I explain the following:
I get the photo from the database, which is saved as a byte array:
List<DevolImgModels> list_img = new List<DevolImgModels>();
string sql = "SELECT img.foto FROM contratostimg img";
conexion.conection(constring);
using (MySqlCommand cmd = new MySqlCommand(sql, conexion.con))
{
cmd.CommandType = CommandType.Text;
using (MySqlDataReader d = cmd.ExecuteReader())
{
while (d.Read())
{
list_img.Add(new DevolImgModels
{
foto = (byte[])d["foto"] //I put the photo in a list_img list, and photo is of type byte[]
});
}
}
}
conexion.close();
Image foto = Image.GetInstance(fila.foto);
PdfPCell c = new PdfPCell(foto, true);
c.Image.ScaleToFitHeight = false;
table.AddCell(c);
//...
//code definitions to create the pdf. I put the dots to save code and go straight to the problem
foreach (var fila in list_img)
{
//...
Image foto = Image.GetInstance(fila.foto);
PdfPCell c = new PdfPCell(foto, true);
c.Image.ScaleToFitHeight = false;
table.AddCell(c);
}
But when passing row.photo(of type byte[]) to Image, it gives an error, that is, in this line of code it gives the error:
Image foto = Image.GetInstance(fila.foto);
And the error it gives is the following:
The byte array is not a recognized imageformat
buggy image:
this is the test image
I wish I could fix it, if anyone has any ideas or solutions I would appreciate it.
Best regards.

Picture appears only after restart the device

I have an Android-App that takes pictures and saves them in an external storage ("DCIM/Cameras"). But the pictures appear only after restarting my handy.
Is there some kind of Update or a way around this?
My source-code from saving my image:
var dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim);
var pictures = dir.AbsolutePath + "/Camera";
string name = System.DateTime.Now.ToString("yyyyMMdd_HHmmssfff") + ".jpg";
string filePath = System.IO.Path.Combine(pictures, name);
FileStream output;
Bitmap bitmap = BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length);
try
{
output = new FileStream(filePath, FileMode.Create);
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, output);
output.Close();
//Static Class that contains an methode for MediaScannerConnection.ScanFile
MediaGalleryHelper.AddFileToGallery(name);
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.ToString());
}
You have to let the photo gallery know that a new photo has been added. You can use below code for that:
this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + filePath)));
Where 'this' is an activity.

How can I save this image as HD as possible?

I am trying to modify my song's metadata. I got this to work, but if the user has not specified an album art image I automatically draw one from a picturebox holding the album image. The returned image is really blurry- Is there any way I could make it as high definition as possible? Here is the part of my code where I handle that:
if (isDir == false){
IPicture art2 = new TagLib.Picture(new TagLib.ByteVector((byte[])new System.Drawing.ImageConverter().ConvertTo(pictureBox1.Image, typeof(byte[])))); //I make the new picture here.
TagLib.File file2 = TagLib.File.Create(Properties.Settings.Default.NowPlayingPath);
file2.Tag.Title = SongBox.Text;
file2.Tag.AlbumArtists = artist;
file2.Tag.Genres = genre;
file2.Tag.Year = Convert.ToUInt32(YearBox.Text);
file2.Tag.Composers = composers;
file2.Tag.Pictures = new IPicture[1] { art2 };//I set the picture here.
file2.Save();
MessageBox.Show("You'll need to reload your song to continue listening to it.", "Settings saved.");
this.Hide();
}
}
Try to use MemoryStream to get image as byte array:
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] buff = ms.GetBuffer();
IPicture art2 = new TagLib.Picture(new TagLib.ByteVector(buff));

Size of Image while storing it in database

I'm facing an odd problem regarding image size.
I've made a simple application which stores and retrieves images in a database. When I'm reading an image from the file, its size is in kB(kilobytes) and so is the length of the byte array.
There are two pictureboxes. pb1 for storing, and pb2 for loading.
My store() and load() methods are given below:
note: openConnState() and CloseConnState() are methods for closing and opening connections. And the byte[] img_byte and imgfilelength = 0 are defined publicly in the class.
Store:
private void StoreImage(string ChosenFile)
{
try
{
//MemoryStream ms = new MemoryStream();
//pb1.Image.Save(ms, ImageFormat.Jpeg);
//img_byte = new byte[ms.Length];
//ms.Position = 0;
//ms.Read(img_byte, 0, img_byte.Length);
FileInfo fileImage = new FileInfo(ChosenFile);
imgfilelength = fileImage.Length;
FileStream fs = new FileStream(ChosenFile, FileMode.Open, FileAccess.Read, FileShare.Read);
img_byte = new Byte[Convert.ToInt32(imgfilelength)];
int count, sum = 0;
while ((count = fs.Read(img_byte, 0, Convert.ToInt32(imgfilelength))) > 0)
{
sum += count;
}
//int byteread = fs.Read(img_byte, 0, Convert.ToInt32(imgfilelength));
fs.Close();
}
catch (Exception e)
{
throw e;
}
}
public void storetoDB()
{
OpenConnState(conn);
string str = "use db2 \n insert into TableImg(Image) \n values('" + img_byte + "')";
SqlCommand cmd = new SqlCommand(str, conn);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
throw e;
}
finally
{
CloseConnState(conn);
}
}
Load:
public void Loadimg()
{
try
{
pb2.Image = null;
byte[] getbyte = LoadImagefromDB(3);
using (MemoryStream ms = new MemoryStream(getbyte))
{
pb2.Image = Image.FromStream(ms);
}
pb2.Refresh();
}
catch (Exception e)
{
throw e;
}
}
public byte[] LoadImagefromDB(long pid)
{
byte[] img = null;
OpenConnState(conn);
string str = "use db2 \n select Image from TableImg where P_Id = " + pid;
SqlCommand cmd = new SqlCommand(str, conn);
try
{
img = (byte[])cmd.ExecuteScalar();
return img;
}
catch (System.Exception e)
{
throw e;
}
finally
{
CloseConnState(conn);
}
}
I store the image into a database using the storeDB() method given above, but when I retrieve the image using the load() method given above, I get an error saying parameter invalid. I found out the problem is likely to be related to the length of the byte array, because when I retrieve the 'image' datatype value of database into a byte array, the length of byte array will always be 13.
And I even ran the below query to get its size in database, it is still the same, i.e. 13 bytes.
select len(Convert(varbinary(max), Image)) from TableImg where P_Id = 1
Can anyone tell me, why?
I retrieve the 'image' datatype value of database into a byte array,
the length of byte array will always be 13.
You are trying to do this:
use db2 \n insert into TableImg(Image) \n values('System.Byte[]')
obviously, length of the string System.Byte[] will always be 13.
You have to convert that binary data to other type before insert.
According to this post if your image is quite small in bytes, you can store it as VARBINARY type. If it big, you should store it as a file in the drive.
EDIT
You can use like this:
using (SqlCommand cmd = new SqlCommand("use db2 \n insert into TableImg(Image) \n values(#binaryValue)", conn))
{
cmd.Parameters.Add("#binaryValue", SqlDbType.VarBinary, img_byte.Length).Value = img_byte;
cmd.ExecuteNonQuery();
}

save user profile image to database

How can I dynamically insert images when user uploads an image file to SQL Server 2005 with C# in ASP.NET? This is to let users upload their profile photos in my web app. Is it very different from how it is done for windows app with C#?
There is a metric ton of examples on the web on this one:
http://aspalliance.com/138
https://web.archive.org/web/20210304133428/https://www.4guysfromrolla.com/articles/120606-1.aspx
http://www.aspfree.com/c/a/ASP.NET/Uploading-Images-to-a-Database--C---Part-I/
You should be able to follow any of those to accomplish what you want.
The same way as in in WinForms. Get byte[] and same to image column. But i strongly recommend to use file system to store pictures. DB is for relational data, File System for raw bytes.
http://msdn.microsoft.com/en-us/library/aa479405.aspx
Here is a sample of the code behind for inserting an image into a database in C#. You will of coarse need supporting table the picture should be a byte field and keep the picture type so you can retrieve the image later to display it. In addition to that you need to put a file input box on your page along with a submit button.
public void AddImage(object sender, EventArgs e)
{
int intImageSize;
String strImageType;
Stream ImageStream;
FileStream fs = File.OpenRead(Request.PhysicalApplicationPath + "/Images/default_image.png");
Byte[] ImageContent;
if (PersonImage.PostedFile.ContentLength > 0)
{
intImageSize = PersonImage.PostedFile.ContentLength;
strImageType = PersonImage.PostedFile.ContentType;
ImageStream = PersonImage.PostedFile.InputStream;
ImageContent = new Byte[intImageSize];
int intStatus;
intStatus = ImageStream.Read(ImageContent, 0, intImageSize);
}
else
{
strImageType = "image/x-png";
ImageContent = new Byte[fs.Length];
fs.Read(ImageContent, 0, ImageContent.Length);
}
SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["conn"]);
SqlCommand objCmd;
string strCmd;
strCmd = "INSERT INTO ImageTest (Picture, PictureType) VALUES (#Picture, #PictureType)";
objCmd = new SqlCommand(strCmd, objConn);
SqlParameter prmPersonImage = new SqlParameter("#Picture", SqlDbType.Image);
prmPersonImage.Value = ImageContent;
objCmd.Parameters.Add(prmPersonImage);
objCmd.Parameters.AddWithValue("#PictureType", strImageType);
lblMessage.Visible = true;
try
{
objConn.Open();
objCmd.ExecuteNonQuery();
objConn.Close();
lblMessage.Text = "ImageAdded!";
}
catch
{
lblMessage.Text = "Error occured the image has not been added to the database!";
}
}

Categories