Get the size of an Image - c#

I'm making a little Windows Forms app to select an image from your PC, and then display the image in pictureBox1 using the filepath.
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
pictureBox1.ImageLocation = openFileDialog1.FileName;
}
}
Now I want to put the dimensions (in pixels) of the image in an other textbox.
Is this possible the way I'm doing it?

I don't think that you can get the size when setting the image using ImageLocation (As the PictureBox handles loading internally). Try loading the image using Image.FromFile, and using the Width and Height properties of that.
var image = Image.FromFile(openFileDialog1.FileName);
pictureBox1.Image = image;
// Now use image.Width and image.Height

Try this
System.Drawing.Image img = System.Drawing.Image.FromFile(openFileDialog1.FileName);
MessageBox.Show("Width: " + img.Width + ", Height: " + img.Height);

Open the image using Image.FromFile method
Image image = Image.FromFile(openFileDialog1.FileName);
Put your image in the pictureBox1
pictureBox1.Image = image;
What you need is System.Drawing.Image class. The size of the image is in the image.Size property. But if you want to get Width and Height separately, you can use image.Width and image.Height respectively
Then in your other TextBox (suppose the name is textBox2) You can simply assign the Text property like this,
textBox2.Text = "Width: " + image.Width.ToString() + ", Height: " + image.Height.ToString();
Complete code:
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
Image image = Image.FromFile(openFileDialog1.FileName);
pictureBox1.Image = image; //simply put the image here!
textBox2.Text = "Width: " + image.Width.ToString() + ", Height: " + image.Height.ToString();
}
}

Related

Set Auto width and height for converted HTML to Image using Bitmap

