Running Two Cameras Simultaneously using Emgu CV C# - c#

I have two IP cameras. I want to run both of them simultaneously. I am using Emgu CV to process images. So here, when I click Start button, my program will check which my cameras are active (get their IP addresses). After getting their IP addresses, my program will use those IPs to get data from database. The condition that I get, my program will be very slow and there is delay for several seconds when capture process is running. Can anyone help me what I must do to solve this problem ? Here what I have done
private void Tombol_Start_Click(object sender, EventArgs e)
{
ProsesSemuaKamera();
}
private void ProsesSemuaKamera()
{
Ping ping = new Ping();
PingReply pingreply;
OleDbConnection kon = new OleDbConnection(koneksi);
OleDbCommand command = kon.CreateCommand();
kon.Open();
string selecturl = "select * from datakamera";
command.CommandText = selecturl;
OleDbDataReader bacadata = command.ExecuteReader();
while (bacadata.Read())
{
int counturl = 0;
pingreply = ping.Send(bacadata["ipadd"].ToString());
if (pingreply.Status == IPStatus.Success)
{
listBox1.Items.Add(bacadata["namakamera"].ToString());
CaptureSemuaKamera = new Capture(bacadata["urlkamera"].ToString());
Application.Idle += new EventHandler(ProcessFrameSemuaKamera);
}
else if (pingreply.Status != IPStatus.Success)
{
textBox3.Text += bacadata["namakamera"].ToString() + Environment.NewLine;
}
}
kon.Close();
}
private void ProcessFrameSemuaKamera(object sender, EventArgs e)
{
Image<Bgr, Byte> sourceImage = CaptureSemuaKamera.QueryFrame();
SourceBox.Image = sourceImage.Bitmap;
ProsesKameraSemua();
}
private string BuildWhereClause(ListBox lb)
{
string WHEREclause = string.Empty;
foreach (string itm in lb.Items)
{
if (WHEREclause == string.Empty)
{
WHEREclause += " where namakamera = '" + itm + "' ";
}
else
{
WHEREclause += " OR namakamera = '" + itm + "' ";
}
}
return WHEREclause;
}
private void ProsesKameraSemua()
{
Image<Bgr, Byte> sourceImage = CaptureSemuaKamera.QueryFrame();
SourceBox.Image = sourceImage.Bitmap;
OleDbConnection kon = new OleDbConnection(koneksi);
OleDbCommand commandkoord = kon.CreateCommand();
OleDbCommand commandkoordgaris = kon.CreateCommand();
kon.Open();
string selectsemuakoord = "select * from koordinatkotak " + BuildWhereClause(listBox1);
string selectsemuakoordgaris = "select * from koordinatgaris " + BuildWhereClause(listBox1);
commandkoord.CommandText = selectsemuakoord;
commandkoordgaris.CommandText = selectsemuakoordgaris;
OleDbDataReader bacakoord = commandkoord.ExecuteReader();
OleDbDataReader bacakoordgaris = commandkoordgaris.ExecuteReader();
while (bacakoord.Read() && bacakoordgaris.Read())
{
#region Perspective projection
PointF[] srcs = new PointF[4];
srcs[0] = new PointF(int.Parse(bacakoord["x1source"].ToString()), int.Parse(bacakoord["y1source"].ToString())); //119, 187
srcs[1] = new PointF(int.Parse(bacakoord["x2source"].ToString()), int.Parse(bacakoord["y2source"].ToString())); //242, 181
srcs[2] = new PointF(int.Parse(bacakoord["x3source"].ToString()), int.Parse(bacakoord["y3source"].ToString())); //253, 225
srcs[3] = new PointF(int.Parse(bacakoord["x4source"].ToString()), int.Parse(bacakoord["y4source"].ToString())); //112, 231
PointF[] dsts = new PointF[4];
dsts[0] = new PointF(int.Parse(bacakoord["x1proj"].ToString()), int.Parse(bacakoord["y1proj"].ToString()));
dsts[1] = new PointF(int.Parse(bacakoord["x2proj"].ToString()), int.Parse(bacakoord["y2proj"].ToString()));
dsts[2] = new PointF(int.Parse(bacakoord["x3proj"].ToString()), int.Parse(bacakoord["y3proj"].ToString()));
dsts[3] = new PointF(int.Parse(bacakoord["x4proj"].ToString()), int.Parse(bacakoord["y4proj"].ToString()));
HomographyMatrix mywarpmat = CameraCalibration.GetPerspectiveTransform(srcs, dsts);
Image<Bgr, Byte> newImage = sourceImage.WarpPerspective(mywarpmat, 355, 288, Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR, Emgu.CV.CvEnum.WARP.CV_WARP_FILL_OUTLIERS, new Bgr(0, 0, 0));
Image<Gray, Byte> newImageGray = newImage.Convert<Gray, Byte>();
Image<Bgr, Byte> imageToShow = newImage.Copy();
Image<Bgr, Byte> imageToShowGaris = newImage.Copy();
ProjectionBox.Image = newImage.Bitmap;
#endregion
}
}

Related

Facial Recognition Using c# & EMGU CV Accuracy Problem

