I have the following C# code :
string selectedFile = "D:\..\IMGP2695.JPG";
MyImage myImage = new MyImage();
Image image = Image.FromFile(selectedFile);
string thumbnail_name = CreateThumbnail(image);
myImage.height = image.Height + "px";
myImage.width = image.Width + "px";
ftp.upload(myImage.internalName, selectedFile, directory);
The process cannot access the file `'D:\..\IMGP2695.JPG'` because it is being used by another process.
I get this error when the code try to run ftp.upload. I know what the error means but i don't know what to do to close the handle to the opened file.
Try to dispose image object by wrapping Image.FromFile with using:
string selectedFile = "D:\..\IMGP2695.JPG";
MyImage myImage = new MyImage();
string thumbnail_name = string.empty;
using(Image image = Image.FromFile(selectedFile)){
thumbnail_name = CreateThumbnail(image);
myImage.height = image.Height + "px";
myImage.width = image.Width + "px";
}
ftp.upload(myImage.internalName, selectedFile, directory);
Because you calling Image image = Image.FromFile(selectedFile); before uploading , for some reason.
If you look on Image.FromFile documentation you will see the following string:
The file remains locked until the Image is disposed.
That means, that according to the code provided, you can init Image even after the upload finished.
ftp.upload("NAME_OF_THE_FILE_RECOVERED_FROM_FILE_ITSELF", selectedFile, directory);
Image image = Image.FromFile(selectedFile);
Related
I have a file upload control that allows users to upload an image file. Rather then forcing them to use a specific size image, I am trying to resize it, save it the resized version to a folder and then delete the original.
When I try to delete the file, I keep getting "file in use" exception. I have searched and tried all suggestions to no avail.
This is the latest try, at which point I decided to seek help. I pass the source path (where original file is in, a destination path where resized file is to end up in, file name and width to which it should be resized, keeping aspect ratio):
public static void CreateResizedCopy(String sourcePath, String destinationPath, String filename, int width)
{
if (!File.Exists(destinationPath + filename))
{
System.Drawing.Image image = System.Drawing.Image.FromFile(sourcePath + filename);
float AspectRatio = (float)image.Size.Width / (float)image.Size.Height;
int newHeight = Convert.ToInt32(width / AspectRatio);
Bitmap thumbnailBitmap = new Bitmap(width, newHeight);
Graphics thumbnailGraph = Graphics.FromImage(thumbnailBitmap);
thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, width, newHeight);
thumbnailGraph.DrawImage(image, imageRectangle);
thumbnailBitmap.Save(destinationPath + filename, ImageFormat.Jpeg);
thumbnailGraph.Dispose();
thumbnailBitmap.Dispose();
image.Dispose();
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
if (!FileInUse(sourcePath + filename))
{
File.Delete(sourcePath + filename);
}
else
{
// Error here: file is in use
using (FileStream fs = new FileStream(sourcePath + filename, FileMode.OpenOrCreate))
fs.Dispose();
}
}
}
public static bool FileInUse(string path)
{
try
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
return false;
}
}
catch (IOException ex)
{
return true;
}
}
UPDATE
This is the AJAX AsynFileUpload's upload completed event handler. It saves the file to a "Resize" folder. If image needs to be resized, it calls the method to resize it and then moves it to its final resting place. If not, no resizing is done, it just moves the file. It then "attempts" to delete the file in resize folder and it chokes!
protected void fuNewsImage_UploadedComplete_Resize(object sender, AsyncFileUploadEventArgs e)
{
if (fuNewsImage.HasFile)
{
HttpPostedFile file = fuNewsImage.PostedFile;
string sFileName = fuNewsImage.FileName;
string sFileSize = e.FileSize;
string sSaveFolder = ImageFilePath.TEMP_FOLDER_EA_TEST + "\\";
string sResizeFolder = ImageFilePath.TEMP_FOLDER_EA_TEST + "\\Resized\\";
fuNewsImage.SaveAs(Server.MapPath(sResizeFolder + sFileName));
System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath(sResizeFolder) + sFileName);
int iImgWidth = img.Width;
int iImgHeight = img.Height;
if (iImgWidth > ImageInfo.MAX_WIDTH)
{
// sSaveFolder is the efinal resting place of the uploaded image
// If image width is more than max allowed, resize it, save it in sSaveFolder
Utils.CreateResizedCopy(Server.MapPath(sResizeFolder), Server.MapPath(sSaveFolder), sFileName, 600);
System.Threading.Thread.Sleep(1000);
File.Delete(Server.MapPath(sSaveFolder + sFileName));
}
else // just move it t sSaveFolder
{
File.Move(Server.MapPath(sResizeFolder) + sFileName, Server.MapPath(sSaveFolder) + sFileName);
}
// --- Chokes here ---
Array.ForEach(Directory.GetFiles(Server.MapPath(sResizeFolder)), File.Delete);
}
}
I Working on Windows Phone 8 application.
string Image = "/MyData/" + myObject.ImageName + "big.png";
BitmapImage bmp = new BitmapImage(new Uri(Image , UriKind.Relative));
MyImage.Source = bmp;
I have a image in the folder MyData/, i have 2 sets of images like <imagename>big.png,<imagename>small.png.
So here what is happening is i want to check if <imagename>big.png exists in the location or not, if not pick <imagename>small.png.
How to do it ?
EDIT
I solved it myself, here is how.
File.Exists("path to file") here path should be `folderName/filenames` and not `/folderName/filenames`
Thanks for everyone who helped me.
string image = "/MyData/" + myObject.ImageName + "/big.png";
string fileName = Path.GetFileName(image);
if(!string.IsNullOrEmpty(fileName))
{
MessageBox.Show("File Exist -"+fileName);
}
else
{
MessageBox.Show("No File Exist -");
}
BitmapImage bmp = new BitmapImage(new Uri(image , UriKind.Relative));
if(bmp==null)
{
image = "/MyData/" + myObject.ImageName + "/small.png";
bmp = new BitmapImage(new Uri(image , UriKind.Relative));
}
MyImage.Source = bmp;
Imagename = objUser.UserID + filename;
Imagepath = "D:\\Shop\\ShopMonkey\\Images" + Imagename;
FileUpload.SaveAs(Path.Combine(#"D:\ShopMonkey_Web_21-6-12\ShopMonkey\Images", Imagename));
objUser.UploadImagePath = Imagepath;
objUser.UploadImagename = Imagename;
System.Drawing.Image img1 = System.Drawing.Image.FromFile(Imagepath);
System.Drawing.Image bmp1 = img1.GetThumbnailImage(50, 50, null, IntPtr.Zero);
ThumbNailPath = "D:\\ShopMonkey_Web_21-6-12\\ShopMonkey\\ThumbNails" + Imagename;
bmp1.Save(Path.Combine(#"D:\ShopMonkey_Web_21-6-12\ShopMonkey\ThumbNails", Imagename));
objUser.UploadThumbnailPath = ThumbNailPath;
How to delete the image and thumbnail in other function? (Is it necessary to close that first or not?)
I'm guessing that you're trying to delete a file on disk if it already exists for this user upon asp.net upload of an image by that same user again.
This method will delete both image and thumbnail if they exist.
Keep your image creation activities separate from your image clean up activities to keep your intent clear and your code maintainable.
// replace with an entry loaded from a config file
const string ImageRoot = #"D:\ShopMonkey_Web_21-6-12\ShopMonkey";
// replace this is your user instance
object user = new object();
string Imagename = objUser.UserID + filename;
string uploadImagePath = Path.Combine(ImageRoot, "Images", Imagename);
string thumbnailPath = Path.Combine(ImageRoot, "ThumbNails", Imagename);
objUser.UploadImagePath = uploadImagePath;
objUser.UploadImagename = Imagename;
objUser.UploadThumbnailPath = thumbnailPath;
// delete both if they exist
if (File.Exists(uploadImagePath))
File.Delete(uploadImagePath);
if (File.Exists(thumbnailPath))
File.Delete(thumbnailPath);
// replace this with your uploaded file details
object fileInfo = new object();
using (System.Drawing.Image img1 = System.Drawing.Image.FromFile(uploadImagePath)) {
img1.Save(uploadImagePath);
using (System.Drawing.Image bmp1 = img1.GetThumbnailImage(50, 50, null, IntPtr.Zero)) {
bmp1.Save(thumbnailPath);
}
FileUpload.SaveAs(uploadImagePath);
}
I would like to clear a bitmap image. I've tried both
uploadImage.Source = null;
and
uploadImage.Source = "";
This is the code I used to make the image:
// BitmapImage.UriSource must be in a BeginInit/EndInit block
BitmapImage myBitmapImage = new BitmapImage();
string curItem = destinationFolder + "\\" + listBox1.SelectedItem.ToString();
myBitmapImage.BeginInit();
myBitmapImage.UriSource = new Uri(#curItem);
myBitmapImage.DecodePixelWidth = 200;
myBitmapImage.EndInit();
uploadImage.Source = myBitmapImage;
uploadImage.Source = null should do it. How are you checking the value of the Source property? I'd suggest Mole.
If you are relying on what you see on screen this may be wrong due to property changes not being notified. Try creating a DependencyProperty for the Image or a regular property raising a notification through the INotifyPropertyChanged interface.
imagesHello -
I want to display a picture from a local folder in a picturebox, however if that picture fails to load, I woud like to download the image from a website and display it. I have no idea how to do this, but what I have is this:
try
{
pictureBox1.Image = System.Drawing.Image.FromFile("images\\" + filename + "_0001.gif");
XmlIn1.Close();
}
catch
{
string downloadPath = "http://www.website.com/images/" + filename + "_0001.gif";
pictureBox1.Image = System.Drawing.Image.FromFile(downloadPath);
XmlIn1.Close();
}
Why not use the ImageLocation property?
pictureBox1.ImageLocation = "http://skins.gmodules.com/ig/images/logos/approved/beveled_white.png";
Above code will display Google Logo from Web.
try something like
WebClient wc = new WebClient();
MemoryStream ms = new MemoryStream(wc.DownloadData(<imgURL>));
pictureBox1.Image = Image.FromStream(ms);