Displaying file names of an image - c#

So I want to display the file name of an image in a label in form 2, form 1 is where I'm going to select the picture and then it'll place it into form 2, but i want it to display the filename of the image that has been selected in the label called 'FileNameLabel' into form 2. This meaning the file location
If you have any more questions, feel free to ask.

This should display the filename.
if (SelectMedia.ShowDialog() == DialogResult.OK)
{
if (SelectMedia.FilterIndex == 1)
{
PictureViewer picture = new PictureViewer();
picture.SetPicture(SelectMedia.FileName);
FileNameLabel.Text = SelectMedia.FileName;
picture.Show();
}
}
Your SetPicture method takes the filename to put the picture into the picture box.
That is the same filename that will get displayed in your FileNameLabel.
If you are asking to display the full filepath then you need to do this.
if (SelectMedia.ShowDialog() == DialogResult.OK)
{
if (SelectMedia.FilterIndex == 1)
{
PictureViewer picture = new PictureViewer();
picture.SetPicture(SelectMedia.FileName);
FileInfo path = new FileInfo(SelectMedia.FileName);
FileNameLabel.Text = path;
picture.Show();
}
}
If those aren't what you are after explain a lot better about what you are trying to do.

Related

How do I get the Bitmap name when I click the image in datagridview?

I am trying to click on an image in a datagridview and then write its image/file name into a textbox so I can access this from elsewhere.
First I try just a small app to make sure I can make it all work. A Dialog contains the dataviewgrid and I put a bitmap into it as below:
public ChooseFormat()
{
InitializeComponent();
dataGridView1[0,0].Value = new Bitmap(#"C:\a\eggs\grid_app\grid_app\bin\Debug\graphics\1L5HQ60.bmp");
}
Now I click on the image but all the things I have tried I cannot get hold of the file name. The closest I get is below but this returns "System.Drawing.Bitmap" and not the file name. I am sure this must just be a tweak here to make it work but I have tried teh few things I know and nothing is working.
void DataGridView1CellContentClick(object sender, DataGridViewCellEventArgs e)
{
txtbx_choice.Text = dataGridView1[0,0].Value.ToString();
}
Drilling into the cells's data in the debugger doesn't bring up any info on the source of it. Maybe I have overlooked something..
One simple solution is to store the filename in the cell's Tag property:
string fileName = #"C:\a\eggs\grid_app\grid_app\bin\Debug\graphics\1L5HQ60.bmp";
dataGridView1[0,0].Value = new Bitmap(fileName );
dataGridView1[0,0].Tag = fileName ;
Now you can always access it:
string displayedFile = dataGridView1[0, someRow].Tag.ToString();
I have placed a Picture Box on the same form and this how I am displaying the ImageColumn's data (an Image ) in picture box
pictureBox1.Image = (Image)dataGridView1[0, 0].Value;

C# : List image reset after close app

I'm using VS2013 to develop an windows form application with SQL Server database.
I have a column in database table to store the image name :
In my application, I creat a button to select image from my computer and save that's image to application startup path :
private void buttonX1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Image only. | *.jpg; *.jpeg; *png; *.gif;";
dlg.InitialDirectory = #"E:\";
dlg.Multiselect = false;
string a = null;
if (dlg.ShowDialog() == DialogResult.OK)
{
string[] tmp = dlg.FileNames;
foreach (string i in tmp)
{
FileInfo fi = new FileInfo(i);
string[] xxx = i.Split('\\');
string des = Application.StartupPath + #"\Images\" + xxx[xxx.Length - 1];
string desfolder = Application.StartupPath + #"\Images\";
imagename = xxx[xxx.Length - 1].ToString();
System.IO.Directory.CreateDirectory(desfolder);
File.Delete(des);
imageuploaded.Image = Image.FromFile(dlg.FileName);
//over.
fi.CopyTo(des);
imageList1.Images.Add(imagename, Image.FromFile(des));
//Process.Start("explorer.exe", desfolder);
}
MessageBox.Show("Thành công ");
}
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
That code will load the image from computer, save to folder "images" in startup path and add image to imagelist1, too.
After that, I have a button to insert imagename to "Images" column (in SQL server database).
I have this code to use imagelist for my grid :
public PrdMan()
{
InitializeComponent();
GridPanel panel = superGridControl1.PrimaryGrid;
GridColumn column = panel.Columns["image"];
column.EditorType = typeof(MyGridImageEditControl);
column.EditorParams = new object[] { imageList1, ImageSizeMode.Zoom };
//superGridControl1.PrimaryGrid.Columns[8].Visible = false;
//superGridControl1.PrimaryGrid.Columns[2].CellStyles = "dd/MM/yyyy";
//styleManager1.ManagerStyle = eStyle.Metro;
//
//this.Location = new Point(0, 0);
//this.Size = Screen.PrimaryScreen.WorkingArea.Size;
}
And code to load grid :
this.mPhamTableAdapter.Fill(this.beautyMaDataSet.MPham);
this.superGridControl1.PrimaryGrid.DataSource = this.beautyMaDataSet.MPham;
My problem is : When I load image, and insert it into database's "Images" columns : It's success and grid will display image. But When I close app (after published) or stop debug (in VS) then re-open ( or debug again). The grid will not display my image
even though the image was still in folder :
And imagelist have no image in list :
I don't know what is my problem. Can you support me how to :
1/ Add image from PC to startup path's folder using C# and save image name to SQL server (to bind image to grid).
2/ Bind image from startup path's folder to imagelist and use it.
Thanks for support.
I sense two problems in your code, maybe some of them cause your problem.
First, if you load a table to a DataGridView (or something else), and update the GridView with your new image, but not write back to the database manually, the modification will not save to database.
As you said,
After that, I have a button to insert imagename to "Images" column (in SQL server database). I have this code to use imagelist for my grid
I guess one reason of your problem may relative to here.
Second, you used a dialog to select an image and copy to path "APP\Images", and store name to database. How will you do when the user run you application next time? Load the table and get image names, and find those images from the path?
Please provide the relative codes to solve your problem.
BTW, if the database is local, off-line DB, and also you won't store too many records, you may consider store your image raw-data in DB, too. (I know some people do not recommend this way, but in my opinion, it's one way to solve your problem too.)