I have project code to create a face recognition system using EMGUCV. I have trained the database with 2 people. When the webcam detects those people and able to show the name correctly but the problem is the third person whose do not exist in trained database detect by webcam, it will take the nearest face and display the name on it instead of show "Unknown". How can I improve the accuracy? I have tried to change the threshold value but didn't help. What's going wrong?
MCvFont font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_TRIPLEX, 0.6d, 0.6d);
HaarCascade faceDetected;
Image<Bgr, Byte> Frame;
Capture camera;
Image<Gray, byte> result;
Image<Gray, byte> TrainedFace = null;
Image<Gray, byte> grayFace = null;
List<Image<Gray, byte>> trainingImages = new List<Image<Gray, byte>>();
List<string> labels = new List<string>();
List<string> Users = new List<string>();
EigenObjectRecognizer recognizer;
int Count, NumLabels, t;
string name, names = null;
public Form1()
{
InitializeComponent();
PhotoPers.Image = Properties.Resources.EmptyPiC;
//HaarCascade is for face detection
faceDetected = new HaarCascade("haarcascade_frontalface_default.xml");
try
{
string Labelsinfo = File.ReadAllText(Application.StartupPath + "/Faces/Faces.txt");
string[] Labels = Labelsinfo.Split(',');
NumLabels = Convert.ToInt16(Labels[0]);
Count = NumLabels;
string LoadFaces;
// if (result)
// {
// CvInvoke.cvPutText(Frame, name[result.Labels], new Point(face.X - 2, face.Y - 2),
// FontFace.HersheyComplex, 1.0, new Bgr(Color.Orange).MCvScalar);
// CvInvoke.cvRectangle(Frame, face, new Bgr(Color.Green).MCvScalar, 2);
//}
for (int tf = 1; tf < NumLabels + 1; tf++)
{
LoadFaces = "face" + tf + ".bmp";
trainingImages.Add(new Image<Gray, byte>(Application.StartupPath + "/Faces/" + LoadFaces));
labels.Add(Labels[tf]);
}
}
catch (Exception e)
{
}
}
string imgLocation = " ";
private void button1_Click(object sender, EventArgs e)
{
camera = new Capture();
camera.QueryFrame();
Application.Idle += new EventHandler(FrameProcedure);
}
private void BtnSave_Click(object sender, EventArgs e)
{
byte[] images = null;
FileStream Streem = new FileStream(imgLocation, FileMode.Open, FileAccess.Read);
BinaryReader brs = new BinaryReader(Streem);
images = brs.ReadBytes((int)Streem.Length);
if (txtName.Text == "" || txtLName.Text == " " || txtIDNo.Text == " " || cboDepartment.Text == " ")
{
MessageBox.Show("All fields must be fillup!");
}
else
{
Count = Count + 1;
grayFace = camera.QueryGrayFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
MCvAvgComp[][] DetectedFaces = grayFace.DetectHaarCascade(faceDetected, 1.2, 10, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));
foreach (MCvAvgComp f in DetectedFaces[0])
{
TrainedFace = Frame.Copy(f.rect).Convert<Gray, byte>();
break;
}
TrainedFace = result.Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
trainingImages.Add(TrainedFace);
labels.Add(txtName.Text);
File.WriteAllText(Application.StartupPath + "/Faces/Faces.txt", trainingImages.ToArray().Length.ToString() + ",");
for (int i = 1; i < trainingImages.ToArray().Length + 1; i++)
{
trainingImages.ToArray()[i - 1].Save(Application.StartupPath + "/Faces/face" + i + ".bmp");
File.AppendAllText(Application.StartupPath + "/Faces/Faces.txt", labels.ToArray()[i - 1] + ",");
}
}
mCon.ConOpen();
string SaveStr = "INSERT INTO tblRegister (FirstName, LastName, IDno, Department, Image)" +
"VALUES(#FirstName, #LastName, #IDno, #Department, #Image)";
SqlCommand myCommand = new SqlCommand(SaveStr, mCon.myCon);
myCommand.Parameters.AddWithValue("#FirstName", txtName.Text);
myCommand.Parameters.AddWithValue("#LastName", txtLName.Text);
myCommand.Parameters.AddWithValue("#IDno", txtIDNo.Text);
myCommand.Parameters.AddWithValue("#Department", cboDepartment.Text);
myCommand.Parameters.AddWithValue("#Image", images);
myCommand.ExecuteNonQuery();
mCon.ConClose();
MessageBox.Show("Data has been Save!");
txtName.Text = " ";
txtLName.Text = " ";
txtIDNo.Text = " ";
cboDepartment.Text = " ";
}
private void PhotoPers_Click(object sender, EventArgs e)
{
}
private void FrameProcedure(object sender, EventArgs e)
{
Users.Add("");
Frame = camera.QueryFrame().Resize(500, 300, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
grayFace = Frame.Convert<Gray, Byte>();
MCvAvgComp[][] facesDetectedNow = grayFace.DetectHaarCascade(faceDetected, 1.2, 10, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));
foreach (MCvAvgComp f in facesDetectedNow[0])
{
result = Frame.Copy(f.rect).Convert<Gray, Byte>().Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
Frame.Draw(f.rect, new Bgr(Color.Cyan), 3);
if (trainingImages.ToArray().Length != 0)
{
MCvTermCriteria termCriterias = new MCvTermCriteria(Count, 0.001);
EigenObjectRecognizer recognizer = new EigenObjectRecognizer(trainingImages.ToArray(), labels.ToArray(), 4500, ref termCriterias);
name = recognizer.Recognize(result);
Frame.Draw(string.IsNullOrEmpty(name) ? "UNKNOWN" : name, ref font, new Point(f.rect.X - 2, f.rect.Y - 2), new Bgr(Color.Red));
}
Users.Add("");
}
CameraBox.Image = Frame;
names = "";
Users.Clear();
}
private void TrainImagesFromDir()
{
//string path = Directory.GetCurrentDirectory() + "/Faces/Faces.txt";
//Users.Add("");
//Frame = camera.QueryFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
//grayFace = Frame.Convert<Gray, Byte>();
//MCvAvgComp[][] facesDetectedNow = grayFace.DetectHaarCascade(faceDetected, 1.2, 10, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));
//foreach (MCvAvgComp f in facesDetectedNow[1])
//{
// result = Frame.Copy(f.rect).Convert<Gray, Byte>().Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
// Frame.Draw(f.rect, new Bgr(Color.Green), 3);
// if (trainingImages.ToArray().Length != 0)
// {
// MCvTermCriteria termCriterias = new MCvTermCriteria(Count, 0.001);
// EigenObjectRecognizer recognizer = new EigenObjectRecognizer(trainingImages.ToArray(), labels.ToArray(), 1500, ref termCriterias);
// name = recognizer.Recognize(result);
// Frame.Draw(name, ref font, new Point(f.rect.X - 2, f.rect.Y - 2), new Bgr(Color.Red));
}
private void btnUpload_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "png files(*.png)|*.png|jpg files(*.jpg)|*.jpg|All files (*.*)|*.*";
if (dialog.ShowDialog() == DialogResult.OK)
{
imgLocation = dialog.FileName.ToString();
PhotoPers.ImageLocation = imgLocation;
}
}
}