I'm using these 2 Functions for generate Image from Html Code:
public static void StartBrowser(string HtmlText)
{
var th = new Thread(() =>
{
var webBrowser = new WebBrowser();
webBrowser.ScrollBarsEnabled = false;
webBrowser.IsWebBrowserContextMenuEnabled = true;
webBrowser.AllowNavigation = true;
webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;
webBrowser.DocumentText = HtmlText;
Application.Run();
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
}
static void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string path = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var webBrowser = (WebBrowser)sender;
using (Bitmap bitmap =
new Bitmap(
webBrowser.Width=450,
webBrowser.Height=1000))
{
webBrowser
.DrawToBitmap(
bitmap,
new System.Drawing
.Rectangle(0, 0, bitmap.Width, bitmap.Height));
string imgfile = "fileimg" + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + ".jpg";
bitmap.Save(path + "/images/" + imgfile, System.Drawing.Imaging.ImageFormat.Jpeg);
OrderDetailRepeatedImage = path + "/images/" + imgfile;
}
Application.ExitThread();
}
The Issue that I am trying to fix is the previous code to generate an image using bitmap with specific width and height.
How I can Make this function work by setting automatic width and height as the given html code, because some times the given html is more than the given dimensional?
Thanks in advance.

c# the image file is duplicated when I copy file to the folder

I am trying to browse multiple image files and copy them to another folder. So, what I do is when I browse the image I storeit in flowlayoutpanel first, after that I create a button to copy all the image from flowlayutpanel to the destination folder. Now,I have a problem when I copy to another folder even if it has a different file name. Any suggestions to solve this question.
*this is the code to copy file to folder.
private void button2_Click(object sender, EventArgs e)
{
foreach (TextBox tb1 in TextBoxes1)
{
MessageBox.Show(tb1.Text);
String[] files = openFileDialog1.FileNames;
String newDir = #"C:\Users\Public\Pictures\Sample Pictures\Modified";
System.IO.Directory.CreateDirectory(newDir);
Parallel.ForEach(files, (textboxes) =>
{
foreach (TextBox tb in TextBoxes)
{
String filename = System.IO.Path.GetFileName(tb.Text);
var bitmap = new Bitmap(textboxes);
String text = Path.Combine(newDir, filename);
string toDisplay = string.Join(Environment.NewLine, files);
MessageBox.Show(toDisplay);
bitmap.Save(text);
}
});
}
}
* this is the code how i browse the image file and show in flowlayout
private void button1_Click_2(object sender, EventArgs e)
{
DialogResult dr = this.openFileDialog1.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
// Read the files
foreach (String file in openFileDialog1.FileNames)
{
// Create a PictureBox.
try
{
Panel panel = new Panel();
PictureBox pb = new PictureBox();
TextBox tb = new TextBox();
TextBox tb1 = new TextBox();
Image loadedImage = Image.FromFile(file);
pb.Height = 200;
pb.Width = 200;
pb.Image = loadedImage;
pb.SizeMode = PictureBoxSizeMode.StretchImage;
tb.Text = Path.GetFileName(openFileDialog1.FileName);
tb1.Text = openFileDialog1.FileName;
//panel.Controls.Add(pb);
panel.Controls.Add(tb);
panel.Controls.Add(tb1);
panel.Height = 200;
panel.Width = 200;
flowLayoutPanel1.Controls.Add(panel);
TextBoxes.Add(tb);
TextBoxes1.Add(tb1);
}
catch (SecurityException ex)
{
// The user lacks appropriate permissions to read files, discover paths, etc.
MessageBox.Show("Security error. Please contact your administrator for details.\n\n" +
"Error message: " + ex.Message + "\n\n" +
"Details (send to Support):\n\n" + ex.StackTrace
);
}
catch (Exception ex)
{
// Could not load the image - probably related to Windows file system permissions.
MessageBox.Show("Cannot display the image: " + file.Substring(file.LastIndexOf('\\'))
+ ". You may not have permission to read the file, or " +
"it may be corrupt.\n\nReported error: " + ex.Message);
}
}
}
I guess parallel.foreach is the culprit. You are using multiple threads when using Parallel.foreach
In other words, you have two threads doing the same thing.
I would suggest you to try with a simple foreach loop.

How to get all the data in flowlayout panel and copy to folder

i manage to do when i browse multiple image path in flowayoutpanel, and click on button save so, all the image path will save to a folder, my problem is i can browse the image path and show in flowlayoutpanel, but i dun know how to get the image path from it and copy to folder, any suggestion to do it?
*this is how i browse image path and show in Flowlayoutpanel
private void button1_Click_2(object sender, EventArgs e)
{
DialogResult dr = this.openFileDialog1.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
// Read the files
foreach (String file in openFileDialog1.FileNames)
{
// Create a PictureBox.
try
{
Panel panel = new Panel();
PictureBox pb = new PictureBox();
TextBox tb = new TextBox();
Image loadedImage = Image.FromFile(file);
pb.Height = 200;
pb.Width = 200;
pb.Image = loadedImage;
pb.SizeMode = PictureBoxSizeMode.StretchImage;
tb.Text = openFileDialog1.FileName;
//panel.Controls.Add(pb);
panel.Controls.Add(tb);
panel.Height = 200;
panel.Width = 200;
flowLayoutPanel1.Controls.Add(panel);
}
catch (SecurityException ex)
{
// The user lacks appropriate permissions to read files, discover paths, etc.
MessageBox.Show("Security error. Please contact your administrator for details.\n\n" +
"Error message: " + ex.Message + "\n\n" +
"Details (send to Support):\n\n" + ex.StackTrace
);
}
catch (Exception ex)
{
// Could not load the image - probably related to Windows file system permissions.
MessageBox.Show("Cannot display the image: " + file.Substring(file.LastIndexOf('\\'))
+ ". You may not have permission to read the file, or " +
"it may be corrupt.\n\nReported error: " + ex.Message);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
foreach(TextBox tb in TextBoxes)
{
File.Copy(tb.Text, dest);
}
}
Obviously you have to store the filenames somewhere, either in a textbox like you did (although I would recommend tb.Text=file instead!), or you are using a separate List<string> (I would recommend the latter! Using a form for storing things is mostly no good idea).
To get the files simply iterate either foreach(Control c in flowLayoutPanel1.Items) and then go down the SubControls to your textbox or use the separate list.
The copy you can do with File.Copy(src, dest).

How to delete image which is opened in picturebox in c#? [duplicate]

This question already has answers here:
Deleting File which is displayed in picturebox
(5 answers)
Closed 8 years ago.
Deleting an image which is opened in picturebox:
private void button1_Click_1(object sender, EventArgs e)
{
lblimgname.Text = "Right Thumb 1";
string savepath = #"C:/BrainScript/" + clientname + "/";
FileStream fs = new FileStream(savepath + clientname + "_" + lblimgname.Text + ".jpg", FileMode.Open, FileAccess.Read);
Image img = Image.FromStream(fs);
fs.Close();
picRightthumb1.Image = img.Clone() as Image;
img.Dispose();
File.Delete(savepath + clientname + "_" + lblimgname.Text + ".jpg");
}
private Image GetCopyImage(string path)
{
using (Image im = Image.FromFile(path))
{
Bitmap bm = new Bitmap(im);
return bm;
}
}
I have written the above code to delete the image which is opened in the picturebox but i am getting error "The process is used by another process" pls help me out from this problem.
I used the following code and it works fine:
private void button1_Click(object sender, EventArgs e)
{
FileStream file = new FileStream("1.jpg", FileMode.Open);
pictureBox1.Image = Image.FromStream(file);
file.Close();
File.Delete("1.jpg");
}

'A generic error occurred in GDI+' when saving an image

I have been having quite a problem with this.
Here is my code.
int frame = 0;
//This is a wpf button event
private void up_Click(object sender, RoutedEventArgs e)
{
frame++;
LoadPic();
}
private void LoadPic()
{
string fn = #"C:\Folder\image" + (frame % 2).ToString() + ".png";
Bitmap bmp = new Bitmap(302, 170);
bmp.Save(fn);
bmp.Dispose();
//Picebox is a wpf Image control
Picbox.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(fn));
}
private void down_Click(object sender, RoutedEventArgs e)
{
frame--;
LoadPic();
}
When I start the program, a wpf window pops open. There are two buttons with the events shown in the code.
When I press the up button twice it works fine. This saves two PNGs to the locations
"C:\Folder\image0.png" and "C:\Folder\image1.png"
The third time I press the button, it should save it to "C:\Folder\image0.png" again.
Instead, it gives the exception 'A generic error occurred in GDI+'.
I have had a similar problem before, and solved it by adding these two lines:
GC.Collect();
GC.WaitForPendingFinalizers();
It didn't work this time.
To avoid the filelock that BitmapImage creates you have to take care of a bit more initialization. According to this question here on SO, it can be done like this (ported to C# from their VB.Net code).
private void LoadPic()
{
string fn = #"C:\Folder\image" + (frame % 2).ToString() + ".png";
Bitmap bmp = new Bitmap(302, 170);
bmp.Save(fn);
bmp.Dispose();
var img = new System.Windows.Media.Imaging.BitmapImage();
img.BeginInit();
img.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;
img.UriSource = new Uri(fn);
img.EndInit();
Picbox.Source = img;
}

Categories