1

我正在使用以下代码获取 wpf 中图像的源代码(图像类型为System.Windows.Controls.Image)。我想用原始扩展名将此图像存储到磁盘,可以吗?

System.drawing.image提供保存方法有类似的东西System.windows.controls.image吗?

Image image=new Image();
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(openFileDlg.FileName);
bitmap.EndInit();               
image.Source = bitmap;                
4

1 回答 1

2

看看RenderTargetBitmapBitmapEncoder类。

以下实用程序类允许您Image根据选择的格式将您的光栅图形图像保存为:

public static class VisualToImg
{

    static VisualToImg()
    {
        DPI = 96;
        PixelFormat = PixelFormats.Default;
    }

    public enum eImageFormat
    { Bitmap, Png, Gif, Jpeg, Tiff, Wmp }

    static public bool SaveAs(FrameworkElement element, String filePath,
        eImageFormat imageFormat)
    {
        switch (imageFormat)
        {
            case eImageFormat.Bitmap:
                return SaveUsingEncoder(element, filePath, new BmpBitmapEncoder());
            case eImageFormat.Gif:
                return SaveUsingEncoder(element, filePath, new GifBitmapEncoder());
            case eImageFormat.Jpeg:
                return SaveUsingEncoder(element, filePath, new JpegBitmapEncoder());
            case eImageFormat.Png:
                return SaveUsingEncoder(element, filePath, new PngBitmapEncoder());
            case eImageFormat.Tiff:
                return SaveUsingEncoder(element, filePath, new TiffBitmapEncoder());
            case eImageFormat.Wmp:
                return SaveUsingEncoder(element, filePath, new WmpBitmapEncoder());
        }

        return false;
    }

    static public double DPI
    { get; set; }

    static public PixelFormat PixelFormat
    { get; set; }

    static private bool SaveUsingEncoder(FrameworkElement visual, string filePath,
        BitmapEncoder encoder)
    {
        try
        {
            RenderTargetBitmap bmp = new RenderTargetBitmap((int)visual.ActualWidth,
                (int)visual.ActualHeight, DPI, DPI, PixelFormat);

            bmp.Render(visual);
            encoder.Frames.Add(BitmapFrame.Create(bmp));

            using (var stream = File.Create(filePath))
            { encoder.Save(stream); }

            return true;
        }
        catch (Exception)
        { return false; }
    }

}

你可以用它来保存你的Image或任何其他FrameworkElement

VisualToImg.SaveAs(image, "image1.png", VisualToImg.eImageFormat.Png);
VisualToImg.SaveAs(image, "image2.bmp", VisualToImg.eImageFormat.Bitmap);
VisualToImg.SaveAs(image, "image3.jpeg", VisualToImg.eImageFormat.Jpeg);
于 2012-06-26T08:48:49.090 回答