Save the image associated with an Image control to disk

Asked

Viewed 24 times

0

Let’s assume an image is loaded for control Image of the following example ...

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

What code is required to associate to the button button in order to provide a window that performs the "Guard As ..." from image to disk?

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 has the name foresight.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.