I have been searching solution for this but still having error in my update query at the time of image upload

This is my update button click event:
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
if (ValidateAll())
{
SetValues();
_objHotel_EL.HotelID = HotelId;
_objHotel_EL.CommandName = "Update_HotelDetails";
int update = _objHotel_BL.Insert_Hotel(_objHotel_EL);
if (update > 0)
{
MessageBox.Show("Hotel Details Updated");
ClearAll();
}
else
{
MessageBox.Show("Already Exists");
ClearAll();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
here's my code which is used to set and upload image and other parameters:
private void SetValues()
{
_objHotel_EL.HotelName = txtHotelName.Text.Trim();
_objHotel_EL.PhoneNo = txtPhoneNo.Text.Trim();
_objHotel_EL.Address = txtAddress.Text.Trim();
_objHotel_EL.EmailId = txtEmailId.Text.Trim();
_objHotel_EL.WebSite = txtWebsite.Text.Trim();
_objHotel_EL.CurrID = CommanValue.CurrID;
if (flag == 1)
{
_objHotel_EL.BinaryImage = ReadFile(labelImagePath.Text);
_objHotel_EL.ImagePath = labelImagePath.Text;
}
else
{
if (imageData == null)
{
string path = System.AppDomain.CurrentDomain.BaseDirectory.Replace("\\Debug", "");
path = path.Replace("\\bin", "");
path = path.Replace("\\x86", "");
path = path + "Images\\NoImage1.png";
labelImagePath.Text = path;
imageData = ReadFile(labelImagePath.Text);
_objHotel_EL.ImagePath = path;
}
_objHotel_EL.ImagePath = labelImagePath.Text;
_objHotel_EL.BinaryImage = (byte[])imageData;
}
}
This is code of ReadFile:
private byte[] ReadFile(string strPath)
{
byte[] data = null;
FileInfo fInfo = new FileInfo(strPath);
long numBytes = fInfo.Length;
FileStream fstream = new FileStream(strPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
data = br.ReadBytes((int)numBytes);
return data;
}
Please help me out because its giving me an error The conversion is not supported. [ Type to convert from (if known) = nvarchar, Type to convert to (if known) = image ] while i am using sql server compact in visual studio 2012 using c#.
In database side datatype of image is image.
Actually I tried with myself after using SqlCeCommand parameters and its solved.
Here is the code.
if (objEL.CommandName == "Update_HotelDetails")
{
DataTable dt = SqlHelper.ExecuteDataset("SELECT HotelName, HotelID FROM Master_Hotel WHERE (HotelName = '" + objEL.HotelName + "') AND (HotelID <> '" + objEL.HotelID + "')").Tables[0];
if (dt.Rows.Count == 0)
{
string str = ("UPDATE Master_Hotel SET HotelName = #HotelName, PhoneNo = #PhoneNo, Address = #Address, EmailId = #EmailId, Website = #Website, Image = #Image,ImagePath = #ImagePath WHERE (HotelID = #HotelID)");
cmd = new SqlCeCommand(str, SqlHelper.objCon);
cmd.Parameters.Add("#HotelName", SqlDbType.NVarChar).Value = objEL.HotelName;
cmd.Parameters.Add("#PhoneNo", SqlDbType.NVarChar).Value = objEL.PhoneNo;
cmd.Parameters.Add("#Address", SqlDbType.NVarChar).Value = objEL.Address;
cmd.Parameters.Add("#EmailId", SqlDbType.NVarChar).Value = objEL.EmailId;
cmd.Parameters.Add("#Website", SqlDbType.NVarChar).Value = objEL.WebSite;
cmd.Parameters.Add("#Image", SqlDbType.Image).Value = objEL.BinaryImage;
cmd.Parameters.Add("#ImagePath", SqlDbType.NVarChar).Value = objEL.ImagePath;
cmd.Parameters.Add("#HotelID", SqlDbType.Int).Value = objEL.HotelID;
SqlHelper.objCon.Open();
i = cmd.ExecuteNonQuery();
SqlHelper.objCon.Close();
}
}

C# emgu saving an emgu captured image to a MySQL database

I am able to convert the emgu image format to a byte string and this does save on the MySQL database with this code, but the image is saved in a format not even recognized by windows image viewer
string myConnection = mydbconnection;
MySqlConnection myConn = new MySqlConnection(myConnection);
myConn.Open();
Bitmap image = trained.ToBitmap();
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] picture = ms.ToArray();
string formmattedPic = Convert.ToBase64String(picture);
MySqlCommand cmd = new MySqlCommand("INSERT INTO sql434250.facialid (timeanddate,photo1) VALUES(#named,#Trainedface)",myConn);
cmd.Parameters.Add("#named", MySqlDbType.VarChar).Value = named;
cmd.Parameters.Add("#Trainedface", MySqlDbType.Blob);
cmd.Parameters["#Trainedface"].Value = formmattedPic;
cmd.ExecuteNonQuery();
label4.Text = named.ToString();
myConn.Close();
}
My problem starts when I try to add the final image formatting I get a system not supported exception on the fs = new FileStream(named, FileMode.Open, FileAccess.Read); line, I am not sure how the filestream works, (new to C#) so please forgive me for any obvious mistakes in the code, for information I am on a windows 8 os, vs 2013
as here:
FileStream fs;
BinaryReader br;
byte[] ImageData;
**fs = new FileStream(named, FileMode.Open, FileAccess.Read);**
br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
MySqlCommand cmd = new MySqlCommand("INSERT INTO sql434250.facialid (timeanddate,photo1) VALUES(#named,#Trainedface)",myConn);
cmd.Parameters.Add("#named", MySqlDbType.VarChar).Value = named;
cmd.Parameters.Add("#Trainedface", MySqlDbType.Blob);
cmd.Parameters["#Trainedface"].Value = ImageData;
cmd.ExecuteNonQuery();
I am able to take converted images saved on my pc and manually download via the MySQL site the images these images do work with the software, so to my shame I know its a coding error.
added database table as follows:
CREATE TABLE `**yourdatabase**`.`facialid` (
`id` int( 11 ) NOT NULL AUTO_INCREMENT ,
`timeanddate` varchar( 30 ) NOT NULL ,
`photo1` longblob NOT NULL ,
`code1` varchar( 50 ) NOT NULL ,
`code2` varchar( 50 ) NOT NULL ,
`code3` varchar( 50 ) NOT NULL ,
PRIMARY KEY ( `id` )
added full form code
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.CvEnum;
using System.IO;
using System.Diagnostics;
using MySql.Data.MySqlClient;
using System.Drawing.Imaging;
namespace MultiFaceRec
{
public partial class FrmPrincipal : Form
{
//Declararation of all variables, vectors and haarcascades
Image<Bgr, Byte> currentFrame;
Capture grabber;
HaarCascade face;
HaarCascade eye;
MCvFont font = new MCvFont(FONT.CV_FONT_HERSHEY_TRIPLEX, 0.5d, 0.5d);
Image<Gray, byte> result, TrainedFace = null;
Image<Gray, byte> gray = null;
Image<Gray, byte> trained = null;
Image image1 = null;
List<Image<Gray, byte>> trainingImages = new List<Image<Gray, byte>>();
List<string> labels= new List<string>();
List<string> NamePersons = new List<string>();
int ContTrain, t;
string name, names = null;
public FrmPrincipal()
{
InitializeComponent();
//Load haarcascades for face detection
face = new HaarCascade("haarcascade_frontalface_default.xml");
//eye = new HaarCascade("haarcascade_eye.xml");
}
public void dbconnection()
{
grabber = new Capture();
grabber.QueryFrame();
//Initialize the FrameGraber event
Application.Idle += new EventHandler(FrameGrabber);
try
{
//Load of previus trainned faces and labels for each image
string myConnection = **"youdbconnection"**
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlDataAdapter myAdapter = new MySqlDataAdapter();
int totalrows = 0;
int rownumber = 0;
MySqlCommand SelectCommand = new MySqlCommand(" select * from **yourdb**.facialid ", myConn);
MySqlDataReader myReader;
myConn.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
string id = myReader.GetString("id");
string Labelsinfo = myReader.GetString("timeanddate");
string picdata = myReader.GetString("photo1");
string LoadFaces;
LoadFaces = myReader.GetString("photo1");
byte[] picData = myReader["photo1"] as byte[] ?? null;
ImageConverter pic = new ImageConverter();
Image img = (Image)pic.ConvertFrom(myReader["photo1"]);
Bitmap bitmap1 = new Bitmap(img);
trainingImages.Add(new Image<Gray, byte> (bitmap1));
labels.Add(Labelsinfo);
rownumber = count +1;
totalrows = count;
ContTrain = count;
//string userid = myReader.GetString("id");
//string useron = myReader.GetString("user");
}
myReader.Close();
myConn.Close();
label2.Text = totalrows.ToString();
}
catch(MySqlException ex)
{
//MessageBox.Show(e.ToString());
int errorcode = ex.Number;
MessageBox.Show("Nothing in binary database, please add at least a face(Simply train the prototype with the Add Face Button).", "Triained faces load", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void button2_Click(object sender, System.EventArgs e)
{
try
{
//Trained face counter
ContTrain = ContTrain + 1;
//Get a gray frame from capture device
gray = grabber.QueryGrayFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
//Face Detector
MCvAvgComp[][] facesDetected = gray.DetectHaarCascade(
face,
1.2,
10,
Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
new Size(20, 20));
//Action for each element detected
foreach (MCvAvgComp f in facesDetected[0])
{
trained = currentFrame.Copy(f.rect).Convert<Gray, byte>();
TrainedFace = currentFrame.Copy(f.rect).Convert<Gray, byte>();
break;
}
//resize face detected image for force to compare the same size with the
//test image with cubic interpolation type method
TrainedFace = result.Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
//string image;
//Show face added in gray scale
imageBox1.Image = TrainedFace;
string named = DateTime.Now.ToString("dd-MM-yy HH:mm:ss:ms");
string myConnection = **"your db connection"**
MySqlConnection myConn = new MySqlConnection(myConnection);
myConn.Open();
Bitmap image = trained.ToBitmap();
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] picture = ms.ToArray();
string formmattedPic = Convert.ToBase64String(picture);
FileStream fs;
BinaryReader br;
byte[] ImageData;
fs = new FileStream(named, FileMode.Open, FileAccess.Read);
br = new BinaryReader(fs);
ImageData = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
MySqlCommand cmd = new MySqlCommand("INSERT INTO **yourdb**.facialid (timeanddate,photo1) VALUES(#named,#Trainedface)",myConn);
cmd.Parameters.Add("#named", MySqlDbType.VarChar).Value = named;
cmd.Parameters.Add("#Trainedface", MySqlDbType.Blob);
cmd.Parameters["#Trainedface"].Value = ImageData;
cmd.ExecuteNonQuery();
label4.Text = named.ToString();
myConn.Close();
}
catch (MySqlException ee)
{
int errorcode = ee.Number;
}
}
void FrameGrabber(object sender, EventArgs e)
{
label3.Text = "0";
//label4.Text = "";
NamePersons.Add("");
//Get the current frame form capture device
currentFrame = grabber.QueryFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
//Convert it to Grayscale
gray = currentFrame.Convert<Gray, Byte>();
//Face Detector
MCvAvgComp[][] facesDetected = gray.DetectHaarCascade(
face,
1.2,
10,
Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
new Size(20, 20));
//Action for each element detected
foreach (MCvAvgComp f in facesDetected[0])
{
t = t + 1;
result = currentFrame.Copy(f.rect).Convert<Gray, byte>().Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
//draw the face detected in the 0th (gray) channel with blue color
currentFrame.Draw(f.rect, new Bgr(Color.Red), 2);
if (trainingImages.ToArray().Length != 0)
{
//TermCriteria for face recognition with numbers of trained images like maxIteration
MCvTermCriteria termCrit = new MCvTermCriteria(ContTrain, 0.001);
//Eigen face recognizer
EigenObjectRecognizer recognizer = new EigenObjectRecognizer(
trainingImages.ToArray(),
labels.ToArray(),
1000,
ref termCrit);
name = recognizer.Recognize(result);
//Draw the label for each face detected and recognized
currentFrame.Draw(name, ref font, new Point(f.rect.X - 2, f.rect.Y - 2), new Bgr(Color.LightGreen));
}
NamePersons[t-1] = name;
NamePersons.Add("");
//Set the number of faces detected on the scene
label3.Text = facesDetected[0].Length.ToString();
/*
//Set the region of interest on the faces
gray.ROI = f.rect;
MCvAvgComp[][] eyesDetected = gray.DetectHaarCascade(
eye,
1.1,
10,
Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
new Size(20, 20));
gray.ROI = Rectangle.Empty;
foreach (MCvAvgComp ey in eyesDetected[0])
{
Rectangle eyeRect = ey.rect;
eyeRect.Offset(f.rect.X, f.rect.Y);
currentFrame.Draw(eyeRect, new Bgr(Color.Blue), 2);
}
*/
}
t = 0;
//Names concatenation of persons recognized
for (int nnn = 0; nnn < facesDetected[0].Length; nnn++)
{
names = names + NamePersons[nnn] + ", ";
}
//Show the faces procesed and recognized
imageBoxFrameGrabber.Image = currentFrame;
//Clear the list(vector) of names
NamePersons.Clear();
}
private void FrmPrincipal_Load(object sender, EventArgs e)
{
dbconnection();
}
private void label3_Click(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
}
}
I was able to solve my question, I don't know what I did wrong but with a little copying here and there the following code works, what I have done is first stored the image to a local application file and used this file location in the file stream.
named = DateTime.Now.ToString("dd-MM-yy HH:mm:ss:ms");
TrainedFace.Save(Application.StartupPath + "/Temp/face1.bmp");
string dated = DateTime.Now.ToString("HH:mm:ss:ff dd-MM-yy");
label4.Text = dated;
//Show face added in gray scale
imageBox1.Image = TrainedFace;
trainingImages.Add(TrainedFace);
labels.Add(label4.Text);
byte[] imagepic = null;
FileStream fsstream = new FileStream(Application.StartupPath + "/Temp/face1.bmp", FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fsstream);
imagepic = br.ReadBytes((int)fsstream.Length);
string myConnection = "datasource=sql4.freemysqlhosting.net;port=3306;user=sql434250;password=lE3!lQ5*";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand("INSERT INTO `sql434250`.`facialid` (`id`, `timeanddate`, `photo1`) VALUES (NULL, #dated, #IMG);", myConn);
MySqlDataReader myReader;
myConn.Open();
SelectCommand.Parameters.Add(new MySqlParameter("#IMG", imagepic));
SelectCommand.Parameters.Add(new MySqlParameter("#dated", dated));
myReader = SelectCommand.ExecuteReader();
while (myReader.Read())
{
}

ArgumentOutOfRangeException was unhandled?

Here is my case: i can retrieved the data from the database, but when i run the program and filled up the Quantity column (on the third line), the error says: index was out of range. Anyone know why is this happen? (When i tried to fill the Quantity column (on third line), the error appeared) <-- shown in the picture below.
Here is the images of my program:
Here is the images of where the error is pointed:
Here is the full code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Windows.Forms;
namespace Sell_System
{
public partial class Form2 : Form
{
string connectionString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\Archives\Projects\Program\Sell System\Sell System\App_Data\db1.accdb;Persist Security Info=False;");
private Form1 firstForm;
private List<List<TextBox>> textBoxCodeContainer = new List<List<TextBox>>();
private List<List<TextBox>> textBoxQuantityContainer = new List<List<TextBox>>();
private List<List<TextBox>> textBoxDescContainer = new List<List<TextBox>>();
private List<List<TextBox>> textBoxSubTotalContainer = new List<List<TextBox>>();
private List<List<TextBox>> textBoxTotalContainer = new List<List<TextBox>>();
private List<List<TextBox>> textBoxAllTotalContainer = new List<List<TextBox>>();
public Form2()
{
InitializeComponent();
}
public Form2(Form1 firstForm)
: this()
{
this.firstForm = firstForm;
}
private void Form2_Load(object sender, EventArgs e)
{
UpdateTextPosition();
OleDbDataReader dReader;
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT [Code] FROM [Data]", conn);
dReader = cmd.ExecuteReader();
AutoCompleteStringCollection codesCollection = new AutoCompleteStringCollection();
while (dReader.Read())
{
string numString = dReader[0].ToString().PadLeft(4, '0');
codesCollection.Add(numString);
}
dReader.Close();
conn.Close();
if (firstForm.comboBox1.SelectedIndex == 0)
{
label1.Text = "Code:";
label1.Location = new Point(60, 125);
label2.Text = "Welcome to the Selling System.";
label2.Location = new Point(600, 0);
label3.Text = "Quantity:";
label3.Location = new Point(155, 125);
label4.Text = "Description:";
label4.Location = new Point(580, 125);
label5.Text = "Sub Total on Rp:";
label5.Location = new Point(1020, 125);
label6.Text = "Total on Rp:";
label6.Location = new Point(1210, 125);
label7.Text = "Total on Rp:";
label7.Location = new Point(1080, 580);
}
else if (firstForm.comboBox1.SelectedIndex == 1)
{
label1.Text = "Kode:";
label1.Location = new Point(60, 125);
label2.Text = "Selamat datang di Selling System.";
label2.Location = new Point(600, 0);
label3.Text = "Banyaknya:";
label3.Location = new Point(145, 125);
label4.Text = "Keterangan:";
label4.Location = new Point(580, 125);
label5.Text = "Sub Total di Rp:";
label5.Location = new Point(1020, 125);
label6.Text = "Total di Rp:";
label6.Location = new Point(1210, 125);
label7.Text = "Total di Rp:";
label7.Location = new Point(1080, 580);
}
//****TextBox for Code****
for (int y = 0; y <= 16; y++)
{
textBoxCodeContainer.Add(new List<TextBox>());
textBoxCodeContainer[0].Add(new TextBox());
textBoxCodeContainer[0][y].Size = new Size(100, 50);
textBoxCodeContainer[0][y].Location = new Point(25, 150 + (y * 25));
textBoxCodeContainer[0][y].TextChanged += new System.EventHandler(this.textBox_TextChanged);
textBoxCodeContainer[0][y].AutoCompleteMode = AutoCompleteMode.Suggest;
textBoxCodeContainer[0][y].AutoCompleteSource = AutoCompleteSource.CustomSource;
textBoxCodeContainer[0][y].AutoCompleteCustomSource = codesCollection;
Controls.Add(textBoxCodeContainer[0][y]);
}
//****TextBox for Quantity****
for (int y = 0; y <= 16; y++)
{
textBoxQuantityContainer.Add(new List<TextBox>());
textBoxQuantityContainer[0].Add(new TextBox());
textBoxQuantityContainer[0][y].Size = new Size(100, 50);
textBoxQuantityContainer[0][y].Location = new Point(125, 150 + (y * 25));
textBoxQuantityContainer[0][y].TextChanged += new System.EventHandler(this.textBox_TextChanged);
Controls.Add(textBoxQuantityContainer[0][y]);
}
//****TextBox for Description****
for (int y = 0; y <= 16; y++)
{
textBoxDescContainer.Add(new List<TextBox>());
textBoxDescContainer[0].Add(new TextBox());
textBoxDescContainer[0][y].Size = new Size(750, 50);
textBoxDescContainer[0][y].Location = new Point(225, 150 + (y * 25));
Controls.Add(textBoxDescContainer[0][y]);
}
//****TextBox for Sub Total****
for (int y = 0; y <= 16; y++)
{
textBoxSubTotalContainer.Add(new List<TextBox>());
textBoxSubTotalContainer[0].Add(new TextBox());
textBoxSubTotalContainer[0][y].Size = new Size(175, 50);
textBoxSubTotalContainer[0][y].Location = new Point(975, 150 + (y * 25));
Controls.Add(textBoxSubTotalContainer[0][y]);
}
//****TextBox for Total****
for (int y = 0; y <= 16; y++)
{
textBoxTotalContainer.Add(new List<TextBox>());
textBoxTotalContainer[0].Add(new TextBox());
textBoxTotalContainer[0][y].Size = new Size(175, 50);
textBoxTotalContainer[0][y].Location = new Point(1150, 150 + (y * 25));
textBoxTotalContainer[0][y].TextChanged += new System.EventHandler(this.textBox_TextChanged);
Controls.Add(textBoxTotalContainer[0][y]);
}
//****TextBox for Total All****
textBoxAllTotalContainer.Size = new Size(175, 50);
textBoxAllTotalContainer.Location = new Point(1150, 575);
textBoxAllTotalContainer.TextChanged += new System.EventHandler(this.textBox_TextChanged);
Controls.Add(textBoxAllTotalContainer);
}
private void UpdateTextPosition()
{
Graphics g = this.CreateGraphics();
Double startingPoint = (this.Width / 2) - (g.MeasureString(this.Text.Trim(), this.Font).Width / 2);
Double widthOfASpace = g.MeasureString(" ", this.Font).Width;
String tmp = " ";
Double tmpWidth = 0;
while ((tmpWidth + widthOfASpace) < startingPoint)
{
tmp += " ";
tmpWidth += widthOfASpace;
}
this.Text = tmp + this.Text.Trim();
}
private void UpdateDatas()
{
int codeValue = 0;
int index = 0;
string query = "SELECT [Description], [Price] FROM [Data] WHERE [Code] IN (";
OleDbDataReader dReader;
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
if (int.TryParse(this.textBoxCodeContainer[0][0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][1].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][2].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][3].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][4].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][5].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][6].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][7].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][8].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][9].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][10].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][11].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][12].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][13].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][14].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][15].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][16].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
query = query + ")";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxCodeContainer[0][index].TextLength != 0)
{
this.textBoxDescContainer[0][index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[0][index].Text = dReader["Price"].ToString();
}
index += 1;
}
dReader.Close();
conn.Close();
}
private void UpdatePrice()
{
if (textBoxQuantityContainer[0][0].Text == "")
{
textBoxTotalContainer[0][0].Text = "";
}
else if (textBoxQuantityContainer[0][0].Text == "1")
{
textBoxTotalContainer[0][0].Text = textBoxSubTotalContainer[0][0].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][0].Text;
}
if (textBoxQuantityContainer[0][1].Text == "")
{
textBoxTotalContainer[0][1].Text = "";
}
else if (textBoxQuantityContainer[0][1].Text == "1")
{
textBoxTotalContainer[0][1].Text = textBoxSubTotalContainer[0][1].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][1].Text;
}
if (textBoxQuantityContainer[0][2].Text == "")
{
textBoxTotalContainer[0][2].Text = "";
}
else if (textBoxQuantityContainer[0][2].Text == "1")
{
textBoxTotalContainer[0][2].Text = textBoxSubTotalContainer[0][2].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][2].Text;
}
if (textBoxQuantityContainer[0][3].Text == "")
{
textBoxTotalContainer[0][3].Text = "";
}
else if (textBoxQuantityContainer[0][3].Text == "1")
{
textBoxTotalContainer[0][3].Text = textBoxSubTotalContainer[0][3].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][3].Text;
}
if (textBoxQuantityContainer[0][4].Text == "")
{
textBoxTotalContainer[0][4].Text = "";
}
else if (textBoxQuantityContainer[0][4].Text == "1")
{
textBoxTotalContainer[0][4].Text = textBoxSubTotalContainer[0][4].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][4].Text;
}
if (textBoxQuantityContainer[0][5].Text == "")
{
textBoxTotalContainer[0][5].Text = "";
}
else if (textBoxQuantityContainer[0][5].Text == "1")
{
textBoxTotalContainer[0][5].Text = textBoxSubTotalContainer[0][5].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][5].Text;
}
if (textBoxQuantityContainer[0][6].Text == "")
{
textBoxTotalContainer[0][6].Text = "";
}
else if (textBoxQuantityContainer[0][6].Text == "1")
{
textBoxTotalContainer[0][6].Text = textBoxSubTotalContainer[0][6].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][6].Text;
}
if (textBoxQuantityContainer[0][7].Text == "")
{
textBoxTotalContainer[0][7].Text = "";
}
else if (textBoxQuantityContainer[0][7].Text == "1")
{
textBoxTotalContainer[0][7].Text = textBoxSubTotalContainer[0][7].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][7].Text;
}
if (textBoxQuantityContainer[0][8].Text == "")
{
textBoxTotalContainer[0][8].Text = "";
}
else if (textBoxQuantityContainer[0][8].Text == "1")
{
textBoxTotalContainer[0][8].Text = textBoxSubTotalContainer[0][8].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][8].Text;
}
if (textBoxQuantityContainer[0][9].Text == "")
{
textBoxTotalContainer[0][9].Text = "";
}
else if (textBoxQuantityContainer[0][9].Text == "1")
{
textBoxTotalContainer[0][9].Text = textBoxSubTotalContainer[0][9].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][9].Text;
}
if (textBoxQuantityContainer[0][10].Text == "")
{
textBoxTotalContainer[0][10].Text = "";
}
else if (textBoxQuantityContainer[0][10].Text == "1")
{
textBoxTotalContainer[0][10].Text = textBoxSubTotalContainer[0][10].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][10].Text;
}
if (textBoxQuantityContainer[0][11].Text == "")
{
textBoxTotalContainer[0][11].Text = "";
}
else if (textBoxQuantityContainer[0][11].Text == "1")
{
textBoxTotalContainer[0][11].Text = textBoxSubTotalContainer[0][11].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][11].Text;
}
if (textBoxQuantityContainer[0][12].Text == "")
{
textBoxTotalContainer[0][12].Text = "";
}
else if (textBoxQuantityContainer[0][12].Text == "1")
{
textBoxTotalContainer[0][12].Text = textBoxSubTotalContainer[0][12].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][12].Text;
}
if (textBoxQuantityContainer[0][13].Text == "")
{
textBoxTotalContainer[0][13].Text = "";
}
else if (textBoxQuantityContainer[0][13].Text == "1")
{
textBoxTotalContainer[0][13].Text = textBoxSubTotalContainer[0][13].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][13].Text;
}
if (textBoxQuantityContainer[0][14].Text == "")
{
textBoxTotalContainer[0][14].Text = "";
}
else if (textBoxQuantityContainer[0][14].Text == "1")
{
textBoxTotalContainer[0][14].Text = textBoxSubTotalContainer[0][14].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][14].Text;
}
if (textBoxQuantityContainer[0][15].Text == "")
{
textBoxTotalContainer[0][15].Text = "";
}
else if (textBoxQuantityContainer[0][15].Text == "1")
{
textBoxTotalContainer[0][15].Text = textBoxSubTotalContainer[0][15].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][15].Text;
}
if (textBoxQuantityContainer[0][16].Text == "")
{
textBoxTotalContainer[0][16].Text = "";
}
else if (textBoxQuantityContainer[0][16].Text == "1")
{
textBoxTotalContainer[0][16].Text = textBoxSubTotalContainer[0][16].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][16].Text;
}
}
private void textBox_TextChanged(object sender, EventArgs e)
{
UpdateDatas();
UpdatePrice();
}
}
}
Here is my problem: "i am confuse, when i try assign a value for "textBoxAllTotalContainer.Text = textBoxTotalContainer[0][0].Text", the code is working. but, when i tried "textBoxAllTotalContainer.Text = textBoxTotalContainer[0][one(1)]", the screen stucked in there (I have to stop debugging from Visual Studio)"
textBoxTotalContainer contains 17 textboxes, therefore, i used [0][0] to [0][16], and textBoxAllTotalContainer contains 1 textbox, so i just used textBoxAllTotalContainer.Text
Note: "Keyword (one), it suppose to be "1" <-- number, i wrote (one), because when i tried changed the [0][(Here supposed to be "1")], the text automatically changed to linked image"
Issue: **"When i tried the code
else if (textBoxQuantityContainer[0][0].Text == "1")
{
textBoxTotalContainer[0][0].Text = textBoxSubTotalContainer[0][0].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][0].Text;
}
the textbox for alltotalcontainer is on (Total on Rp, the textbox is on after words) in the image shown above, the textboxes for subtotal is on (Sub Total on Rp), the textboxes for totalcontainer is on (Total on Rp, the textboxes are on below words), the textboxes for quantitycontainer is on (Quantity). In code above, shown that textbox 1 on textboxtotalcontainer are same with the textbox 1 on subtotalcontainer, and alltotalcontainer is same with totalcontainer.**
But, below code it not working, and the screen stucked on there (the mouse dissappear and i cant do anything, unless i press SHIFT + F5 on Visual Studio):
else if (textBoxQuantityContainer[0][1].Text == "1")
{
textBoxTotalContainer[0][1].Text = textBoxSubTotalContainer[0][1].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][1].Text;
}
Thanks
You get that error when you try to access an element in a collection that doesn't exist.
For example, if you have a list of strings...
List<string> myList = new List {"one", "two", "three"};
...and try to access the fourth element with myList[3], you'll get that error.
Either textBoxAllTotalContainer[0][2] doesn't exist, or textBoxTotalContainer[0][2]. Can't tell from the error in your picture. Place a breakpoint on that line and check both objects.
Looks like your stop condition is wrong.
you have the following code for initializing textBoxAllTotalContainer:
//****TextBox for Total All****
for (int y = 0; y <= 1; y++)
{
textBoxAllTotalContainer.Add(new List<TextBox>());
textBoxAllTotalContainer[0].Add(new TextBox());
textBoxAllTotalContainer[0][y].Size = new Size(175, 50);
textBoxAllTotalContainer[0][y].Location = new Point(1150, 575);
textBoxAllTotalContainer[0][y].TextChanged += new System.EventHandler(this.textBox_TextChanged);
Controls.Add(textBoxAllTotalContainer[0][y]);
}
Note that the loop is itterating only twice.
Therefore textBoxAllTotalContainer[0][0] and textBoxAllTotalContainer[0][1] are created.
but when you try to access textBoxAllTotalContainer[0][2] you hit the exception because the location is really out of the list's range as the exception specifies.

