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

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");
}

Related

Extract resources to current directory?

I want to extract the resources "cygz.dll" to the current directory where the program started right after the form is loaded.
Here is my code.
private static void extract(string nameSpace, string outDirectory, string internalFilePath, string resourceName)
{
Assembly assembly = Assembly.GetCallingAssembly();
using (Stream s = assembly.GetManifestResourceStream(nameSpace + "." + (internalFilePath == "" ? "" : internalFilePath + ".") + resourceName))
using (BinaryReader r = new BinaryReader(s))
using (FileStream fs = new FileStream(outDirectory + "\\" + resourceName, FileMode.OpenOrCreate))
using (BinaryWriter w = new BinaryWriter(fs))
w.Write(r.ReadBytes((int)s.Length));
}
private void Form1_Load(object sender, EventArgs e)
{
extract("myNamespace", "\\TEMP", "resources", "cygz.dll");
}
Instead of "\\TEMP", I want to extract "cygz.dll" to the current directory
If by "current directory" you mean the path for the executable file that started the application, then you can use Application.ExecutablePath like this:
System.IO.Path.GetDirectoryName(Application.ExecutablePath);
You can find more details here: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.application.executablepath?view=netframework-4.7.2
This solved my problem
private void Form1_Load(object sender, EventArgs e)
{
string path = Environment.CurrentDirectory;
extract("myNamespace", path, "resources", "cygz.dll");
}

delete folder but the process cannot access the file because being used

so i made a simple project where when i click a button the picture edit get an image from a folder file, but when i want to delete the folder that contains the image, it gives me an error. the code as following
private void button1_Click(object sender, EventArgs e)
{
string pathx = AppDomain.CurrentDomain.BaseDirectory + "\\TempImage\\" + "naruto" + ".png";
pictureEdit1.Image = Image.FromFile(pathx);
}
private void button2_Click(object sender, EventArgs e)
{
string dir = AppDomain.CurrentDomain.BaseDirectory + "\\TempImage";
try {
if (Directory.Exists(dir))
{
//////give me an error in here///////
Directory.Delete(dir, true);
}
else
{
MessageBox.Show("folder not found");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
the purpose of this, is in my main project, for cache purpose. so i get an image from a certain folder after coping it from server to local. and when i want to close the main project i need to clear the cache or folder
Update
which is better alternate 1 or alternate 2 (to dispose)
private void button1_Click(object sender, EventArgs e)
{
string pathx = AppDomain.CurrentDomain.BaseDirectory + "\\TempImage\\" + "naruto" + ".png";
//alternate1
using (FileStream stream = new FileStream(pathx, FileMode.Open, FileAccess.Read))
{
pictureEdit1.Image = Image.FromStream(stream);
//stream.Dispose();
}
//alternate2
//Image img = new Bitmap(pathx);
//pictureEdit1.Image = img.GetThumbnailImage(pictureEdit1.Width, pictureEdit1.Height, null, new IntPtr());
//img.Dispose();
}
The documentation on System.Drawing.Bitmap (http://msdn.microsoft.com/en-us/library/0cbhe98f.aspx) says:
The file remains locked until the Bitmap is disposed.
To get around this, you should replace this line:
pictureEdit1.Image = Image.FromFile(pathx);
With this:
Image img = new Bitmap(pathx);
pictureEdit1.Image = img.GetThumbnailImage(pictureEdit1.Width, pictureEdit1.Height, null, new IntPtr());
img.Dispose();
This should load the Bitmap only long enough to create a thumbnail version of the image for use in the PictureBox control, then dispose of it immediately, releasing the lock on the file but still displaying the image on the screen.
Hope this helps!
Edit: Here's the version using using that does the same thing:
using (Image img = new Bitmap(pathx)) {
pictureEdit1.Image = img.GetThumbnailImage(pictureEdit1.Width, pictureEdit1.Height, null, new IntPtr());
}

Get the size of an Image

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();
}
}

'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;
}

Refreshing Image Control To Display File Upload Preview

Hi i'm trying to display a preview of an uploaded img in asp.net using the file upload control, i have a preview button where when the user clicks should save the file from the fileupload control into a temp folder on my server and change the imageurl of the imagecontrol to the path of the saved image in the temp folder and display the image on the page after a postback. Here is what i have done:
protected void btnPreview_1_Click(object sender, EventArgs e)
{
if (!imgUpload_1.HasFile)
{
return;
}
string strFileName = Path.GetFileNameWithoutExtension(imgUpload_1.FileName.ToString());
string ext = Path.GetExtension(imgUpload_1.FileName.ToString());
string loc = "temp/";
string strImgFolder = Server.MapPath(loc);
System.Drawing.Image newImage;
FileUpload img = (FileUpload)imgUpload_1;
Byte[] imgByte = null;
try
{
if (img.HasFile && img.PostedFile != null)
{
HttpPostedFile File = imgUpload_1.PostedFile;
imgByte = new Byte[File.ContentLength];
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
}
catch (Exception ex)
{
}
if (imgByte != null)
{
using (MemoryStream stream = new MemoryStream(imgByte, 0, imgByte.Length))
{
newImage = System.Drawing.Image.FromStream(stream);
newImage.Save(strImgFolder + strFileName + ext);
imgPreview.ImageUrl = strImgFolder + strFileName + ext;
imgPreview.AlternateText = strFileName;
}
}
}
I've tried using a handler for this using code i found online and after hours of trying i still couldn't get it to work, i also tried attaching a random number to the end of the imageurl(like so imageurl + "?" + randomnumber to force the page to refresh(That didn't work either) and i also tried:
Response.AddHeader("Cache-Control", "no-cache");
in my page load even and that didn't work either.
I've been at it for hours could someone plz help me out?

Categories