How to detect whether pictureBox successfully displayed the image or not?

I have a pictureBox that loads an image directly from the internet. The image can change dynamically and is specified by the user in a textBox that has a TextChanged event that changes the image in pictureBox to the URL in the textBox. When user clicks the submit button, the image URL is saved in the database. But before saving I want to validate the image, that whether the image displayed successfully or the error image is displayed in place of it. So how can I validate this?
You can use the LoadComplete event to see when it has changed, and if the eventArg's error is null (successful) or not null (fail).
void pictureBox1_LoadCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
MessageBox.Show(e.Error.ToString());
}
this.pictureBox1.Validated += new EventHandler(pictureBox1_Validated);
this.pictureBox1.ImageLocation = this.textBox1.Text;
-
Edit: Just saw Dips' comment, did not use that link but is same means to answer this.
Place the code below in the function where you are retrieving the path of image from textBox ,be sure to place it before you do anything else on that path;
string path = "Path to image";
Bitmap bmp;//To validate the Image.
try
{
bmp = new Bitmap(path);//Create a Bitmap object from the given path.
if (bmp != null)
{
pictureBox1.Load(path);//Display the image to the user.
//Now it's safe to store the image path in the database,
//because we have validated it.
bmp.Dispose();//Dispose the Bitmap object to free occupied resources.
//Place you database related code here which uses the path we just validated.
}
}
catch (ArgumentException)
{
MessageBox.Show("The specified image file is invalid.");
//Show error image in PictureBox.
//(pictureBox1.Image="Path to error image").
//Don't store image path,its invalid.
}
catch (FileNotFoundException)
{
MessageBox.Show("The path to image is invalid.");
//Show error image in PictureBox.
//(pictureBox1.Image="Path to error image").
//Don't store image path,its invalid.
}
When you've done this you can place your code where I've shown the comment //Place your database....This ensures that the file path and image is validated before anything else uses them.`This method also checks if the image file is actually an image and not a .txt or .exe with its extension changed to .jpg or any other image format,as you've mentioned in your comments you need to check if the path actually points to an image file.
You can the extend the exception handling mechanism if you need something more than displaying a MessageBox with error information.One more thing that is worth to be mentioned is that,before you display any image or do anything you will have to check if the url is valid one,to simplify this step you can try to download the file(it can be anything - an image,an executable,a text file or at least a web page,when it has been downloaded pass the path to that file(relative to filesystem) to this function.
Hope it works for you.
Suppose Pic1 is name of your control. To validate then you can use simply,
if(pic1.ImageLocation.Trim().Length>4) // > 4 since a shortest valid image
file will be a.png or something
similar; length= 5
{
if(validExtensions(pic1.ImageLocation)
{
//then put the path to database
}
}
Updated
//Mehod to valid image extensions
private bool validExtensions(string url)
{
var imgs = new []{".jpg",".gif",".png",".bmp",".jpeg"};
var ext = System.IO.Path.GetFileExtention(url); // see the correct method
in intellisense
if(imgs.Contains(ext)
return false;
}
Update 2
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";
dialog.InitialDirectory = #"C:\";
dialog.Title = "Please select an image file to encrypt.";
if (dialog.ShowDialog() == DialogResult.OK)
{
//Encrypt the selected file. I'll do this later. :)
}

Multi-line textbox shows mult-line string as One-Line

I am making a program where you enter an item's name and it's description. Then you add it to a listbox and after you are done you can save all the items to a 'txt' file. (Using StreamWriter). This program also has an edit button that allows you to edit the description in the listbox by removing it first from the listbox and then showing it back in the textbox (, so you can edit it)
If the description is multi-line, it will successfuly show it multi-line when I select it in the listbox and click the edit button that will show it back in the textbox. BUT if I save all the items in the listbox to a file first. And then open up the file again so it load the items back into the listbox. And then clicking the edit button...
The multi-line description will show as a one-line description in the textbox.
I am not sure why - but I've also made a label that will show the exact string that the textbox is suppose to show and the label is showing it multi-lined while textbox isn't!
The string is definitely multi-line but the multi-line textbox is showing it one-line after loading the items back into the listbox using StreamReader.
Example of the multi-line string: (named "theString1")
This is line 1
This is line 2
Using the following code: TextBox1.Text = theString1; this appears in the text box:
This is line1This is line2
But if I use the same code with a label. It will show it correctly.
If someone can explain to me why this is happening I will be more than happy. I just need an explanation.
Thanks in advance.
---[More info]---
Just so you know. I came up with this code myself so it is probably set-up all wrong.
I will be happy if you tell me a better way to do this.
I am using a list to store the description text + the item name. I seperated these two using '`' .And splited the string (see code).
This is the code that happens when you click the edit button. It removes the item from
the listbox and shows it in the textbox so you can edit it and add to listbox again:
int index = listBox.SelectedIndex;
itemName.Text = listBox.SelectedItem.ToString();
var descVar = descList.ElementAt(index).Split('`');
string theString1 = descVar[1];
TextBox1.Text = theString1;
This is how it saves it to a file:
FileDialog save = new SaveFileDialog();
save.Title = "Save information...";
save.DefaultExt = "Text File|*.txt";
save.Filter = "Text File|*.txt";
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(save.FileName);
foreach (string s in listBox.Items) //This writes the names of item names.
{
sw.WriteLine(s);
}
sw.WriteLine("`1`"); //I use this to seperate the item names from description.
foreach (string s in descList) //This writes the descriptions that are stored in a list named "descList".
{
sw.WriteLine(s);
sw.WriteLine("``"); //I use this to seperate descriptions from each other because they are multi-line.
}
sw.WriteLine("`2`"); //Just something so I know where it ends. :D
sw.Close();
}
else
{
}
And this is how it loads: (This can definitely be better!)
FileDialog load = new OpenFileDialog();
load.Title = "Load information...";
load.DefaultExt = "Text File|*.txt";
load.Filter = "Text File|*.txt";
if (load.ShowDialog() == DialogResult.OK)
{
List<string> loadDesc = new List<string>(); //Don't ask you will see why
descList.Clear();
while (listBox.Items.Count > 0) //This removes all items in the listbox to load new ones.
{
int index = 0;
listBox.Items.RemoveAt(index);
descList.Clear();
itemName.Text = "";
}
StreamReader rw = new StreamReader(load.FileName);
for (; true; )
{
string read = rw.ReadLine();
if (read == "`1`") //When it reaches the separator I made it stops reading.
{
break;
}
else
{
listBox.Items.Add(read);
}
}
for (; true; )
{
string read = rw.ReadLine();
if (read == "`2`")
{
break;
}
else
{
loadDesc.Clear();
loadDesc.Add(read);
for (; true; ) //Please tell me if this can be done differently.
{
string read2 = rw.ReadLine();
if (read2 != "``") //This will keep reading the whole description until it reaches the separator.
{
loadDesc.Add(read2); //Adds each line into the list I created.
}
else
{
break;
}
}
string oneBigString = string.Join("\n", loadDesc); //This basically converts all strings in a list into one string.
descList.Add(oneBigString); //And this finally add the string to the main list from where it then loads.
}
}
}
else
{
}
I believe that is it.
If there is anything else you need - tell me.
string oneBigString = string.Join("\n", loadDesc); is where the issue is.
Use Environment.NewLine instead of \n
I'm also just going to go over a couple of things that could be improved with your code (there are a lot, but I just want to cover a couple).
while (listBox.Items.Count > 0) //This removes all items in the listbox to load new ones.
You don't need to iterate over every element in the listbox to remove it. You can just do listBox.clear()
Also, using break to get out of loops is generally bad practice. This should be written as...
for (; true; )
{
string read = rw.ReadLine();
if (read == "`1`") //When it reaches the separator I made it stops reading.
{
break;
}
else
{
listBox.Items.Add(read);
}
}
this
string read = rw.ReadLine()
while(read != "`1`")
{
listBox.Items.Add(read);
read = rw.ReadLine()
}
but theres more, what if 1 is never found in the file? It would crash your program, so you also need to check if there is more data to be read...
string read = rw.ReadLine()
while(read != "`1`" && !sw.EndOfStream) // Make sure you're not at the end of the file
{
listBox.Items.Add(read);
read = rw.ReadLine()
}

How to split an image into 9 pieces and place in a canvas randomly?

I am trying to select an image and split it into 9 pieces and place randomly in a canvas. I am at the point where I have selected an image, but I am unsure of how to split the image.
I have looked at similar questions but no luck. I'm not looking for someone else to do the work, but advice on how best to do it.
private void uploadImage_Click(object sender, RoutedEventArgs e)
{
//creates (but not yet displays) a OpenFile dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
//specifies the look of the open file dialog box
dlg.DefaultExt = ".jpg";
dlg.Filter = "Image Files|*.jpg;";
dlg.InitialDirectory = Environment.CurrentDirectory;
//shows the open file dialog box to user and awaits OK or Cancel
bool? result = dlg.ShowDialog();
//result is true if user selects an image file
if (result == true)
{
filename = dlg.FileName;
var uri = new Uri(filename);
var bitmap = new BitmapImage(uri);
Image bg = new Image();
bg.Source = new BitmapImage(uri);
}
else
return;
}
I have already answered similiar question. Either use my solution, or resort to CroppedBitmap.
How to crop image and save into ImageSource in WPF?

Categories