private void SetClipboardMetafile(MemoryStream ms) { using var metafile = new System.Drawing.Imaging.Metafile(ms); var emfHandle = metafile.GetHenhmetafile(); if (emfHandle.Equals(IntPtr.Zero)) { return; } var emfCloneHandle = Win32.CopyEnhMetaFile(emfHandle, IntPtr.Zero); if (emfCloneHandle.Equals(IntPtr.Zero)) { return; } try { if (Win32.OpenClipboard(IntPtr.Zero) && Win32.EmptyClipboard()) { Win32.SetClipboardData(Win32.CF_ENHMETAFILE, emfCloneHandle); Win32.CloseClipboard(); } } finally { Win32.DeleteEnhMetaFile(emfHandle); } }
void ConvertToWMF(Stream emfStream, Stream wmfStream) { const int MM_ANISOTROPIC = 8; System.Drawing.Imaging.Metafile mf = new System.Drawing.Imaging.Metafile(emfStream); System.Drawing.Imaging.Metafile mf2 = new System.Drawing.Imaging.Metafile(@"c:\trash\test.emf"); int handle = mf.GetHenhmetafile().ToInt32(); int handle2 = mf2.GetHenhmetafile().ToInt32(); int bufferSize = GdipEmfToWmfBits(handle, 0, null, MM_ANISOTROPIC, EmfToWmfBitsFlags.EmfToWmfBitsFlagsIncludePlaceable); byte[] buf = new byte[bufferSize]; GdipEmfToWmfBits(handle, bufferSize, buf, MM_ANISOTROPIC, EmfToWmfBitsFlags.EmfToWmfBitsFlagsIncludePlaceable); wmfStream.Write(buf, 0, bufferSize); }
public static void CopyXAMLStreamToWmfClipBoard(Visual visual, Window clipboardOwnerWindow) { // http://xamltoys.codeplex.com/ try { var drawing = Utility.GetDrawingFromXaml(visual); var bounds = drawing.Bounds; Console.WriteLine("Drawing Bounds: {0}", bounds); MemoryStream wmfStream = new MemoryStream(); using (var g = CreateEmf(wmfStream, bounds)) Utility.RenderDrawingToGraphics(drawing, g); wmfStream.Position = 0; System.Drawing.Imaging.Metafile metafile = new System.Drawing.Imaging.Metafile(wmfStream); IntPtr hEMF, hEMF2; hEMF = metafile.GetHenhmetafile(); // invalidates mf if (!hEMF.Equals(new IntPtr(0))) { hEMF2 = NativeMethods.CopyEnhMetaFile(hEMF, new IntPtr(0)); if (!hEMF2.Equals(new IntPtr(0))) { if (NativeMethods.OpenClipboard(((IWin32Window)clipboardOwnerWindow.OwnerAsWin32()).Handle)) { if (NativeMethods.EmptyClipboard()) { NativeMethods.SetClipboardData(14 /*CF_ENHMETAFILE*/, hEMF2); NativeMethods.CloseClipboard(); } } } NativeMethods.DeleteEnhMetaFile(hEMF); } } catch (Exception e) { MessageBox.Show(e.ToString()); } }
/// <summary> /// Метод конвертирует исходный графический файл в wmetafile /// и создает строку для вставки в RTF-документ /// wmetafile т.к. его поддерживает большинство RTF редакторов /// </summary> private static StringBuilder BitmapToRtfImage(Image image) { StringBuilder sb = new StringBuilder(); MemoryStream memory = null; System.Drawing.Imaging.Metafile metaFile = null; try { memory = new MemoryStream(); using (Graphics graphics = Graphics.FromImage(image)) { IntPtr ptr = graphics.GetHdc(); metaFile = new System.Drawing.Imaging.Metafile(memory, ptr); graphics.ReleaseHdc(ptr); } using (Graphics graphics = Graphics.FromImage(metaFile)) { graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height)); } IntPtr metaPtr = metaFile.GetHenhmetafile(); // указатель на метафайл uint bufferSize = NativeMethods.GdipEmfToWmfBits(metaPtr, 0, null, MM_ANISOTROPIC, NativeMethods.EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); // получаем размер массива byte[] buffer = new byte[bufferSize]; // здесь хранится метафайл NativeMethods.GdipEmfToWmfBits(metaPtr, bufferSize, buffer, MM_ANISOTROPIC, NativeMethods.EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); //копируем файл в буфер NativeMethods.DeleteEnhMetaFile(metaPtr);//удаление метафайла byte[] block; int blockSize = 0x100000; int bufferBytesToRead = buffer.Length; int currentBufferPosition = 0; // копируем байты метафайла в StringBuilder попутно переводя в правильный текстовый формат while (bufferBytesToRead > blockSize) { block = new byte[blockSize]; Buffer.BlockCopy(buffer, currentBufferPosition, block, 0, blockSize); currentBufferPosition += blockSize; bufferBytesToRead -= blockSize; sb.Append(BitConverter.ToString(block, 0).Replace("-", string.Empty)); } if (bufferBytesToRead > 0) { block = new byte[bufferBytesToRead]; Buffer.BlockCopy(buffer, currentBufferPosition, block, 0, bufferBytesToRead); sb.Append(BitConverter.ToString(block, 0).Replace("-", string.Empty)); } //return sb.ToString(); } finally { if (metaFile != null) metaFile.Dispose(); if (memory != null) memory.Close(); } return sb; }
/// <summary> /// Wraps the image in an Enhanced Metafile by drawing the image onto the /// graphics context, then converts the Enhanced Metafile to a Windows /// Metafile, and finally appends the bits of the Windows Metafile in HEX /// to a string and returns the string. /// </summary> /// <param name="_image"></param> /// <returns> /// A string containing the bits of a Windows Metafile in HEX /// </returns> private string GetRtfImage(Image _image) { StringBuilder _rtf = null; // Used to store the enhanced metafile System.IO.MemoryStream _stream = null; // Used to create the metafile and draw the image Graphics _graphics = null; // The enhanced metafile System.Drawing.Imaging.Metafile _metaFile = null; // Handle to the device context used to create the metafile IntPtr _hdc; try { _rtf = new StringBuilder(); _stream = new System.IO.MemoryStream(); // Get a graphics context from the RichTextBox using (_graphics = this.CreateGraphics()) { // Get the device context from the graphics context _hdc = _graphics.GetHdc(); // Create a new Enhanced Metafile from the device context _metaFile = new System.Drawing.Imaging.Metafile(_stream, _hdc); // Release the device context _graphics.ReleaseHdc(_hdc); } // Get a graphics context from the Enhanced Metafile using (_graphics = Graphics.FromImage(_metaFile)) { // Draw the image on the Enhanced Metafile _graphics.DrawImage(_image, new Rectangle(0, 0, _image.Width, _image.Height)); } // Get the handle of the Enhanced Metafile IntPtr _hEmf = _metaFile.GetHenhmetafile(); // A call to EmfToWmfBits with a null buffer return the size of the // buffer need to store the WMF bits. Use this to get the buffer // size. uint _bufferSize = GdipEmfToWmfBits(_hEmf, 0, null, MM_ANISOTROPIC, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); // Create an array to hold the bits byte[] _buffer = new byte[_bufferSize]; // A call to EmfToWmfBits with a valid buffer copies the bits into the // buffer an returns the number of bits in the WMF. uint _convertedSize = GdipEmfToWmfBits(_hEmf, _bufferSize, _buffer, MM_ANISOTROPIC, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); // Append the bits to the RTF string for (int i = 0; i < _buffer.Length; ++i) { _rtf.Append(String.Format("{0:X2}", _buffer[i])); } return(_rtf.ToString()); } finally { if (_graphics != null) { _graphics.Dispose(); } if (_metaFile != null) { _metaFile.Dispose(); } if (_stream != null) { _stream.Close(); } } }
private string ConvertToMetafileHexDataString(Stream imageStream) { MemoryStream metafileStream = new MemoryStream(); // Get the graphics to write image on the metafile System.Drawing.Graphics graphics = System.Drawing.Graphics.FromHwnd(IntPtr.Zero); // Create the empty metafile System.Drawing.Imaging.Metafile metafile = new System.Drawing.Imaging.Metafile(metafileStream, graphics.GetHdc(), System.Drawing.Imaging.EmfType.EmfOnly); // Release HDC graphics.ReleaseHdc(); // Create the graphics for metafile destination System.Drawing.Graphics graphicsTarget = System.Drawing.Graphics.FromImage(metafile); // Create bitmap from the image source stream System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(imageStream); // Draw the bitmap image to the metafile graphicsTarget.DrawImage(bitmap, System.Drawing.Point.Empty); // Dispose graphics target graphicsTarget.Dispose(); // Move to the start position metafileStream.Position = 0; // Create the enhance metafile from metafile stream what we rendered from the bitmap image System.Drawing.Imaging.Metafile enhanceMetafile = new System.Drawing.Imaging.Metafile(metafileStream); // Get the enhance metafile handle from the enhance metafile IntPtr hdc = UnsafeNativeMethods.CreateCompatibleDC(new HandleRef(this, IntPtr.Zero)); IntPtr hEnhanceMetafile = enhanceMetafile.GetHenhmetafile(); // Convert the enhance metafile to the windows metafile with Win32 GDI uint windowsMetafileSize = UnsafeNativeMethods.GetWinMetaFileBits(hEnhanceMetafile, 0, null, /*MapMode:MM_ANISOTROPIC*/8, hdc); Byte[] windowsMetafileBytes = new Byte[windowsMetafileSize]; UnsafeNativeMethods.GetWinMetaFileBits(hEnhanceMetafile, windowsMetafileSize, windowsMetafileBytes, /*MapMode:MM_ANISOTROPIC*/8, hdc); // Dispose metafile and metafile stream metafile.Dispose(); metafileStream.Dispose(); // return the windows metafile hex data string return ConvertToImageHexDataString(windowsMetafileBytes); }