0

A WPF button opens a file dialog to open an image and display it in an image control

I want to use another button event to open the image in another app, is this possible?

Nitesh
  • 39
  • 6

1 Answers1

2

Try this:

Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
    byte[] data;
    JpegBitmapEncoder encoder = new JpegBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(imagebox.Source as BitmapImage));
    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
    {
        encoder.Save(ms);
        data = ms.ToArray();
    }

    if (data != null)
    {
        string filename = dlg.FileName;
        System.IO.File.WriteAllBytes(filename, data);
    }
}

If you don't want to use a dialog you could just specify the file name in a string variable:

byte[] data;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(imagebox.Source as BitmapImage));
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
    encoder.Save(ms);
    data = ms.ToArray();
}

if (data != null)
{ 
    const string filename = @"c:\test\1.jpg";
    System.IO.File.WriteAllBytes(filename, data);
}
mm8
  • 163,881
  • 10
  • 57
  • 88
  • Note that instead of encoding to a MemoryStream and then writing the MemoryStream's buffer to a file, you could as well directly encode into a FileStream. – Clemens Mar 24 '17 at 11:50
  • @mm8 - this done the trick, thank you. However, I would like it to overwrite any existing files with the same name, is this possible? – Nitesh Mar 28 '17 at 19:04
  • The WriteAllBytes method should overwrite the file if it exists by default. So my code should work as is. – mm8 Mar 28 '17 at 19:08
  • @mm8 I think I have this working, but if I wanted 'encoder.Frames.Add...' to allow null values is this possible – Nitesh Mar 30 '17 at 12:52
  • I don't understand what you mean but it makes no sense to add null values to the Frames collection of a BitmapEncoder. – mm8 Mar 30 '17 at 14:14