Mint Source

Code snippets, tips, and tricks…

Posts Tagged ‘Word

Copy Image Scaled

leave a comment »

When an image is pasted into MS Word from the Windows clipboard, often the first task is to shrink it to the desired size. The full size image is not lost however, as zooming in on the document, printing, or enlarging the image still shows a high resolution image.

When providing a ‘Copy’ feature within your application it is possible for the image to be placed on the clipboard along with scaling information using a Metafile. When pasting into MS Word the image is already scaled as defined in the Metafile without reducing the resolution of the image.

The method below will create a Metafile given a RenderTargetBitmap commonly used in WPF applications and a scale factor.

/// <summary>
/// Create an image meta file for the supplied bitmap.
/// The meta file specifies the scaling that should be applied to the image.
/// The meta file can be placed on the clipboard and the scaled image will
/// appear when the meta file is pasted into applications such as MS Word.
/// </summary>
private static Metafile CreateMetaFile(RenderTargetBitmap rtb, double scale)
    Metafile metaFile = null;
    using (Graphics offScreenDeviceContext = Graphics.FromHwndInternal(IntPtr.Zero))
        metaFile = new Metafile(new MemoryStream(), offScreenDeviceContext.GetHdc(), EmfType.EmfOnly);
        using (Graphics aGraphic = Graphics.FromImage(metaFile))
            System.Drawing.Image image = RenderTargetBitmapToImage(rtb);
            aGraphic.SmoothingMode = SmoothingMode.HighQuality;
            aGraphic.InterpolationMode = InterpolationMode.High;
            aGraphic.DrawImage(image, new RectangleF(0, 0,
                              (image.PhysicalDimension.Width*(float) scale),
                              (image.PhysicalDimension.Height*(float) scale)));
    return metaFile;

The helper function below will create an Image from a RenderTargetBitmap.

/// <summary>
/// Convert a <see cref="RenderTargetBitmap"/> to a <see cref="System.Drawing.Image"/>
/// </summary>
private static System.Drawing.Image RenderTargetBitmapToImage(RenderTargetBitmap rtb)
    MemoryStream ms = new MemoryStream();
    BmpBitmapEncoder bbe = new BmpBitmapEncoder();
    BitmapFrame frame = BitmapFrame.Create(rtb);


    return System.Drawing.Image.FromStream(ms);

Written by Andy Lamb

January 26, 2013 at 00:22

Posted in .NET

Tagged with , , , , ,