Converting image with OpenfileDialog

754 Views Asked by At

I need help with this code. I want to create basic image convert program but this program is not working? What am I doing wrong. Thanks for answers.

private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog file = new OpenFileDialog();
        file.ShowDialog();

        string DosyaYolu = file.FileName;
        string DosyaAdi = file.SafeFileName;

        if (file.ShowDialog() == DialogResult.OK) 
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(DosyaYolu);
            image.Save(DosyaYolu, System.Drawing.Imaging.ImageFormat.Png);
        }
1

There are 1 best solutions below

0
On

You choose the wrong target path to save the new image to. Also you invoked the ShowDialog() twice, which is not necessary. The following code will save the new file with the same name but a different extension.

var dialog = new OpenFileDialog();

if (dialog.ShowDialog() == DialogResult.OK)
{
    string sourceFile = dialog.FileName;
    string targetFile = Path.ChangeExtension(sourceFile, "png");

    Image image = Image.FromFile(sourceFile);

    image.Save(targetFile, ImageFormat.Png);
}