How do I insert bitmap into MySQL in c#? - c#

I'm trying to insert my bitmap Image into MySQL but the problem is that bitmap is not supported. My error:"System.NotSupportedException: 'Parameter type Bitmap is not supported; see https://fl.vu/mysql-param-type. Value: System.Drawing.Bitmap'". My picture datatype in MySQL is a blob. I wonder if I should change the datatype?
My button Register
private void buttonRegister_Click(object sender, EventArgs e)
{
String email = textBoxEmail.Text;
String username = textBoxUsername.Text;
String password = textBoxPassword.Text;
String reTypepassword = textBoxReTypePassword.Text;
UsersClass user = new UsersClass();
System.Security.Cryptography.AesCryptoServiceProvider keyMaker = new System.Security.Cryptography.AesCryptoServiceProvider();
keyMaker.KeySize = 128;
keyMaker.BlockSize = 128;
keyMaker.GenerateKey();
byte[] build = keyMaker.Key;
String Key = Convert.ToBase64String(build);
//MessageBox.Show(Key);
string encryptPassword = user.EncryptString(Key, textBoxPassword.Text);
char[] v = encryptPassword.ToCharArray();
int c = 0;
Bitmap bm = new Bitmap(Image);
for (int w = 0; w < bm.Width; w++)
{
for (int h = 0; h < bm.Height; h++)
{
if (v.Length > c)
{
Color pixel = bm.GetPixel(w, h);
bm.SetPixel(w, h, Color.FromArgb(pixel.R, pixel.G, Convert.ToInt32(v[c])));
c++;
}
}
}
Color p = bm.GetPixel(Image.Width - 1, Image.Height - 1);
bm.SetPixel(Image.Width - 1, Image.Height - 1, Color.FromArgb(p.R, p.G, Convert.ToInt32(c)));
Image = (Image)bm;
imageBox.Image = Image;
myconn.openConnection();
if (password == reTypepassword)
{
MySqlCommand cmd = new MySqlCommand("insert into customer values(#id, #username, #email, #password, #Customer_Request,#location,#address,#key, #picture)", myconn.getConnection());
cmd.Parameters.Add(new MySqlParameter("#id", 0));
cmd.Parameters.Add(new MySqlParameter("#username", textBoxUsername.Text));
cmd.Parameters.Add(new MySqlParameter("#email", textBoxEmail.Text));
cmd.Parameters.Add(new MySqlParameter("#password", encryptPassword));
cmd.Parameters.Add(new MySqlParameter("#Customer_Request", ""));
cmd.Parameters.Add(new MySqlParameter("#location", ""));
cmd.Parameters.Add(new MySqlParameter("#address", textBoxAddress.Text));
cmd.Parameters.Add(new MySqlParameter("#key", Key));
cmd.Parameters.Add(new MySqlParameter("#picture", Image));
cmd.ExecuteNonQuery();
MessageBox.Show("Success to insert");
}
else
{
MessageBox.Show("Please enter the correct password");
}
}