ASP.NET fileupload doesn't work in server

I have a website project in local and connection with database which database in server. I can add photo and country which I work in local but I can't add which I load project to server
public void resim_ekle()
{
if (FileUpload1.HasFile)
{
try
{
string fileExtension = Path.GetExtension(FileUpload1.FileName).ToLower();
string fileName = Guid.NewGuid().ToString(); // şifreli isim
string fileName2 = Guid.NewGuid().ToString();
if (File.Exists(fileName + fileExtension))
fileName = Guid.NewGuid().ToString();
if (File.Exists(fileName2 + fileExtension))
fileName2 = Guid.NewGuid().ToString();
if (FileUpload1.FileContent == null)
return;
if (FileUpload1.FileContent.Length == 0)
return;
System.Drawing.Bitmap originalBMP = new System.Drawing.Bitmap(FileUpload1.FileContent);
int origWidth = 800;
int origHeight = 600;
int origWidth2 = 120;
int origHeight2 = 90;
double sgnRatio = Convert.ToDouble(origWidth) / Convert.ToDouble(origHeight);
double sgnRatio2 = Convert.ToDouble(origWidth2) / Convert.ToDouble(origHeight2);
System.Drawing.Bitmap newBMP = new System.Drawing.Bitmap(originalBMP, origWidth, origHeight);
System.Drawing.Bitmap newBMP2 = new System.Drawing.Bitmap(originalBMP, origWidth2, origHeight2);
System.Drawing.Graphics oGraphics = System.Drawing.Graphics.FromImage(newBMP);
System.Drawing.Graphics oGraphics2 = System.Drawing.Graphics.FromImage(newBMP2);
oGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
oGraphics2.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
oGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
oGraphics2.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
oGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
oGraphics2.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
oGraphics.DrawImage(originalBMP, 0, 0, origWidth, origHeight);
oGraphics2.DrawImage(originalBMP, 0, 0, origWidth2, origHeight2);
newBMP.Save(Server.MapPath("~/resimler/olkeler/" + fileName.ToString() + fileExtension));
newBMP2.Save(Server.MapPath("~/resimler/olkeler/kucuk/" + fileName2.ToString() + fileExtension));
olkeler ulke = new olkeler();
ulke.resim_buyuk = ("~/resimler/olkeler/" + fileName.ToString() + fileExtension).ToString();
ulke.resim_kucuk = ("~/resimler/olkeler/kucuk/" + fileName2.ToString() + fileExtension).ToString();
ulke.olke_adi = txtulke_adi.Text;
vt.insert_ulke(ulke);
label_Uyari.Text = "Resim Başarıyla Yüklendi...";
}
catch { label_Uyari.Text = "Resim Yükleme İşlemi Esnasında Bir Hata Oluştu. Lütfen Tekrar Deneyiniz..."; }
}
else { label_Uyari.Text = "Resim Seçilmemiş..."; }
}
This code run in my loclhost but doesn't work in server. FileUpload1 has no file in server
I think it's wrong with your
newBMP.Save(Server.MapPath("~/resimler/olkeler/" + fileName.ToString() + fileExtension));
I think you shall loose the ~
I write:
profilPic.SaveAs(Server.MapPath(#"images/people/") +
profilPic.FileName);
from here:
<asp:FileUpload ID="profilPic" runat="server" />

Categories

Resources