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. :)
}
Related
I am trying to make a file display. When the user selects a file, it displays the icon of the file in the window. When I select the Google Chrome icon and click on 'OK' in the openfiledialog, the intended result happens. (see pictures below)
However, when I select another icon (e.g Word), it gives me the error 'Path does not exist'.
(see pictures below)
If I select another file (e.g File Explorer) it gives me 'Catastrophic Error' (see pictures below)
For some reason, this problem only happens with shortcut files. For other files like .txt files or .exe files, this problem does not occur.
Here is my code (Add_Item is the name of the button)
private void AddItem_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == true)
{
foreach (String myfile in openFileDialog.FileNames)
{
// here myfile represent your selected file name
//get filename
string filename = System.IO.Path.GetFileName(myfile);
//TODO: Create settings
Icon icon1 = System.Drawing.Icon.ExtractAssociatedIcon(myfile);
Bitmap icon = icon1.ToBitmap();
System.Windows.Controls.Image image = new System.Windows.Controls.Image();
image.Source = BitmapToImageSource(icon);
Tiles.Children.Add(image);
}
}
}
Can anyone help me?
Thanks
Alright, {DeferenceLinks = false} fixed my problem.
I'm trying to do something when I click image displayed inside pictureBox1.
pictureBox is loaded with this code:
string imgpath = #"img\256.png";
pictureBox48.Image = Image.FromFile(imgpath);
Then control is released to me so I can see that the picture loaded correctly.
Then i click the picture:
public void pictureBox48_Click(object sender, EventArgs e)
{
string variable1 = pictureBox48.ImageLocation;
Form3 fo = new Form3(variable1);
fo.ShowDialog();
}
This doesn't work. When I debug the code I see that variable1 stay null, that is pictureBox48.ImageLocation is null. Why is that? Shouldn't it be the path to the image that is assigned there?
You can't get the image path when you set the image using the Image property because you are assigning an Image object which can come from different sources.
Set the image using ImageLocation.
string imgpath = #"img\256.png";
pictureBox48.ImageLocation = imgpath;
When you click in the PictureBox you can get the path using the same property:
public void pictureBox48_Click(object sender, EventArgs e)
{
string variable1 = pictureBox48.ImageLocation;
Form3 fo = new Form3(variable1);
fo.ShowDialog();
}
When dealing with Image or PictureBox I would recommend to not use something like Location or Path of the image. Assume that when the image is loaded user removes it from the hard drive and you're left with the code full of errors.
That's why you should rely on Image itself as it contains every information about the image like pixel format, width, height and raw pixel data.
I would recommend you to just copy the image, not the path to the file.
This piece of code should give you a hint:
pixtureBox48.Image = Image.FromFile(imgPath);
// above code assumes that the image is still on hard drive and is accessible,
// now let's assume user deletes that file. You have the data but not on the physical location.
Image copyImage = (Image)pictureBox48.Image.Clone();
Form3 fo = new Form(copyImage); // change .ctor definition to Form(Image copy)
fo.ShowDialog();
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.)
This question already has answers here:
Default name with OpenFileDialog C#?
(3 answers)
Closed 1 year ago.
I use the following to display an Open File dialog:
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.FileName = Properties.Settings.Default.Last_competition_file;
fdlg.Filter = "FS database files (*.fsdb)|*.fsdb|All files (*.*)|*.*";
fdlg.FilterIndex = 0;
if (fdlg.ShowDialog(this) == DialogResult.Cancel) return false;
(Properties.Settings.Default.Last_competition_file contains the whole path to the last file)
Problem: For a file name "c:\data\nationals_2014.fsdb", the File name field only shows "ionals_2014.fsdb".
When clicking into the File name field, and moving the cursor to the left, the remainder of the file name & path re-appears. But I'm looking for a way to make the whole file name visible from the beginning.
Note that this is not a length issue. I also tried setting path and file name separately (through OpenFileDialog.InitialDirectory), but even then only the tail end of the (now much shorter) file name was displayed.
Any ideas how to get the Open File dialog to show the full pre-populated file name from the beginning?
Caveat: This is a Kludge, not a real answer.
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.FileName = Properties.Settings.Default.Last_competition_file;
fdlg.Filter = "FS database files (*.fsdb)|*.fsdb|All files (*.*)|*.*";
fdlg.FilterIndex = 0;
fdlg.ShowHelp = true;
fdlg.HelpRequest += new System.EventHandler(HelpRequested); ;
if (fdlg.ShowDialog(this) == DialogResult.Cancel) return false;
private void HelpRequested(object sender, EventArgs e)
{
MessageBox.Show(".. is no Help", "There..");
}
The style of the Dialog reverts to an older incarnation.
Shrug. Some workarounds make me wonder about many things..
I got the same thing on windows 10 with an open file dialog set up like this:
var dialog = new OpenFileDialog{
Filter = "excel files (*.xlsx)|*.xlsx",
InitialDirectory = #"c:\temp",
FileName = #"MyFileNameExceeds14Characters.xlsx"
};
dialog.ShowDialog();
Work-arounds:
Set AutoUpgradeEnabled = false to revert to an older dialog style. But then you're stuck with the older UI.
Make sure the file name is under 14 characters long. If you don't have direct control of the file name, then run it through Path.GetFileNameWithoutExtension() to slim it down as much as possible.
Use a SaveFileDialog instead, which does not have this issue.
Inserting code:
SendKeys.Send("{HOME}");
before the line :
if (fdlg.ShowDialog(this) == DialogResult.Cancel) return false;
does the job.
Found a good answer on another thread:
c# Sending keyboard commands to another window / process
This does a good job of fixing the file name display.
I use a timer anyway in order to make sure that dialog is centered on active screen. Once the dialog is displayed:
IntPtr handle = FindWindowByCaption(IntPtr.Zero, dialogTitle));
SetForegroundWindow(handle);
SendKeys.SendWait("{HOME}");
SendKeys.Flush();
I am looking for a way to embed image to Rich text box. My rtf file is portable which contains both image and text. i.e. It can be moved from one computer to another. So the user should be able to see the content of rtf file (text+image) even if its in another machine.
Now I am using the following code to insert image.
public static void ApplyImage(RichTextBox RichTextBoxControl)
{
try
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt = ".png";
dlg.Filter = "PNG Files (.png)|*.png|JPG Files (.jpg)|*.jpg|GIF Files (.gif)|*.gif";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string fileName = dlg.FileName;
if (File.Exists(fileName))
{
BitmapImage bi = new BitmapImage(new Uri(fileName));
Image image = new Image();
image.Source = bi;
InlineUIContainer container = new InlineUIContainer(image);
Paragraph paragraph = new Paragraph(container);
RichTextBoxControl.Document.Blocks.Add(paragraph);
}
}
}
catch
{
throw;
}
}
But this code is not suitable for my purpose. Because the embedded image may not be in the other machine. So it won't work. Either I need to embed image or store image as binary in rtf file. I searched everywhere and no luck.
Can anyone help me please?
I got a solution for the problem. I am not sure its the right way, but still this solution is working for me. Hope it may help others.
The solution is to iterate through all image tags in flow document and copy the images to a repository folder which is portable. Then load the images from that repository folder next time to show the images back in to richtextbox.
foreach (Block block in rtb.Blocks)
{
if (block is Paragraph)
{
Paragraph paragraph = (Paragraph)block;
foreach (Inline inline in paragraph.Inlines)
{
if (inline is InlineUIContainer)
{
InlineUIContainer uiContainer = (InlineUIContainer)inline;
if (uiContainer.Child is Image)
{
Image image = (Image)uiContainer.Child;
//Copy Image source to another repository folder and save the path.
}
}
}
}