Retrieve image from Database in winform - winforms

I want to retrieve data from database but i'm not able to retrieve image.I've taken TmagePath Datatype as nvarchar
PFB

First you must consider that the datatype in your Database of image must be VarBinary. Than try this:
var filename = ds.Tables[0].Rows[0];
byte[] getImg = new byte[0];
getImg = (byte[])filename["WImagepath"];
MemoryStream stream = new MemoryStream(getImg);
Picwaiter.Image = Image.FromStream(stream);
Maybe usefull answer:
https://stackoverflow.com/a/29589703/5603115

Related

Change CheckCharacters on XmlReader generated by SqlCommand.ExecuteXmlReader

If I try to change CheckCharacters the following way it, reader.Settings.CheckCharacters is still true. How am I supposed to do it?
using (var reader_org = command.ExecuteXmlReader())
{
var settings = new XmlReaderSettings { CheckCharacters = false, ConformanceLevel = ConformanceLevel.Auto };
var reader = XmlReader.Create(reader_org, settings);
reader.Read();
}
According to the documentation it's supposed to work:
"Add features to an existing XML reader. The Create method can accept another XmlReader object. The underlying XmlReader object can be a user-defined reader, a XmlTextReader object, or another XmlReader instance that you want to add additional features to."
It appears you are using FOR XML in SQL Server to generate certain types of XML that are not actually valid values, because they contain restricted characters, and is therefore not valid XML.
SQL Server will quite rightly not allow you to generate such XML if you use the , TYPE directive. But if you do not use that, it generates the XML as a string, and does not validate invalid characters. See also this article.
Ideally, you would use Base64 or similar to encode this. But assuming for whatever reason you don't want to do this, then the reason your current code does not work is that the underlying reader_ord XML reader already has CheckCharacters = true so will throw an exception.
Instead you need to create your own XML reader from the string. Since FOR XML without , TYPE also splits up large XML blobs into separate rows, you also need to concatenate them all first.
var sb = new StringBuilder();
using (var reader = command.ExecuteReader())
{
while (reader.Read()) // read all rows
{
sb.Append(reader.GetString(0));
}
}
var settings = new XmlReaderSettings { CheckCharacters = false, ConformanceLevel = ConformanceLevel.Auto };
using (var xmlReader = XmlReader.Create(sb.ToString(), settings))
{
// do stuff with reader here
}
There are more performant ways to do that: for example you could create your own Stream out of sequential reader.GetStream results, but that is significantly more complex.

Deserializing byte to image from sql through memory stream

I have convert an image to be saved in SQL Server Database as Binary with column name as "img". I have PictureBox1 ready to show the image.
Now I want to import the binary data back into image, and I'm trying this code in VB.net for example:
Dim queries As String
queries = "SELECT * from StudentData where Std_fname='" & ComboBox1.Text & "'"
Dim com As New SqlCommand(queries, sqlconn)
sqlconn.Open()
Dim ds As New SqlDataAdapter(queries, sqlconn)
Dim dr As SqlDataReader
dr = com.ExecuteReader()
While dr.Read
Std_fnameTextBox.Text = dr("Std_fname")
Std_lnameTextBox.Text = dr("Std_lname")
AgeTextBox.Text = dr("age")
AddressTextBox.Text = dr("address")
StateTextBox.Text = dr("state")
CityTextBox.Text = dr("city")
CountryTextBox.Text = dr("country")
Ic_passportTextBox.Text = dr("ic_passport")
DobDateTimePicker.Text = dr("dob")
PictureBox1.Image = dr("img") 'Here is the problem. If I run it, it ask me to convert Binary to Image first.
End While
sqlconn.Close()
The problem is, I don't know how to convert binary to image in this situation. And yes, I've been googling for it, but can't seem to get the right answer.
dr("img") returns either DBNull.Value, or a byte[]. You can use the stream overload of the Bitmap constructor to load this. In C# (should be easy to translate to VB), you can do it like this:
var imageData = (byte[])dr["img"];
using (var ms = new MemoryStream(imageData))
{
var bmp = new Bitmap(ms);
// Work with bmp
}
As Mark correctly noted, you're supposed to keep the stream open for the whole life-time of the Bitmap - this is actually a bit trickier than it seems, because the Bitmap doesn't even keep a reference to the stream.
The easiest way to handle this is to clone the bitmap after you create it, to remove the dependency on the stream. Unless you can do whatever work you need to do within the using - unlikely if you want to display it in a PictureBox.
You can also use ImageConverter.ConvertFrom directly, but all it does is create the MemoryStream if used on raw byte[] data :)

Change System.Windows.Controls.Image to MemoryStream?

I have a problem in silverlight which I need to convert this image(from database probably will be in bytes) and convert it to MemoryStream. I need to do this so I can use it to export images to PDF files. Any Ideas?
Image myImage = new Image();
myImage.Source = new BitmapImage(new Uri("Resources/cancel.jpg", UriKind.RelativeOrAbsolute));
For starters, I am trying to convert an Image object to a memory stream object in a sample project(that's why UriSource is coded). Because I'm not familiar with creating dummy data in bytes. Any help on this one? Can I convert an Image to MemoryStream? if not, I believe bytes can be converted to stream, how can I do dummy data?
Thanks for all the replies.
You just need to pass byte[] to MemoryStream constructor
byte[] bytes = GetBytes();
MemoryStream ms = new MemoryStream(bytes);
Hope this helps

Saving FlowDocument to SQL Server

I need to save WPF FlowDocuments to SQL Server. What is the best format for doing that? String? Blob? Does it matter in a document less than 5K words or so?
FlowDocument is not serializable so SWeko's answer above will not work.
You can use the methods below to get the FlowDocument to and from a Xaml string which can then be saved in the database using nvarchar(max).
var stringReader = new StringReader(info);
var xmlTextReader = new XmlTextReader(stringReader);
return (FlowDocument)XamlReader.Load(xmlTextReader);
and
var infoString = XamlWriter.Save(info);
If you just want to store the FlowDocument objects in a database, without any processing, I would recommend using binary serialization, and storing the resulting byte array into a varbinary(max). This is fast and scales well.
However, if you already have the FlowDocuments as XML files, than it would be easier just to dump them into a nvarchar(max) field, with no (added) serialization/deserialization overhead. This scales trivially for values under 8k, and then performs kinda OK until you hit around the 10MB mark.
You can serialize FlowDocument using the TextRange class. You can even use the RTF format. Saving:
FlowDocument docToSave; // Lets suppose this var is initialized.
var tr = new TextRange(docToSave.ContentStart,docToSave.ContentEnd);
var dst = new MemoryStream();
tr.Save(dst, DataFormats.Rtf);
dst.Close();
And loading:
FlowDocument docToLoad = new FlowDocument();
var tr = new TextRange(docToLoad.ContentStart,docToLoad.ContentEnd);
Stream src; // Lets suppose it is initialized.
tr.Load(src, DataFormats.Rtf);
src.Close();
See also https://www.wpf-tutorial.com/rich-text-controls/how-to-creating-a-rich-text-editor/

Serializing an object and storing it to a varbinary field in a DB

I can serialize an object to a file using:
var writeStream = File.Open("l.osl", FileMode.Create);
var bformatter = new BinaryFormatter();
bformatter.Serialize(writeStream, l);
What I am trying to do is instead of writing it to a file, write it to a DB varbinary field.
I assume that I have to change writeStream to something else, but what? Can I just put an object in there and there insert that object into the DB (I'm using LINQ).
Will this work?
PS: I have looked around and can't find any solid examples.
Kind of close to this:
Storing C# data structure into a SQL database

Resources