How can I Print label from database select result using loop - c#

I've to say this first , I'm new to windows programming,
I have got a requirement to print a set of results getting from a search query. Each resulted row should be printed on individual labels . A sample result set is included in the query. What is the best way achieving this.The barcode column shown should printed as bar code and the other two columns should print above and below the label.
Normally we may have to print up to 500 labels in a single button click.
Below I've added the code I'm working with. In the page load event I'm passing the ID to load data for a specific item from database. But I need to make it automated with a selected list of items, not a single one.
Result set
public partial class PrintLabel : Form
{
string s_desc = "";
string s_date = "";
Image bCodeImage;
public PrintLabel()
{
InitializeComponent();
}
private void PrintLabel_Load(object sender, EventArgs e)
{
FillData(735);
}
private void Print_Click(object sender, EventArgs e)
{
ItemPrint();
this.Close();
}
void FillData(int ID)
{
string str = Properties.Settings.Default.ConW;
using (SqlConnection conn = new SqlConnection(str))
{
try
{
string query = "select item.ID+'-'+item.ItemLookupCode as Barcode,ExtendedDescription,GETDATE()+180 Expiry from Item where ID=" + ID + ";";
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader dtr = cmd.ExecuteReader();
if (dtr.Read())
{
GenerateBarcode(dtr[0].ToString());
s_desc = dtr[1].ToString();
s_date = dtr[2].ToString();
lblDescription.Text = s_desc;
lblExpiry.Text = s_date;
PBBarcode.Image = bCodeImage;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void GenerateBarcode(string _bCodeImage)
{
string barCode = _bCodeImage;
Bitmap bitmap = new Bitmap(barCode.Length * 60, 750);
using (Graphics grapics = Graphics.FromImage(bitmap))
{
Font ofont = new System.Drawing.Font("IDAHC39M Code 39 Barcode", 14);
PointF point = new PointF(2f, 2f);
SolidBrush black = new SolidBrush(Color.Black);
SolidBrush white = new SolidBrush(Color.White);
grapics.FillRectangle(white, 0, 0, bitmap.Width, bitmap.Height);
grapics.DrawString("*" + barCode + "*", ofont, black, point);
}
using (MemoryStream ms = new MemoryStream())
{
bitmap.Save(ms, ImageFormat.Png);
bCodeImage = bitmap;
}
}
private void ItemPrint()
{
PrintDialog printdg = new PrintDialog();
if (printdg.ShowDialog() == DialogResult.OK)
{
PrintDocument pd = new PrintDocument();
pd.PrinterSettings = printdg.PrinterSettings;
pd.PrintPage += PrintPage;
pd.Print();
pd.Dispose();
}
}
private void PrintPage(object o, PrintPageEventArgs e)
{
lblDescription.Text = s_desc;
lblExpiry.Text = s_date;
PBBarcode.InitialImage = bCodeImage;
}
}

I've achieved it using the below code, posting as it may help some one in the future.
private void PrintLabelVal()
{
string str = Properties.Settings.Default.con;
SqlConnection Conn = new SqlConnection(str);
string query = " SELECT TempLotUpdate.Quantity,Item.BinLocation,Item.ItemLookupCode," +
" Item.ExtendedDescription,Item.LotNumber," +
" Item.ExpiryDate " +
" FROM TempLotUpdate" +
" INNER JOIN Item ON TempLotUpdate.ItemId = Item.ID" +
" WHERE TempLotUpdate.PONumber = '" + Globals.s_PON + "'; ";
int cnt = 0;
int var = 0;
SqlCommand cmd = new SqlCommand(query, Conn);
try
{
Conn.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
for (var i = 0; i < dt.Rows.Count; i++)
{
cnt = Convert.ToInt32(dt.Rows[i][0]);
var = Convert.ToInt32(dt.Rows[i][4]);
for (var j = 0; j < cnt; j++)
{
var = Convert.ToInt32(dt.Rows[i][4]);
print(var); // Passing Lot ID
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void print(int obj)
{
FillData(obj);
ItemPrint();
this.Close();
}
void FillData(int ID)
{
string str = Properties.Settings.Default.con;
using (SqlConnection conn = new SqlConnection(str))
{
try
{
string query = "SELECT ItemLookupCode BarCode,Description,ExpiryDate,BinLocation,Price " +
" FROM Item where ID = " + ID + ";";
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader dtr = cmd.ExecuteReader();
if (dtr.Read())
{
barCode = dtr[0].ToString();
s_desc = dtr[1].ToString();
s_date = dtr[2].ToString();
s_BinLoc = dtr[3].ToString();
s_Price = dtr[4].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void ItemPrint()
{
PrintDialog printdg = new PrintDialog();
if (printdg.ShowDialog() == DialogResult.OK)
{
PrintDocument pd = new PrintDocument();
pd.PrinterSettings = printdg.PrinterSettings;
pd.PrintPage += PrintPage;
pd.Print();
pd.Dispose();
}
}
private void PrintPage(object o, PrintPageEventArgs e)
{
string _desc = s_desc;
var _g = e.Graphics;
_g.DrawString(_desc, new Font("Arial Black", 7), Brushes.Black, 5, 8);
string _bCode = "*"+barCode+"*";
var _f = e.Graphics;
_f.DrawString(_bCode, new Font("IDAHC39M Code 39 Barcode", 8), Brushes.Black, 4, 25);
string _BinLoc = s_BinLoc;
var _i = e.Graphics;
_i.DrawString(_BinLoc, new Font("Arial Narrow", 7), Brushes.Black, 5, 75);
string _date = "Exp: " + s_date.Substring(0, 10);
var _h = e.Graphics;
_h.DrawString(_date, new Font("Arial Narrow", 7), Brushes.Black, 45, 75);
string _Price = s_Price;
var _j = e.Graphics;
_j.DrawString(_Price, new Font("Arial Narrow", 7), Brushes.Black, 120, 75);
}

Related

how i dynamically create text box on run time and display data text box form MYSQL C#?

private void button1_Click(object sender, EventArgs e)
{
try
{
string MyConnection2 = "datasource = 127.0.0.1;port=3306;username = root;password =; database = test123; SslMode=None ;Convert Zero Datetime=True";
int txtno = int.Parse(textBox1.Text);
int pointX = 30;
int pointY = 40;
panel2.Controls.Clear();
for (int i = 0; i < txtno; i++)
{
TextBox a = new TextBox();
a.Text = (i + 1).ToString();
a.Location = new Point(pointX, pointY);
panel2.Controls.Add(a);
panel2.Show();
pointY += 20;
}
string Query = "select task_comment from test123.task_comment where task_id ='" + textBox1.Text + "'";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
MyConn2.Close();
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
while (MyReader2.Read())
{
txtno = Convert.ToInt32(MyReader2["task_comment"].ToString());
}
MyConn2.Close(); //Connection closed here
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Try This:
protected void Page_Load(object sender, EventArgs e)
{
int n = 4;//fetch your rows from database in datatable, then count number of rows. And based on those
//count create textboxes.
TextBox[] textBoxes = new TextBox[n];
for (int i = 0; i < n; i++)
{
textBoxes[i] = new TextBox();
// Here you can modify the value of the textbox which is at textBoxes[i]
textBoxes[i].Text="Your text from database";
}
}
Hope this helps!
Suppose you have the data retrieved from MySql in a list of object with propertis ID and Name, so you loop over them and create a textbox and add it to the form:
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
while (MyReader2.Read())
{
txtno = Convert.ToInt32(MyReader2["task_comment"].ToString());
TextBox bx = new TextBox();
bx.Text = txtno;
// retrieve here any other data u need to assign to the textbox
bx.Location = new Point(x, y);// x and y should be the calculated //coordinates, this will depend on how you want to display the textboxes
this.Controls.Add(bx);// Add the textbox to the form
}
MyConn2.Close(); //Connection closed here
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Acces dynamically created controls from other method C#

I'm trying to acces my dynamically created Textbox through the click of a button.
private void assortiment_Load(object sender, EventArgs e)
{
string lastorder = "Select MAX(idorders) From orders";
string query = "Select * From Product";
var cmd = new MySqlCommand(lastorder, connection);
cmd.CommandType = CommandType.Text;
int orderid = Convert.ToInt32(cmd.ExecuteScalar());
label1lblorderid.Text = orderid.ToString();
var cmd2 = new MySqlCommand(query, connection);
var da = new MySqlDataAdapter(cmd2);
var ds = new DataSet();
da.Fill(ds, "Image");
int count = ds.Tables["Image"].Rows.Count;
var y = 3;
for (int i = 0; i < count; i++)
{
var data = (Byte[])(ds.Tables["Image"].Rows[i]["Image"]);
var stream = new MemoryStream(data);
//picture box creation
var pbList = new PictureBox
{
Name = "pic" + i,
Size = new Size(150, 150),
SizeMode = PictureBoxSizeMode.StretchImage,
Image = Image.FromStream(stream)
};
//panel creation
var tblPanelList = new TableLayoutPanel
{
Name = "tblp" + i,
Size = new Size(380, 150),
Location = new System.Drawing.Point(219, y),
BackColor = Color.ForestGreen,
GrowStyle = TableLayoutPanelGrowStyle.AddColumns,
ColumnCount = 2
};
//other
productid = Convert.ToInt32((ds.Tables["Image"]
.Rows[i]["idproduct"]).ToString());
//Textbox: Aantal
var tbAantal = new TextBox { Size = new Size(107, 20),
Name = "tbaantal" + productid};
//label productid
var lblproductid = new Label();
lblproductid.Text = productid.ToString();
//Button: Bestellen
var btnBestel = new Button();
btnBestel.Name = "bestel" + productid;
btnBestel.Text = "Bestellen";
btnBestel.Anchor = AnchorStyles.Right;
btnBestel.Click += btnBestel_Click;
//Voeg controls toe
this.panel.Controls.Add(pbList);
this.Controls.Add(tblPanelList);
tblPanelList.Controls.Add(naam);
tblPanelList.Controls.Add(omschrijving);
tblPanelList.Controls.Add(lblAantal);
tblPanelList.Controls.Add(tbAantal);
tblPanelList.Controls.Add(btnBestel,1,10);
tblPanelList.Controls.Add(lblproductid);
y = y + 156;
}
}
void btnBestel_Click(object sender, EventArgs e)
{
MainForm frm_1 = new MainForm();
var button = sender as Button;
string btnname = button.Name.ToString();
//btnname.Remove(1, 6);
int orderid = Convert.ToInt32(label1lblorderid.Text);
Control tbAantalControl = FindControl("tbAantal" + btnname.Remove(0, 6));
int aantal = Convert.ToInt32(tbAantalControl.Text);
//MessageBox.Show(btnname.Remove(0,6));
string query = "Insert Into orderproduct(idorder, idproduct, aantal)
Values('" + orderid + "'" + productid +
"'" + aantal + "')";
var cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
}
As you can see, I have already tried to access the Textbox by a FindControl(), But this didn't work. I want the Textbox that has the same last value as the clicked TextBox, I'm trying to do this by cutting the string and paste that in a variable.
Please help.
First of all you are searching for TextBoxes with different names than you create them with (tbAantal... vs. tbaantal...). Together with a recursive Find method that would work.
Neither is that good practice nor is it fast.
Better
Rather than searching for controls by name each time you create them you should implement something that directly let's you retrieve the controls (via some identifier or similar, in your case: via productid).
For example:
Declare a Dictionary<int, TextBox> textBoxes as a local variable. In your loop, add textBoxes.Add(productid, tbAantal); right after your definition of tbAantal.
In btnBestel_Click you can then use this mapping to retrieve the correct TextBox via textBoxes[productid].
I am aware that you don't really have the productid defined in that context.
Instead of using btnname.Remove(0, 6), you should use the Buttons's Tag property and store the productid as extra metadata:
Back in your loop add btnBestel.Tag = productid; at the appropriate position. In btnBestel_Click you can then write textBoxes[(int)button.Tag].
Overall code in that case
Dictionary<int, TextBox> textBoxes = new Dictionary<int,TextBox>();
private void assortiment_Load(object sender, EventArgs e)
{
string lastorder = "Select MAX(idorders) From orders";
string query = "Select * From Product";
var cmd = new MySqlCommand(lastorder, connection);
cmd.CommandType = CommandType.Text;
int orderid = Convert.ToInt32(cmd.ExecuteScalar());
label1lblorderid.Text = orderid.ToString();
var cmd2 = new MySqlCommand(query, connection);
var da = new MySqlDataAdapter(cmd2);
var ds = new DataSet();
da.Fill(ds, "Image");
int count = ds.Tables["Image"].Rows.Count;
var y = 3;
for (int i = 0; i < count; i++)
{
var data = (Byte[])(ds.Tables["Image"].Rows[i]["Image"]);
var stream = new MemoryStream(data);
//picture box creation
var pbList = new PictureBox
{
Name = "pic" + i,
Size = new Size(150, 150),
SizeMode = PictureBoxSizeMode.StretchImage,
Image = Image.FromStream(stream)
};
//panel creation
var tblPanelList = new TableLayoutPanel
{
Name = "tblp" + i,
Size = new Size(380, 150),
Location = new System.Drawing.Point(219, y),
BackColor = Color.ForestGreen,
GrowStyle = TableLayoutPanelGrowStyle.AddColumns,
ColumnCount = 2
};
//other
productid = Convert.ToInt32((ds.Tables["Image"]
.Rows[i]["idproduct"]).ToString());
//Textbox: Aantal
var tbAantal = new TextBox { Size = new Size(107, 20),
Name = "tbaantal" + productid};
textBoxes.Add(productid, tbAantal);
//label productid
var lblproductid = new Label();
lblproductid.Text = productid.ToString();
//Button: Bestellen
var btnBestel = new Button();
btnBestel.Name = "bestel" + productid;
btnBestel.Text = "Bestellen";
btnBestel.Anchor = AnchorStyles.Right;
btnBestel.Click += btnBestel_Click;
btnBestel.Tag = productid;
//Voeg controls toe
this.panel.Controls.Add(pbList);
this.Controls.Add(tblPanelList);
tblPanelList.Controls.Add(naam);
tblPanelList.Controls.Add(omschrijving);
tblPanelList.Controls.Add(lblAantal);
tblPanelList.Controls.Add(tbAantal);
tblPanelList.Controls.Add(btnBestel,1,10);
tblPanelList.Controls.Add(lblproductid);
y = y + 156;
}
}
void btnBestel_Click(object sender, EventArgs e)
{
MainForm frm_1 = new MainForm();
var button = sender as Button;
int orderid = Convert.ToInt32(label1lblorderid.Text);
Control tbAantalControl = textBoxes[(int)button.Tag];
int aantal = Convert.ToInt32(tbAantalControl.Text);
string query = "Insert Into orderproduct(idorder, idproduct, aantal)
Values('" + orderid + "'" + productid +
"'" + aantal + "')";
var cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
}
I am not sure you are giving valid control name for search. For checking you should apply break point on the line, to see if you are getting valid control name.
For searching your required control by name you should look into each parent control recursively. FindControl method can be used for the purpose.
Change this:
Control tbAantalControl = FindControl("tbAantal" + btnname.Remove(0, 6));
With this:
Control tbAantalControl = FindControl(this.Controls, "tbAantal" + btnname.Remove(0, 6));
Method that recursive find your required:
private Control FindControl(Control.ControlCollection controlCollection, string name)
{
foreach (Control control in controlCollection)
{
if (control.Name.ToLower() == name.ToLower())
{
return control;
}
if (control.Controls.Count > 0)
{
Control result = FindControl(control.Controls, name);
if (result != null)
{
return result;
}
}
}
return null;
}
Is there any reason why you can't just make tbAantal a form level variable and then reference that in the btnBestel_Click method?
var tbAantal = null;
private void assortiment_Load(object sender, EventArgs e)
{
string lastorder = "Select MAX(idorders) From orders";
string query = "Select * From Product";
var cmd = new MySqlCommand(lastorder, connection);
cmd.CommandType = CommandType.Text;
int orderid = Convert.ToInt32(cmd.ExecuteScalar());
label1lblorderid.Text = orderid.ToString();
var cmd2 = new MySqlCommand(query, connection);
var da = new MySqlDataAdapter(cmd2);
var ds = new DataSet();
da.Fill(ds, "Image");
int count = ds.Tables["Image"].Rows.Count;
var y = 3;
for (int i = 0; i < count; i++)
{
var data = (Byte[])(ds.Tables["Image"].Rows[i]["Image"]);
var stream = new MemoryStream(data);
//picture box creation
var pbList = new PictureBox
{
Name = "pic" + i,
Size = new Size(150, 150),
SizeMode = PictureBoxSizeMode.StretchImage,
Image = Image.FromStream(stream)
};
//panel creation
var tblPanelList = new TableLayoutPanel
{
Name = "tblp" + i,
Size = new Size(380, 150),
Location = new System.Drawing.Point(219, y),
BackColor = Color.ForestGreen,
GrowStyle = TableLayoutPanelGrowStyle.AddColumns,
ColumnCount = 2
};
//other
productid = Convert.ToInt32((ds.Tables["Image"].Rows[i]["idproduct"]).ToString());
//Textbox: Aantal
tbAantal = new TextBox { Size = new Size(107, 20), Name = "tbaantal" + productid};
//label productid
var lblproductid = new Label();
lblproductid.Text = productid.ToString();
//Button: Bestellen
var btnBestel = new Button();
btnBestel.Name = "bestel" + productid;
btnBestel.Text = "Bestellen";
btnBestel.Anchor = AnchorStyles.Right;
btnBestel.Click += btnBestel_Click;
//Voeg controls toe
this.panel.Controls.Add(pbList);
this.Controls.Add(tblPanelList);
tblPanelList.Controls.Add(naam);
tblPanelList.Controls.Add(omschrijving);
tblPanelList.Controls.Add(lblAantal);
tblPanelList.Controls.Add(tbAantal);
tblPanelList.Controls.Add(btnBestel,1,10);
tblPanelList.Controls.Add(lblproductid);
y = y + 156;
}
}
void btnBestel_Click(object sender, EventArgs e)
{
MainForm frm_1 = new MainForm();
var button = sender as Button;
string btnname = button.Name.ToString();
//btnname.Remove(1, 6);
int orderid = Convert.ToInt32(label1lblorderid.Text);
int aantal = Convert.ToInt32(tbAantal.Text);
//MessageBox.Show(btnname.Remove(0,6));
string query = "Insert Into orderproduct(idorder, idproduct, aantal) Values('" + orderid + "'" + productid +
"'" + aantal + "')";
var cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
}

How to make my id declaration global or getting it from other method?

Hello Everyone, I have this code :
I declared this global :
FlowLayoutPanel PresPanel = new FlowLayoutPanel();
My InitPanel :
Label PresLabel = new Label();
PresLabel.Text = "PRESIDENT :";
PresLabel.AutoSize = true;
PresLabel.Location = new Point(30, 20);
PresLabel.Font = new Font(this.Font, FontStyle.Bold);
PresLabel.Font = new Font("Courier New", 18);
PresLabel.ForeColor = Color.Orange;
this.Controls.Add(PresLabel);
PresPanel.Size = new Size(630, 160);
PresPanel.Location = new Point(50, 50);
PresPanel.FlowDirection = FlowDirection.LeftToRight;
PresPanel.BorderStyle = BorderStyle.FixedSingle;
PresPanel.AutoScroll = true;
PresPanel.WrapContents = false;
Controls.Add(PresPanel);
Form_load :
InitPanel();
PresPanel.SuspendLayout();
BtnVote.CenterHorizontally();
try
{
string cmdText = "SELECT (FirstName + ' ' + MiddleName + ' ' + LastName) as FullName, " +
"imgPath as ImagePath, " + "id as GetID FROM TableVote WHERE Position='President'";
using (SqlCommand com = new SqlCommand(cmdText, sc))
{
if (sc.State != ConnectionState.Open) sc.Open();
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
AddRadioButton(reader.GetString(0), reader.GetString(1), reader.GetInt32(2));
}
reader.Close();
sc.Close();
PresPanel.ResumeLayout(true);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
My AddRadioButton :
public void AddRadioButton(string fullName, string imagePath, int getID)
{
RadioButton radio = new RadioButton { Text = fullName, Parent = PresPanel };
radio.AutoSize = false;
radio.Size = new Size(150, 130);
radio.Image = new Bitmap(Image.FromFile(imagePath), 90, 90);
radio.TextImageRelation = TextImageRelation.ImageAboveText;
radio.CheckAlign = ContentAlignment.BottomCenter;
radio.CheckAlign = ContentAlignment.BottomCenter;
radio.ImageAlign = ContentAlignment.MiddleCenter;
radio.TextAlign = ContentAlignment.MiddleCenter;
radio.ForeColor = Color.LimeGreen;
radio.CheckedChanged += radio_CheckedChanged;
}
Now for my question, How do I get my getID from AddradioButton whenever i click each radiobutton? Thanks.. :)
You can use the Tag property:
public void AddRadioButton(string fullName, string imagePath, int getID)
{
RadioButton radio = new RadioButton { Text = fullName, Parent = PresPanel };
//.....
radio.Tag = getID;
radio.CheckedChanged += radio_CheckedChanged;
}
//then in the CheckedChanged event handler
private void radio_CheckedChanged(object sender, EventArgs e){
RadioButton radio = sender as RadioButton;
int getID = (int) (radio.Tag ?? -1);//suppose -1 is an invalid ID which is used to indicate that there is not associated ID
//other code....
}

Resize image before storing it into a folder in asp.net c#

I want to resize Profile picture before storing it into a folder in asp.net .What will be technique to resize it ?? Here is my code for image upload.
Any help will be appreciated..Thanks!
protected void btnUpload_Click(object sender, EventArgs e)
{
StartUpLoad();
}
private void StartUpLoad()
{
//get the file name of the posted image
string imgName = fileuploadImage.FileName.ToString();
//sets the image path
string imgPath = "ImageStorage/" + imgName;
fileuploadImage.SaveAs(Server.MapPath(imgPath));
//get the size in bytes that
int imgSize = fileuploadImage.PostedFile.ContentLength;
//validates the posted file before saving
if (fileuploadImage.PostedFile != null && fileuploadImage.PostedFile.FileName != "")
{
if (fileuploadImage.PostedFile.ContentLength > 102400)
{
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('File is too big')", true);
}
else
{
//save the file
//Call the method to execute Insertion of data to the Database
ExecuteInsert(imgName, imgSize, imgPath);
Response.Write("Save Successfully!");
}
}
}
private string GetConnectionString()
{
//sets the connection string from your web config file. "DBConnection" is the name of your Connection String
return System.Configuration.ConfigurationManager.ConnectionStrings["ParkingProjectConnectionString"].ConnectionString;
}
private void ExecuteInsert(string name, int size, string path)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
string sql = "INSERT INTO ImageInfo (ImageName, ImageSize, ImagePath) VALUES "
+ " (#imgName,#imgSize,#imgPath)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[3];
param[0] = new SqlParameter("#imgName", SqlDbType.NVarChar, 50);
param[1] = new SqlParameter("#imgSize", SqlDbType.BigInt, 9999);
param[2] = new SqlParameter("#imgPath", SqlDbType.VarChar, 50);
param[0].Value = name;
param[1].Value = size;
param[2].Value = path;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
This Code works for me.
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Test/") + "test.jpg");
string pth = Server.MapPath("~/Test/test.jpg");
resizeImageAndSave(pth);
}
}
private string resizeImageAndSave(string imagePath)
{
System.Drawing.Image fullSizeImg
= System.Drawing.Image.FromFile(imagePath);
var thumbnailImg = new Bitmap(150, 130);
var thumbGraph = Graphics.FromImage(thumbnailImg);
thumbGraph.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
thumbGraph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
thumbGraph.InterpolationMode =System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, 150, 130);
thumbGraph.DrawImage(fullSizeImg, imageRectangle);
string targetPath = imagePath.Replace(Path.GetFileNameWithoutExtension(imagePath), Path.GetFileNameWithoutExtension(imagePath) + "-resize");
thumbnailImg.Save(targetPath, System.Drawing.Imaging.ImageFormat.Jpeg); //(A generic error occurred in GDI+) Error occur here !
thumbnailImg.Dispose();
return targetPath;
}
Try this code:
private Image resizeImageAndSave(string imagePath)
{
Size wantedSize = new Size(250, 180);
Image fullImg = Image.FromFile(imagePath);
Bitmap resizedImg = new Bitmap(fullImg, wantedSize);
return (Image)resizedImg;
}

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