Save the image associated with an Image control to disk

0

Let's suppose that an image is loaded into the Image control of the following example ...

<Button x:Name="button" Content="Button" />
<Image x:Name="image" />

What code do I need to associate with the button button to pop up a " Save As ... " operation from image to disk?     

asked by anonymous 06.01.2017 / 18:50

1 answer

0

This was the solution found by me:

private void guardarImagemDiscoDoPreviewButton_Click(object sender, RoutedEventArgs e)
{
    //Save As Dialog ...
    Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
    dlg.FileName = "imagem";
    dlg.DefaultExt = ".jpg";
    dlg.Filter = "Imagem JPEG|*.jpg";
    Nullable<bool> result = dlg.ShowDialog();

    //Converter source da imagem num byte array
    byte[] ImageData = getJPGFromImageControl(previewImage.Source as BitmapImage);

    //Gravar a imagem no disco
    using (Image image = Image.FromStream(new MemoryStream(ImageData)))
    {
        image.Save(dlg.FileName, ImageFormat.Jpeg);  // Ou Png ...
    }
}

public byte[] getJPGFromImageControl(BitmapImage imageC)
{
    MemoryStream memStream = new MemoryStream();
    JpegBitmapEncoder encoder = new JpegBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(imageC));
    encoder.Save(memStream);
    return memStream.ToArray();
}

In this case the Image control is preview .

    
13.01.2017 / 12:59