This code writes a PNG file (but that could be another type too) to the database, and retrieves it, and stores it to 'test.png'.
using System.IO;
using MySql.Data.MySqlClient;
class Program
{
static void Main(string[] args)
{
string filename = #"D:/MySQL Server 8.0/Uploads/d95251abfa0f532b0b332906de4d3181b033b35e76319b807c4948df4fa5aa95.png";
string Server = "localhost";
string DatabaseName = "test";
string UserName = "test";
string Password = "test";
string connstring = string.Format("Server={0}; database={1}; UID={2}; password={3}", Server, DatabaseName, UserName, Password);
MySqlConnection conn = new MySqlConnection(connstring);
conn.Open();
string sql = "INSERT INTO pic VALUES(#idpic,#caption,#image)";
var cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#idpic",null);
cmd.Parameters.AddWithValue("#caption","test");
cmd.Parameters.AddWithValue("#image", File.ReadAllBytes(filename));
var result = cmd.ExecuteNonQuery();
var lastId = cmd.LastInsertedId;
Console.WriteLine($"Executing insert resulted in {result}, with idpic={lastId}");
sql = "SELECT img FROM pic WHERE idpic=#id";
cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#id", lastId);
MySqlDataReader reader = cmd.ExecuteReader();
reader.Read();
byte[] picture = (byte[])reader["img"];
File.WriteAllBytes(#"d:\temp\test.png", picture);
conn.Close();
}
}
The MySQL table was created as follows:
CREATE TABLE `pic` (
`idpic` int unsigned NOT NULL AUTO_INCREMENT,
`caption` varchar(45) NOT NULL,
`img` longblob NOT NULL,
PRIMARY KEY(`idpic`)
) ENGINE=InnoDB AUTO_INCREMENT = 2 DEFAULT CHARSET = utf8mb4 COLLATE=utf8mb4_0900_ai_ci
There are, at least two settings which needs to be checked.
max_allowed_packet Should be set larger than the maximum file size for the picture.
secure_file_priv If this is set, only files from the directory specified can be inserted to your database.
The user that is connecting to the database should be granted FILE access

Related

Insert image in Oracle Database using OleDb from a C# application

I want to insert a PNG image into an OracleDatabase using OleDb and a C# application. The table looks like this:
CREATE TABLE Plant
(
Id NUMBER GENERATED BY DEFAULT ON NULL AS IDENTITY,
Name VARCHAR2(50) NOT NULL,
Image BLOB null,
CONSTRAINT plant_pk PRIMARY KEY (Id)
);
Below is the code:
public static void AddBinaryParameterToCommand(OleDbCommand cmd, string parameterColumn, object parameter)
{
if (cmd != null)
{
if (parameter != null && !parameter.ToString().Equals(""))
{
OleDbParameter blobParameter = new OleDbParameter();
blobParameter.OleDbType = OleDbType.LongVarBinary;
blobParameter.Direction = ParameterDirection.InputOutput;
blobParameter.ParameterName = parameterColumn;
blobParameter.Value = parameter;
cmd.Parameters.Add(blobParameter);
}
else
cmd.Parameters.Add(new OleDbParameter(parameterColumn, DBNull.Value));
}
}
public int InsertPlant(string name, byte[] image)
{
int id = 0;
using (var connection = new OleDbConnection(ConnectionString))
{
var commandGetIdText = #"SELECT MAX(id) FROM PLANT";
connection.Open();
using (var command = new OleDbCommand(commandGetIdText, connection))
{
using (var reader = command.ExecuteReader())
{
reader.Read();
id = int.Parse(reader[0].ToString()) + 1;
}
}
var commandText = string.Format("INSERT INTO PLANT(ID,NAME,IMAGE) VALUES (?, ?, ?)");
using (var command = new OleDbCommand(commandText, connection))
{
Utils.AddParameterToCommand(command, "ID", id);
Utils.AddParameterToCommand(command, "NAME", name);
Utils.AddBinaryParameterToCommand(command, "IMAGE", image);
command.ExecuteNonQuery();
connection.Close();
}
}
return id;
}
private void button_UploadMap_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog
{
Multiselect = true
};
var path = string.Empty;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
path = openFileDialog.FileName;
}
else
{
return;
}
byte[] imageArray = File.ReadAllBytes(path);
var palletMapDL = new PalletMapDL("Data Source=192.168.1.21/orcl;Persist Security Info=True; Password=test;User ID=test; Provider=MSDAORA; OLEDB.NET=True; PLSQLRSet=1");
palletMapDL.InsertPlant("Test Plant 01", imageArray);
When execute command.ExecuteNonQuery(); I got this error message:
System.InvalidOperationException: 'Command parameter[2] '' data value
could not be converted for reasons other than sign mismatch or data
overflow.
OleDbException: 'MSDAORA' failed with no error message available,
result code: DB_E_ERRORSOCCURRED(0x80040E21).
Do you know what could be the issue?
Thanks

