Hi I'm new to azure storage blob. I have a project in WPF and I have created a container in azure storage blob that I can send /upload images to on button click. Can anyone tell me if I can store a string form the blob into my sql database that will allow me to access/use/display the image in my WPF project.
Maybe someone could direct me to an example! Thanks!
private void btnSAVE_Click(object sender, RoutedEventArgs e)
{
try
{
byte[] photo = GetPhoto(filePath);
sc.Open();
cmd = new SqlCommand("Insert into Rewards (Name, Picture, ) values'" + txtName.Text+ "','" + txtPicture.Text + "')", sc);
cmd.Parameters.Add("#Picture", SqlDbType.Image, photo.Length).Value = photo;
cmd.ExecuteNonQuery();
MessageBox.Show("Inserted");
sc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
displayAll();
}
private byte[] GetPhoto(string filePath) {
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] photo = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
return photo;
}
}
You can just store URL of that blob and use that URL to display image
CloudBlockBlob blockBlob = new CloudBlockBlob();
using (var fileStream = System.IO.File.OpenRead(path + "/" + up.GetName().ToString()))
{
blockBlob.UploadFromStream(fileStream);
}
string URL = blockBlob.Uri.OriginalString;
Refer to this link Writing BLOB values to a database.
From MSDN:
To write a BLOB value to your database, issue the appropriate INSERT
or UPDATE statement and pass the BLOB value as an input parameter. If
your BLOB is stored as text, such as a SQL Server text field, you can
pass the BLOB as a string parameter. If the BLOB is stored in binary
format, such as a SQL Server image field, you can pass an array of
type byte as a binary parameter.
Related
We are trying to store an executable(exe) file in SQL. We are getting no error either writing or reading. Just the file we stored is not working after downloading back.
This is how we store the file:
databaseFilePut(#"FilePath", con, dt.Rows[0].ItemArray[0].ToString(), "ASIL");
And this is the inside of the function:
public static void databaseFilePut(string varFilePath, SqlConnection con, string version, string OFSET )
{
byte[] file;
using (var stream = new FileStream(varFilePath, FileMode.Open, FileAccess.Read))
{
using (var reader = new BinaryReader(stream))
{
file = reader.ReadBytes((int)stream.Length);
}
}
using (var sqlWrite = new SqlCommand("UPDATE ERP_TOOL_UPDATE SET Version=#Version1, ExeDosyasi= #ExeDosyasi1, OFSET= #OFSET1", con))
{
sqlWrite.Parameters.AddWithValue("#Version1", (double.Parse(version) + 1).ToString());
sqlWrite.Parameters.Add("#ExeDosyasi1", SqlDbType.VarBinary, file.Length).Value = file;
sqlWrite.Parameters.AddWithValue("#OFSET1", "ASIL");
sqlWrite.ExecuteNonQuery();
}
}
After saving to the database this is what the data like:
0x4D5A90000300000004000000FFFF0000B8000.... and goes on.
After reading we try to recreate the stored exe with this code:
SqlCommand com = new SqlCommand("Select ExeDosyasi From ERP_TOOL_UPDATE WHERE OFSET = 'ASIL' ", con);
com.CommandType = CommandType.Text;
SqlDataReader reader = com.ExecuteReader();
reader.Read();
byte[] blob;
byte[] blob2;
blob = (byte[])reader[0];
blob2 = System.Text.Encoding.Default.GetBytes(System.Text.Encoding.Unicode.GetString(blob));
using (var fs = new FileStream(#"C:\Users\Bilal\Desktop\ERPAnalizTool.exe", FileMode.Create, FileAccess.Write))
{
fs.Write(blob2, 0, blob2.Length);
fs.Flush();
}
We are not getting any errors, it saves the file. Just the problem is the file has a little bit smaller size. When we try to run, it doesn't run. Like it never was an exe before.
Any help would be appreciated. Thank you all.
Your problem is the following line:
blob2 = System.Text.Encoding.Default.GetBytes(System.Text.Encoding.Unicode.GetString(blob));
The blob variable contains the bytes you wrote to the database, which is the content of the file read in the databaseFilePut method. There is no reason at all to convert it to a Unicode string and then to the system default encoding (Windows-1252 on my system). The data is not a string, it is binary. The double conversion will simply produce a mangled byte sequence.
Simply write the blob variable to disk:
blob = (byte[])reader[0];
File.WriteAllBytes(#"C:\Users\Bilal\Desktop\ERPAnalizTool.exe", blob);
I am using WPF to insert an image to my MySQL database. I can upload the file to image control but I don't know how to save it.
Here is what I've done so far. The emp_image is the image control that displays the photo.
private void btn_save_image_click(object sender,...)
{
Mysqlconnection cn= new mysqlconnection(connectionstring);
byte[] imagedata;
imagedata=File.ReadAllBytes(emp_img); //..here is error,it says has invalid arguments..//
mysqlcommand= new mysqlcommand("insert into dep_table(photo)values(?data)",cn);
cmd.parameters.addwithvalue("?data", imagedata);
cn.open();
cmd.executeNonQuery();
cn.close();
}
you need to convert the image source to byte[] :
public static byte[] ImageToArray(BitmapSource image)
{
var encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
using (var stream = new MemoryStream())
{
encoder.Save(stream);
return stream.ToArray();
}
}
Then, call the function:
imagedata = ImageToArray((BitmapSource)emp_img.Source);
Seems you are not passing the file path.
Please check File::ReadAllBytes Method
Should be something like
var imagedata=File.ReadAllBytes(filepath);
I'm trying to get attachments (images, word documents, etc.) stored as an Image datatype from a SQL Server database. The attachments can be of any file type, but I'm just trying to get a .jpg to download successfully.
I'm able to save the file to my local drive, but it appears to be corrupting the file in the process.
What I'm trying to do:
Retrieve binary data of type IMAGE from SQL Server Database.
Create a file from the binary data.
Save the file to a local directory.
My CODE:
public void ProcessRequest()
{
//Get the ticket number from query string
_ticketNumber = context.Request.QueryString["ID"];
SqlConnection conn = new SqlConnection(_DBConn);
SqlCommand cmd = new SqlCommand();
string fileName = ""; //Holds the file name retrieved from DB
byte[] data; // Holds the IMAGE data from DB
using (conn)
{
using (cmd)
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"SELECT File_Name, Data FROM Tickets_All INNER JOIN Attachments ON Tickets_All.ID = Attachments.[Object_ID] WHERE Ticket = #Ticket";
cmd.Parameters.AddWithValue("#Ticket", _ticketNumber);
cmd.Connection = conn;
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
fileName = reader.GetString(0);
data = (byte[])reader["Data"];
if (data != null)
{
SaveData(fileName, data);
}
}
}
reader.Close();
}
}
protected bool SaveData(string FileName, byte[] Data)
{
string path = #"C:\Windows\temp\test.jpg";
try
{
BinaryWriter writer = new BinaryWriter(File.OpenWrite(path));
writer.Write(Data);
writer.Flush();
writer.Close();
}
catch (Exception ex)
{
return false;
}
return true;
}
Please forgive me if the code isn't up to par with best practices, I'm more of a VB programmer and I've never had to do this before. I'm just trying to get a working example.
Thanks in advance.
I would use the Image.FromStream method to do this :
http://msdn.microsoft.com/en-us/library/system.drawing.image.fromstream(v=vs.110).aspx
protected bool SaveData(string FileName, byte[] Data)
{
using (Image image = Image.FromStream(new MemoryStream(Data)))
{
image.Save("MyImage.jpg", ImageFormat.Jpeg);
}
return true;
}
Thanks for the input everyone. After doing some additional testing, I think that the data being retrieved from the database has been compressed in some way. I'm able to insert and pull out files programmatically just fine, the problem comes in when the application puts the data into the database (3rd party software). I'm going to look into the compression what I can come up with.
I have been able to upload an image to sql server, in binary format. This is the code that I am using to upload it..
protected void Button2_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string filename = FileUpload1.FileName;
Stream imgStream = FileUpload1.PostedFile.InputStream;
int imgLen = FileUpload1.PostedFile.ContentLength;
byte[] imgBinaryData = new byte[imgLen];
string strCm = "s_PictInsert";
SqlCommand cm = new SqlCommand(strCm, Cn);
cm.CommandType = CommandType.StoredProcedure;
cm.Parameters.Add(new SqlParameter("#TheImage", SqlDbType.Image)).Value = imgBinaryData;
Cn.Open();
cm.ExecuteNonQuery();
Cn.Close();
}
}
When I look at the database, all I see in the database, of the pic I uploaded, is 0x00000000000000 etc...I don't know why it looks like that...
Then I am using this code to retrieve the image..
protected void Button3_Click(object sender, EventArgs e)
{
string strCm = "select TheImage from [Pictures] where PictureID = 2";
SqlCommand cm = new SqlCommand(strCm, Cn);
cm.CommandType = CommandType.Text;
Cn.Open();
SqlDataReader dr = cm.ExecuteReader();
if (dr.Read())
{
Response.ContentType = "image/jpg";
Response.BinaryWrite((byte[])dr["TheImage"]);
}
Cn.Close();
}
when I click the button it doesn't show me the image it just writes the markup out to the page.
What I want to do is retrieve the image and put it to an asp image, the thing is the images that I upload can be .png format.
I only used response.binarywrite is because that is what I was shown to do. But it doesn't work the way I was told it would.
Thanks
The problem is with your upload function, you are not setting imgBinaryData with the data from the file stream, you are only settings the size to match, so it will default to all zeros.
Instead of this part:
byte[] imgBinaryData = new byte[imgLen];
Replace it with this:
byte[] imgBinaryData = null;
using (var reader = new BinaryReader(FileUpload1.PostedFile.InputStream))
{
imgBinaryData = reader.ReadBytes(FileUpload1.PostedFile.ContentLength);
}
Then check to see what your database data looks like.
On a side note, I would recommend always storing file name and MIME type when storing files in a database, you never know when you will need them!
try this:
var length = FileUpload1.PostedFile.ContentLength;
Byte[] imgBinaryData = new Byte[length];
var stream = FileUpload1.FileContent;
stream.Read(imgBinaryData, 0, length);
then insert the binary object. Your code does not read the image into the stream for insertion. The above code should read the image into the byte array, then your db code should insert actual data instead of the placeholder.
You are storing image in binary format to the database, you will retrieve the same. You need to use MemoryStream to get the image from the byte array that you retrieved.
See this :
Retrieve image from database and display on ASP.NET without httphandler
I have a problem in displaying the picture which is stored in my MySQL database.
I don't know if I have stored it successfully but using this function which converts image to a blob file, here is the function:
private byte[] imageToByteArray(Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
When I check my database, it says BLOB with blue highlight. Now, I would like to display the image in my picturebox. I have also a function to convert byte array to image..
private Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
ms.Position = 0;
Image returnImage = Image.FromStream(ms);
return returnImage;
}
When I run the application, it says:
ArgumentException was unheld, Parameter is not valid
I have tried using this syntax:
pictureBox1.Image = byteArrayToImage(dr["img"] as byte[]);
Or I'm thinking if I should convert BLOB to Byte Array first? then use the function to convert the byte array into Image?
when I click the name, it should display the information, unfortunately, I'm receiving the argument exception..
int i = dataGridView1.SelectedCells[0].RowIndex;
string firstname = dataGridView1.Rows[i].Cells[0].Value.ToString();
string lastname = dataGridView1.Rows[i].Cells[1].Value.ToString();
Connection connect = new Connection();
MySqlConnection mySqlConnect = new MySqlConnection(connect.connString());
mySqlConnect.Open();
string s = "SELECT * FROM tbl_contacts WHERE username = '" + label1.Text + "' and (fname = '" + firstname + "' and lname = '" + lastname + "')";
MySqlCommand mySQL = new MySqlCommand(s, mySqlConnect);
mySQL.ExecuteNonQuery();
MySqlDataReader dr = mySQL.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
txtFname.Text = dr["fname"].ToString();
txtLname.Text = dr["lname"].ToString();
txtBday.Text = dr["birthday"].ToString();
txtEmail.Text = dr["email"].ToString();
txtMobile.Text = dr["mobile"].ToString();
txtAddress.Text = dr["address"].ToString();
txtNotes.Text = dr["notes"].ToString();
pictureBox1.Image = byteArrayToImage(dr["img"] as byte[]);
}
Try something like that :
byteArrayToImage(dr.GetSqlBytes(dr.GetOrdinal("img")).Buffer);
ArgumentException was unheld, Parameter is not valid is due to corrupt image. Your image did not save correctly. Save byte[] you have received in some file in the disk and try to rename it as .jpg or .png and try to open.
Corruption of binary data happens due to various reasons, Length of binary data wasn't saved or trimmed. If your database is configured to store 5kb someone wrote code to trim data to 5kb instead of raising exception or appending buffer wasn't coded correctly resulting in missing last few bytes.