i have a image. and i open it in image viewer that i created. now i want to edit this image. so i open this image in paint and when i click on save button after change it give me. some error of a sharing violation occurred while accessing.
i remove the file name from image viewer before open image in paint.
here is my code..
private void btnEditImage_Click(object sender, RoutedEventArgs e)
{
if (File.Exists(Helper.DefaultPath + listImages[count].Path))
{
SetNullImage();
string editPath = Helper.DefaultPath + listImages[count].Path;
if (File.Exists(editPath))
{
Process my = new Process();
my.StartInfo.FileName = "mspaint.exe";
my.StartInfo.Arguments = "\"" + editPath + "\"";
my.StartInfo.CreateNoWindow = true;
my.EnableRaisingEvents = true;
my.Exited += new EventHandler(myProcess_Exited);
my.Start();
}
}
}
private void myProcess_Exited(object sender, System.EventArgs e)
{
Dispatcher.Invoke(new Action(() =>
{
SetImage();
}));
}
See Images
Open In Image viewer:
thanks...
Error when make changes in image and click on save:
While you call SetImage() Method, make sure that you are using Image.FromFile() Method. If you using That, Use Bellow code instead of that
private Bitmap SetImage(){
pictureBox1.Image = GetImageFromPath(ImagePath)
}
private Bitmap GetImageFromPath(string Path)
{
using (StreamReader streamReader = new StreamReader(Path))
{
using (Bitmap tmpBitmap = (Bitmap)Bitmap.FromStream(streamReader.BaseStream))
{
return tmpBitmap;
}
}
}
Related
I have asp:FileUpload and I want to save all uploaded images of all acceptable formats as png images in the Images forlder on website, my upload code is:
protected void btnSave_Click(object sender, EventArgs e)
{
if (fup2.HasFile)
{
Regex reg = new Regex(#"(?i).*\.(gif|jpe?g|png|tif)$");
string uFile = fup2.FileName;
if (reg.IsMatch(uFile))
{
string saveDir = Server.MapPath(#"~/Images/");
string SavePath = saveDir + uFile;
fup2.SaveAs(SavePath);
}
else
{
Response.Write("Error");
}
}
}
I also tried using
var tempImg = Image.FromFile(Server.MapPath(#"~/Images/"));
tempImg.Save("a.tiff", ImageFormat.png);
It keeps throwing file not found exception
Any new ideas?
Use Bitmap.FromStream. Something like:
using System.Drawing;
protected void btnSave_Click(object sender, EventArgs e)
{
if (fup2.HasFile)
{
Regex reg = new Regex(#"(?i).*\.(gif|jpe?g|png|tif)$");
string uFile = fup2.FileName;
if (reg.IsMatch(uFile))
{
string saveDir = Server.MapPath(#"~/Images/");
string SavePath = saveDir + Path.GetFileName(uFile) + ".png";
Bitmap b = (Bitmap)Bitmap.FromStream(fup2.PostedFile.InputStream);
b.Save(SavePath, ImageFormat.Png);
}
else
{
Response.Write("Error");
}
}
}
The Image.FromFile -> Save should do the trick, but i don't see how you are using the correct path - you just point at the directory and not the actual file when calling FromFile
As a side note, doing this processing on a web processing thread is not a great idea but for small load it could work.
I will try my best to explain the issue clearly. I'm using the code from
http://msdn.microsoft.com/en-us/magazine/dn385710.aspx
to create a photo sharing app. I am able to FTP images to my server fine. The issue I'm facing is when I tried to create the app to preview the picture and then FTP it. The FTP will still transfer the file, but the file size is always 0 size. I'm not sure if this is a bug or possibly me not disposing a certain object before FTP. Below are my codes:
Page 1
BitmapImage bitmapImage;
public PhotoPreview()
{
InitializeComponent();
btnYes.Tap += btnYes_Tap;
imgPreview.Width = G.getScreenWidth();
imgPreview.Height = G.getScreenHeight() - 250;
//windows phone 8 bug. When bitmap image is set...it blocks the FTP process thread. Will perform FTP on seperate page
previewPhoto();
}
void previewPhoto()
{
bitmapImage = new BitmapImage();
bitmapImage.SetSource(G.myStream);
imgPreview.Source = bitmapImage;
}
private void btnYes_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
disposeImage(bitmapImage);
NavigationService.Navigate(new Uri("/PhotoFTP.xaml", UriKind.Relative));
}
private void disposeImage(BitmapImage img)
{
if (img != null)
{
try
{
using (var ms = new MemoryStream(new byte[] { 0x0 }))
{
img = new BitmapImage();
img.SetSource(ms);
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("ImageDispose FAILED " + e.Message);
}
}
}
Page 2
const string
IP_ADDRESS = "888.88.888",
FTP_USERNAME = "test",
FTP_PASSWORD = "test123"
;
string filename;
FtpClient ftpClient = null;
TestLogger logger = null;
public PhotoFTP()
{
InitializeComponent();
DateTime thisDay = DateTime.Today;
string timestamp = thisDay.Hour.ToString() + "_" + thisDay.Minute.ToString() + "_" + thisDay.Second.ToString();
filename = timestamp + ".jpg";
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Test_connect();
}
private async void Test_connect()
{
logger = TestLogger.GetDefault(this.Dispatcher);
lstLogs.ItemsSource = logger.Logs;
ftpClient = new FtpClient(IP_ADDRESS, this.Dispatcher);
ftpClient.FtpConnected += ftpClient_FtpConnected;
ftpClient.FtpFileUploadSucceeded += ftpClient_FtpFileUploadSucceeded;
ftpClient.FtpFileUploadFailed += ftpClient_FtpFileUploadFailed;
ftpClient.FtpAuthenticationSucceeded += ftpClient_FtpAuthenticationSucceeded;
ftpClient.FtpAuthenticationFailed += ftpClient_FtpAuthenticationFailed;
logger = TestLogger.GetDefault(this.Dispatcher);
await ftpClient.ConnectAsync();
logger.AddLog("Connecting...");
}
async void ftpClient_FtpConnected(object sender, EventArgs e)
{
logger.AddLog("Preparing...");
await (sender as FtpClient).AuthenticateAsync(FTP_USERNAME, FTP_PASSWORD);
}
private async void Test_upload()
{
logger.AddLog("Uploading photo...");
await ftpClient.UploadFileAsync(G.myStream, "username_timestamp.jpg");
}
void ftpClient_FtpAuthenticationFailed(object sender, EventArgs e)
{
logger.AddLog("Connection error.");
}
void ftpClient_FtpAuthenticationSucceeded(object sender, EventArgs e)
{
logger.AddLog("Connection established.");
Test_upload();
}
void ftpClient_FtpFileUploadFailed(object sender, FtpFileTransferFailedEventArgs e)
{
logger.AddLog("Failed.");
}
Boolean firstTime = true;
void ftpClient_FtpFileUploadSucceeded(object sender, FtpFileTransferEventArgs e)
{
logger.AddLog("Completed.");
}
If I comment out the line previewPhoto(); in page 1, it will FTP the file to my server fine. I believe the issue is the
bitmapImage.SetSource(G.myStream);
I've also tried to create two separate stream. One to preview the photo and the other to FTP. The result still resulted in 0 size file when FTP to the my server.
It's because the BitmapImage reads to the end of the stream, so the FtpClient has no data to read/upload.
Use Stream.Seek to reset the stream pointer back to the beginning.
G.myStream.Seek(0, SeekOrigin.Begin);
I've searched and read a lot of the different ways to do this... and tried many of them.
When the program loads it loads printmark.png into the picture box.
Of course every time I try to delete the PNG file it says it's in use. As you can see I've tried both the Image.FileFrom and the picturebox.Load method.
This is the code I have.
private void GetCurrentLogos()
{
Image CurrentWM = Image.FromFile(#"C:\pics\logo.png");
Image CurrentPM = Image.FromFile(#"C:\pics\printmark.png");
pbWatermark.Image = CurrentWM;
pbPrintmark.Image = CurrentPM;
//pbWatermark.Load(#"C:\pics\logo.png");
//pbPrintmark.Load(#"C:\pics\printmark.png");
}
private void btnSetPM_Click(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
ListViewItem item = listView1.SelectedItems[0];
txtNewPM.Text = item.Tag.ToString();
pbPrintmark.Image.Dispose();
pbPrintmark.Image = null;
pbPrintmark.Refresh();
Application.DoEvents();
renameMark("printmark.png", txtNewPM.Text);
}
}
private void renameMark(string MarkType, string FileName)
{
string path = txtPath.Text;
string FullSource = path + FileName;
string FullDest = path + MarkType;
if(File.Exists(FullDest))
{
File.Delete(FullDest);
}
System.IO.File.Copy(FullSource, FullDest);
}
See Image.FromFile():
The file remains locked until the Image is disposed.
To get around this, pass the returned image to a new Bitmap so that the original lock gets released:
Image tmp = Image.FromFile(#"C:\pics\logo.png");
Image CurrentWM = new Bitmap(tmp);
tmp.Dispose();
As noted in some of the answers to this question, an image created by Image.FromFile keeps the underlying file open. This is by design, as the MSDN documentation says ("The file remains locked until the Image is disposed."). You can get around this by loading the file into a MemoryStream, then creating the image from that stream.
tmp.Dispose(); didnt worked for me so maybe u need also a different solution.
I used it for my dataGridView_SelectionChanged:
private void dataGridViewAnzeige_SelectionChanged(object sender, EventArgs e)
{
var imageAsByteArray = File.ReadAllBytes(path);
pictureBox1.Image = byteArrayToImage(imageAsByteArray);
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
I am working on a C# project and i need the file to deleted after 30 seconds. So once the file sent to the machine i need the software to count till 30 seconds and at same time show a splash form and once 30 seconds crossed close the splash screen and then delete the file.
I have added a splash screen called "image". So now what happens is, the data is only sent to the printer after the splash screen is closed. I need to multi thread the job. I mean the data should print in one side while the splash screen should show at the same time. Is there a way i can come out!!.. Please help me out.
So in my case i am copying the file to the bin/debug folder. then sending data to the machine simultaneously show the splash screen for 30 seconds and close the splash screen and then i need to delete the file..
codes:
private void button4_Click(object sender, EventArgs e)
{
//string filePath = image_print();
// MessageBox.Show(filePath, "path");
string s = image_print() + Print_image();
if (String.IsNullOrEmpty(s) || img_path.Text == "")
{
return;
}
else
{
//here its coming to the splash screen code, But data is transferred to the machine only after the splash screen is close :-(
this.Hide();
omg = new image();
omg.ShowDialog();
this.Show();
//splash screen closed and then data is transferred.. which i don't need.. i need simultaneous job to be done at the same time..
PrintFactory.sendTextToLPT1(s);
}
}
private string image_print()
{
OpenFileDialog ofd = new OpenFileDialog();
string path = "";
string full_path = "";
string filename_noext = "";
ofd.InitialDirectory = #"C:\ZTOOLS\FONTS";
ofd.Filter = "GRF files (*.grf)|*.grf";
ofd.FilterIndex = 2;
ofd.RestoreDirectory = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
filename_noext = System.IO.Path.GetFileName(ofd.FileName);
path = Path.GetFullPath(ofd.FileName);
img_path.Text = filename_noext;
//MessageBox.Show(filename_noext, "Filename"); - - -> switching.grf
// MessageBox.Show(full_path, "path");
//move file from location to debug
string replacepath = #"\\bin\Debug";
string fileName = System.IO.Path.GetFileName(path);
string newpath = System.IO.Path.Combine(replacepath, fileName);
// string newpath = string.Empty;
if (!System.IO.File.Exists(filename_noext))
System.IO.File.Copy(path, newpath);
filename_noext = img_path.Text;
MessageBox.Show(filename_noext, "path");
}
if (string.IsNullOrEmpty(img_path.Text))
return "";//
StreamReader test2 = new StreamReader(img_path.Text);
string s = test2.ReadToEnd();
return s;
}
private string Print_image()
{
//some codes
return s;
}
In image form: I have the following codes
public partial class image : Form
{
string filePath;
public image()
{
InitializeComponent();
// this.filePath = FileToDeletePath;
System.Timers.Timer timer1 = new System.Timers.Timer();
timer1.Interval = 30000;
timer1.Elapsed += timer1_Elapsed;
timer1.Start();
}
private void image_Load(object sender, EventArgs e)
{
}
void timer1_Elapsed(object sender, ElapsedEventArgs e)
{
//delete the file using "filePath"
string Filename = img_path.Text; // here i cannot pass the old string file name with extension to this form.. Any ways please help me out
if (string.IsNullOrEmpty(Filename))
return;
if (Filename.ToCharArray().Intersect(Path.GetInvalidFileNameChars()).Any())
return;
File.Delete(Path.Combine(#"\\bin\Debug", Filename));
}
}
something like this????
Task waitfordelete = Task.Run(() =>
{
image im = new image();
});
Assumptions: window image should be shown as a dialog (modal), and only while the call to PrintFactory.sendTextToLPT1 is in progress.
If that's correct, then something like this could work for you:
// Don't forget, you need to dispose modal dialogs
image omg = new image();
// Ensure the dialog has been shown before starting task. That
// way the task knows for sure the dialog's been opened and can
// be closed.
omg.Loaded += (sender, e) =>
{
// Run the print task in a separate task
Task.Run(() =>
{
PrintFactory.sendTextToLPT1(s);
// But get back onto the main GUI thread to close the dialog
Dispatcher.Invoke(() => omg.Close());
});
};
this.Hide();
omg.ShowDialog();
this.Show();
Apologies in advance for any typos/syntax errors/etc. Hopefully the above is sufficient to express the general idea.
The answer given by Narzul and Peter both are correct. You can implement any one. But, I know your next question will be how to implement that method in your code.
you can use Thread or Task class object to separate the process. So when one process is running then other process can perform their taks at that time. There are two process in your login. The first one is send the file to the printer and the second one is the show dialog for 30 seconds and then delete the file. You should create the another thread to invoke the any one of the process so other process can perform asynchronously.
1st: make the seperate process for Print file.
Task waitfordelete = Task.Run(() =>
{
PrintFactory.sendTextToLPT1(s);
});
this.Hide();
omg = new image();
omg.ShowDialog();
this.Show();
2nd: make the seperate process for show dialog and delete the file. But, I think you may get the error in this method. You cannot change the UI from other thread
Task waitfordelete = Task.Run(() =>
{
Dispatcher.Invoke(() => this.ShowSplashScreen());
});
PrintFactory.sendTextToLPT1(s);
private void ShowSplashScreen()
{
this.Hide();
omg = new image();
omg.ShowDialog();
this.Show();
}
if you don't want to use the thread or task then just simply handle the close event of Image form
this.Hide();
omg = new image();
omg.Show();
PrintFactory.sendTextToLPT1(s);
omg.FormClosed += (object sender, EventArgs e) => {
File.Delete(Path.Combine(Application.StartupPath, Path.GetFileName(img_path.Text));
this.Show();
};
and modify the code in timer_tick event in Image form and add the this.Close() after delete file statement.
void timer1_Elapsed(object sender, ElapsedEventArgs e)
{
....
//File.Delete(Path.Combine(#"\\bin\Debug", Filename)); comment this line
this.Close();
}
Another hidden question I have found here. here i cannot pass the old string file name with extension to this form.. Any ways please help me out
void timer1_Elapsed(object sender, ElapsedEventArgs e)
{
//delete the file using "filePath"
string Filename = img_path.Text; // here i cannot pass the old string file name with extension to this form.. Any ways please help me out
for that, you can create the property in Image class and assign the file name from the parent form.
Image omg = new Image()
omg.FileName = Path.Combine(Application.StartupPath, Path.GetFileName(img_path.Text));
omg.Show();
and the property in Image form will be created like this
public class Image : Form
{
public string FileName { get; set; }
public Image()
{
}
void timer1_Elapsed(object sender, ElapsedEventArgs e)
{
....
File.Delete(Path.Combine(Application.StartupPath, this.Filename));
this.Close();
}
}
NOTE: Use the Application.StartupPath istead of \\bin\debug
While i am trying to save Image getting this error
A generic error occurred in GDI+
I searched for this error and checked write permissions for this folder ,and also checked that image file is not in use by anything else (including my code) But While I am trying to save Image still getting same error,Where is the mistake
public partial class AdsMaster : Form
{
OpenFileDialog ofd=null;
public AdsMaster()
{
InitializeComponent();
}
private void browseButton_Click(object sender, EventArgs e)
{
ofd = new OpenFileDialog();
ofd.Filter = "image files|*.jpg;*.jpeg;*.gif;*.png;*.bmp";
DialogResult dr = new DialogResult();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Image img = new Bitmap(ofd.FileName);//create the bitmap
string imgName = ofd.SafeFileName;
txtImagePath.Text = imgName;
pictureBox1.Image = img.GetThumbnailImage(350, 350, null, new IntPtr());
ofd.RestoreDirectory = true;
img.Dispose();
}
}
private void saveImage_Click(object sender, EventArgs e)
{
String str = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string path = str + "\\Image\\";
Image img = new Bitmap(ofd.FileName);
string imgName = ofd.SafeFileName;
try
{
img.Save(path + imgName); //getting error at this line
MessageBox.Show("Image is saved");
img.Dispose(); // dispose of your image
}
catch(Exception err)
{
MessageBox.Show(err.Message.ToString());
}
}
}
I think the problem here may be due to the fact that a lock is placed on the original image when you call
Image img = new Bitmap(ofd.FileName);
The following should do the trick
private void saveImage_Click(object sender, EventArgs e)
{
string str = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string path = str + "\\Image\\";
string imgName = ofd.SafeFileName;
try
{
File.Copy(ofd.FileName, path + imgName);
MessageBox.Show("Image is saved");
}
catch (Exception err)
{
MessageBox.Show(err.Message.ToString());
}
}
I resolve this error by changing the file name and path to where the file is stored.
You needs to check either one of them-
1- FileName should be different/ should not get matched with other files name which have been already present on that location where new file/image you want to store.
2- change the (save ) location of the new file from operating system drive.
try to avoid to store the new file/Image on a drive on which operating system has been already installed.
Below code works for me
IWebdriver driver;
driver = new ChromeDriver("G:\\Selenium_Csharp\\Jar\\chromedriver_win32");
driver.Navigate().GoToUrl("http://www.gmail.com");
driver.Manage().Window.Maximize();
Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
ss.SaveAsFile("e:\\pande", System.Drawing.Imaging.ImageFormat.Jpeg);