Saving Image into SQL Server database

When I insert an image into a SQL Server database, if the image is null, then it inserts a 0x value into the database image column.
When I retrieve the image with 0x hex value, I get an error:
Parameter is not valid
string strsql = "SELECT [ID],PIC_Name FROM [HRMS].[dbo].[Employee_PC] where Id = '" + mFieldValue1 + "'";
myconn = new OleDbConnection(clsConnections.conString);
myconn.Open();
cmd = new OleDbCommand(strsql, myconn);
OleDbDataReader dr = null;
dr = cmd.ExecuteReader();
while (dr.Read())
{
if ((byte[])dr[1] == null )
//if (picData == null)
{
pictureBox1.Image = null;
}
else
{
MemoryStream ms = new MemoryStream((byte[])dr[1]);
ms.Position = 0;
pictureBox1.Image = new Bitmap(ms);
}
}
dr[1] won't be null, so neither will (byte[])dr[1]. You want to check the first byte in that array.
byte[] picData = (byte[])dr[1];
if (picData[0] == 0)
{
pictureBox1.Image = null;
}
else
{
MemoryStream ms = new MemoryStream(picData);
ms.Position = 0;
pictureBox1.Image = new Bitmap(ms);
}

how to saved different sheet from excel file to mysql database

I have a code that importing and displaying a excel file to datagridview and I'm wondering if you help me to how can I save those sheet from my excel file to my database in mysql?? My sheet name are 1st grading, 2nd grading and attendance, I'm using c#. Anyway here's my code:
private void btnSaved_Click(object sender, EventArgs e)
{
int qtr = 0;
string att_qtr = "ATTENDANCE";
MySqlConnection con = new MySqlConnection("Server = DESKTOP-9H7QBOH; Database = sti_spms; UID = root; Password = 1234;");
try
{
string query = "INSERT INTO tbl_secondsem_grades(STUDENT_NO, NAME, SUBJECT, SECTION, GRADE, INITIAL_GRADE, QTR)" + "Values(#STUDENT_NO, #NAME, #SUBJECT, #SECTION, #GRADE, #INITIAL_GRADE, #QTR)";
query += "INSERT INTO tbl_attendance(STUDENT_ID, NAME, SUBJECT, SECTION, TOTAL_ABSENCES)" + "Values(#STUDENT_ID, #NAME, #SUBJECT, #SECTION, #TOTAL_ABSENCES)";
MySqlCommand cmd = new MySqlCommand(query, con);
DataTable dt = new DataTable();
con.Open();
for (int i = 0; i < dataGridView1.Rows.Count -1; i++)
{
if(quarter.Equals("1st QTR"))
{
qtr = 1;
}
else if(quarter.Equals("2nd QTR"))
{
qtr = 2;
}
else if(quarter.Equals("3rd QTR"))
{
qtr = 3;
}
else if(quarter.Equals("4th QTR"))
{
qtr = 4;
}
else if (quarter.Equals("ATTENDANCE"))
{
att_qtr = "ATTENDANCE";
}
else
{
MessageBox.Show("Error!");
}
//int num = Convert.ToInt32(dataGridView1.Rows[i].Cells["STUDENT NO"].Value.ToString());
cmd.Parameters.AddWithValue("#STUDENT_NO", dataGridView1.Rows[i].Cells["STUDENT NO"].Value.ToString());
cmd.Parameters.AddWithValue("#NAME", dataGridView1.Rows[i].Cells["NAME"].Value.ToString());
cmd.Parameters.AddWithValue("#SUBJECT", dataGridView1.Rows[i].Cells["SUBJECT"].Value.ToString());
cmd.Parameters.AddWithValue("#SECTION", dataGridView1.Rows[i].Cells["SECTION"].Value.ToString());
cmd.Parameters.AddWithValue("#INITIAL_GRADE", dataGridView1.Rows[i].Cells["INITIAL GRADE"].Value.ToString());
cmd.Parameters.AddWithValue("#GRADE", dataGridView1.Rows[i].Cells["QG"].Value.ToString());
cmd.Parameters.AddWithValue("#QTR", qtr);
cmd.Parameters.AddWithValue("#STUDENT_NO", dataGridView1.Rows[i].Cells["STUDENT NO"].Value.ToString());
cmd.Parameters.AddWithValue("#NAME", dataGridView1.Rows[i].Cells["NAME"].Value.ToString());
cmd.Parameters.AddWithValue("#SUBJECT", dataGridView1.Rows[i].Cells["SUBJECT"].Value.ToString());
cmd.Parameters.AddWithValue("#SECTION", dataGridView1.Rows[i].Cells["SECTION"].Value.ToString());
cmd.Parameters.AddWithValue("#Total_Absences", dataGridView1.Rows[i].Cells["Total_Absences"].Value.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
catch (Exception ex)
{
MessageBox.Show("Data Sucessfully Saved!");
}
}
Quickie partial
...
MySqlCommand cmd = new MySqlCommand(query, con);
DataTable dt = new DataTable();
cmd.Paramters.Add("#STUDENT_NO", MySqlDbType.Int); .. guessing this is an int - otherwise choose type
cmd.Paramters.Add("#NAME", MySqlDbType.String);
... // add rest here
con.Open();
...
for (.. ) {
...
int studentno;
int.TryParse(dataGridView1.Rows[i].Cells["STUDENT NO"].Value.ToString(), out studentno);
cmd.Paramters["#STUDENT_NO"].Value = studentno;
cmd.Paramters["#NAME"].Value = dataGridView1.Rows[i].Cells["NAME"].Value.ToString();
...
}

ColdFusion query to C# Winform

I was given a query, originally done in ColdFusion, but I am having difficulties with the translation to a Winform use. I have a textbox that contains a concatenated string of other textboxes to make a case number. The purpose of this is to check for a record that might have been a transfer. In the first query, it is based on column caa443400048 either having something or being NULL. How would I incorporate that into a conditional statement for checking?
<cfquery name="q_transfer" datasource=#DSN#>
SELECT caa443400048
FROM caa44340
WHERE caa44340041 = '#SearchCaseNo#'
</cfquery>
<CFSET TransferCaseNo = "">
<CFSET TransferFlag = 'N'>
<CFIF #q_transfer.caa443400048# NEQ "">
<cfquery name="q_newcaseno" datasource=#DSN# >
SELECT caa44340041
FROM caa44340
WHERE caa443400018 = '#q_transfer.caa443400048#'
</cfquery>
<CFSET TransferFlag = 'Y'>
<CFSET TransferCaseNo = #SearchCaseNo#>
<CFSET SearchCaseNo = #q_newcaseno.caa44340041#>
</cfif>
Here is the C# code I am currently using:
string sql = "select COUNT (caa443400048) FROM caa44340 WHERE caa44340041 = ? ";
OdbcConnection con = new OdbcConnection("Dsn=XXXXX; User ID=XXXXX; Password=XXXXX");
con.Open();
OdbcCommand cmd = new OdbcCommand(sql, con);
cmd.Parameters.AddWithValue("caa44340041", txtCustomCaseNumber.Text);
int count = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
if (count != 0)
{
MessageBox.Show("This is a transfer");
}
else
{
MessageBox.Show("This is not a transfer");
}
I'm not 100%, but maybe this may help:
var TransferFlag = "N";
var SearchCaseNo = "";
var q_transfer = "";
var q_newcaseno = "";
using (var con = new OdbcConnection("Dsn=XXXXX; User ID=XXXXX; Password=XXXXX"))
{
con.Open();
using (var cmd = new OdbcCommand("SELECT caa443400048 FROM caa44340 WHERE caa44340041 = ?", con))
{
cmd.Parameters.AddWithValue("#var", txtCustomCaseNumber.Text);
q_transfer = (string)cmd.ExecuteScalar();
}
if (!string.IsNullOrEmpty(q_transfer))
{
using (var cmd = new OdbcCommand("SELECT caa44340041 FROM caa44340 WHERE caa443400018 = ?", con))
{
cmd.Parameters.AddWithValue("#var", q_transfer);
q_newcaseno = (string)cmd.ExecuteScalar();
}
TransferFlag = "Y";
SearchCaseNo = q_newcaseno;
MessageBox.Show("This is a transfer");
}
else
MessageBox.Show("This is not a transfer");
}

How to display images with fixed dimensions in ASP.NET after retrieving them from a MySQL database

Following are the links which describe connection to MySQL:
http://www.codeproject.com/KB/aspnet/asp_net_and_mysql.aspx
http://www.codeproject.com/KB/aspnet/image_asp.aspx
Here is the code to display image from mysql database:
protected void Page_Load(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection(db);
conn.Open();
string s;
s = Session["t"].ToString();
string commantext = "select img_id,img_file,img_type,img_name from image where img_name='"+s+"'";
// string commantext = "select img_id,img_file,img_type,img_name from image";
// DataSet ds = MySqlHelper.ExecuteDataset(conn, commantext);
MySqlCommand cmd = new MySqlCommand(commantext,conn);
cmd.Parameters.Add("?img_id", MySqlDbType.Int32).Value = s;
// DataTable dt = ds.Tables[0];
DataTable dt = GetData(cmd);
while(dt !=null)
{
Byte[] bytes = (Byte[])dt.Rows[0]["img_file"];
// Byte[] bytes = (Byte[])dt.Rows[1][] ;
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["img_type"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["img_name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
conn.Close();
}
private DataTable GetData(MySqlCommand cmd)
{
DataTable dt = new DataTable();
//String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
MySqlConnection con = new MySqlConnection(db);
MySqlDataAdapter sda = new MySqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{ return null;
}
finally
{ con.Close();
sda.Dispose();
con.Dispose();
}
}
My code to upload image file to mysql database is as below.
protected void Button1_Click(object sender, EventArgs e)
{
Stream img_strm = File1.PostedFile.InputStream;
int img_len = File1.PostedFile.ContentLength;
string strtype = File1.PostedFile.ContentType;
//code snippet to determine image height and width.
System.Drawing.Image i = System.Drawing.Image.FromStream(img_strm);
int fileheight = int.Parse(i.Width.ToString());
int filewidth = int.Parse(i.Height.ToString());
strname = Text1.Value;
//Session["t"] = strname;
byte[] imgData = new byte[img_len];
int n = img_strm.Read(imgData, 0, img_len);
int result = saveToDb(strname, imgData, strtype);
}
private int saveToDb(string imgName, byte[] imgbin, string imgContenttype)
{
string db = "server=localhost;database=test;uid=root;password=techsoft";
MySqlConnection conn = new MySqlConnection(db);
MySqlCommand cmd = new MySqlCommand("insert into image(img_name,img_file,img_type) values(?img_name,?img_file,?img_type)", conn);
//MySqlParameter param0 = new MySqlParameter("?img_id", MySqlDbType.Int16, 20);
//param0.Value = ;
//cmd.Parameters.Add(param0);
MySqlParameter param0 = new MySqlParameter("?img_name", MySqlDbType.VarChar, 45);
param0.Value = imgName;
cmd.Parameters.Add(param0);
// MySqlParameter param1 = new MySqlParameter("?img_file", MySqlDbType.VarChar, 45);
MySqlParameter param1 = new MySqlParameter("?img_file", MySqlDbType.LongBlob, 10);
param1.Value = imgbin;
cmd.Parameters.Add(param1);
MySqlParameter param2 = new MySqlParameter("?img_type", MySqlDbType.VarChar, 45);
param2.Value = imgContenttype;
cmd.Parameters.Add(param2);
conn.Open();
int num = cmd.ExecuteNonQuery();
conn.Close();
return num;
}
I have used binary writer to display. Can anybody suggest how to display images in fixed dimensions?
I would resize the images on the page being used to display them. Where are they being displayed?
or
I would resize the images at the time they are saved
Assuming your only challenge is to only scale the images(either before uploading or when retrieving them)...here is some code i use to get scaled dimensions for an image (to fit specific fixed dimensions)...you can stick this somewhere in an imaging class
Note that there are many approaches...
public static Size getScaledDimensions( Image img, Int32 maxW, Int32 maxH)
{
//check if image is already within desired dimensions
if (img.Height <= maxH & img.Width <= maxW)
{
Size orgsize = new Size(img.Width, img.Height);
return orgsize; // no need to rescale
}
else //proceed with rescaling
{
int finalH;
int finalW;
//use height/width ratio to determine our new dimensions
double hwRatio = (double)img.Height / (double)img.Width;
int newW = (int) (maxH/ hwRatio);
int newH = (int) (hwRatio * maxW);
//make sure we scale the right dimension
if (newW <= maxW) // scale width
{
finalH = maxH;
finalW = newW;
}
else
{ // scale height
finalH = newH;
finalW = maxW;
}//end if
Size newsize = new Size(finalW, finalH);
return newsize;
}
Thanks for all the support from rip and The_AlienCoder for their answers. I have found out answer to my own query.
We need to use streams to convert binary data from mysql database. Later graphic library should be used to load the streams. In the meantime we need to resize the image according to our need.
protected void Page_Load(object sender, EventArgs e){
//Create connection to mysql database.
MySqlConnection conn = new MySqlConnection(db);
conn.Open();
string s;
s = Session["t"].ToString();
string commantext = "select img_id,img_file,img_type,img_name from image where img_name='"+s+"'";
MySqlCommand cmd = new MySqlCommand(commantext,conn);
cmd.Parameters.Add("?img_id", MySqlDbType.Int32).Value = s;
//create datatable. GetData is a method to fetch the data.
DataTable dt = GetData(cmd);
//Get data from database to bytes.
Byte[] bytes = (Byte[])dt.Rows[0]["img_file"];
//Defining the size to display data.
int outputSize = 100;
if (bytes.Length > 0)
{
// Open a stream for the image and write the bytes into it
System.IO.MemoryStream stream = new System.IO.MemoryStream(bytes, true);
stream.Write(bytes, 0, bytes.Length);
Bitmap bmp = new Bitmap(stream);
Size new_size = new Size();
//resize based on the longer dimension
if (bmp.Width > bmp.Height)
{
new_size.Width = outputSize;
new_size.Height = (int)(((double)outputSize / (double)bmp.Width) * (double)bmp.Height);
}
else
{
new_size.Width = (int)(((double)outputSize / (double)bmp.Height) * (double)bmp.Width);
new_size.Height = outputSize;
}
Bitmap bitmap = new Bitmap(new_size.Width, new_size.Height, bmp.PixelFormat);
Graphics new_g = Graphics.FromImage(bitmap);
new_g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
new_g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
new_g.DrawImage(bmp, -1, -1, bitmap.Width + 1, bitmap.Height + 1);
bmp.Dispose();
bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
bitmap.Dispose();
new_g.Dispose();
stream.Close();
}
}
private DataTable GetData(MySqlCommand cmd)
{
DataTable dt = new DataTable();
//String strConnString = System.Configuration.ConfigurationManager .ConnectionStrings["conString"].ConnectionString;
MySqlConnection con = new MySqlConnection(db);
MySqlDataAdapter sda = new MySqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{ return null;
}
finally
{ con.Close();
sda.Dispose();
con.Dispose();
}
}
}

Categories