private IntPtr GetImage() { if (OleObject == null) { return(IntPtr.Zero); } IntPtr hDC = Natives.CreateDC("DISPLAY", null, null, IntPtr.Zero); Metafile mf = new Metafile(hDC, EmfType.EmfOnly); using (var g = Graphics.FromImage(mf)) { OleObject.Draw(g); } IntPtr _hEmf = mf.GetHenhmetafile(); uint _bufferSize = Natives.GdipEmfToWmfBits(_hEmf, 0, null, Natives.MM_ANISOTROPIC, Natives.EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); byte[] _buffer = new byte[_bufferSize]; Natives.GdipEmfToWmfBits(_hEmf, _bufferSize, _buffer, Natives.MM_ANISOTROPIC, Natives.EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); IntPtr hwmf = Natives.SetMetaFileBitsEx(_bufferSize, _buffer); var pic = Marshal.AllocHGlobal(20); Marshal.WriteInt32(pic, 0, 8 /*MM_ANISOTROPIC*/); Marshal.WriteInt32(pic, 4, 20000); Marshal.WriteInt32(pic, 8, 20000); Marshal.WriteIntPtr(pic, 12, hwmf); return(pic); }
static public bool SaveEnhMetafileToFile(Metafile mf) { if (mf == null) { return(false); } bool bResult = false; IntPtr hEMF; hEMF = mf.GetHenhmetafile(); // invalidates mf if (!hEMF.Equals(new IntPtr(0))) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Extended Metafile (*.emf)|*.emf"; sfd.DefaultExt = ".emf"; if (sfd.ShowDialog() == DialogResult.OK) { StringBuilder temp = new StringBuilder(sfd.FileName); CopyEnhMetaFile(hEMF, temp); } DeleteEnhMetaFile(hEMF); } return(bResult); }
public void CopyToClipboard() { Metafile mf = null; try { Graphics g = CreateGraphics(); IntPtr hdc = g.GetHdc(); mf = new Metafile(hdc, EmfType.EmfPlusDual); g.ReleaseHdc(hdc); g.Dispose(); g = Graphics.FromImage(mf); g.FillRectangle(new SolidBrush(this.BackColor), 0, 0, Width, Height); g.DrawRectangle(new Pen(Color.Gray), 0, 0, Width - 1, Height - 1); DoPaint(g); g.Dispose(); IntPtr hwnd = this.Handle; if (OpenClipboard(hwnd)) { EmptyClipboard(); IntPtr hemf = mf.GetHenhmetafile(); SetClipboardData(14, hemf); //CF_ENHMETAFILE=14 CloseClipboard(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public bool PutEnhMetafileOnClipboard(Control control, Metafile metaFile) { var hWnd = control.Handle; var bResult = false; var handleForEnhancedMetaFile = metaFile.GetHenhmetafile(); if (handleForEnhancedMetaFile.Equals(new IntPtr(0))) { return(false); } var copyHandle = CopyEnhMetaFile(handleForEnhancedMetaFile, new IntPtr(0)); if (!copyHandle.Equals(new IntPtr(0))) { if (OpenClipboard(hWnd)) { if (EmptyClipboard()) { var hRes = SetClipboardData(CF_ENHMETAFILE, copyHandle); bResult = hRes.Equals(copyHandle); CloseClipboard(); } } } DeleteEnhMetaFile(handleForEnhancedMetaFile); return(bResult); }
public static void CopyEmf(ZedGraphControl zedGraphControl) { Metafile mf = zedGraphControl.MasterPane.GetMetafile(); bool success = false; if (OpenClipboard(zedGraphControl.Handle)) { if (EmptyClipboard()) { success = true; SetClipboardData(14 /*CF_ENHMETAFILE*/, mf.GetHenhmetafile()); // TODO (nicksh): It would be nice if we also set the CF_BITMAP CloseClipboard(); } } if (zedGraphControl.IsShowCopyMessage) { if (success) { MessageBox.Show(zedGraphControl, "Metafile image copied to clipboard"); } else { MessageBox.Show(zedGraphControl, "Unable to copy metafile image to the clipboard."); } } }
/// <summary> /// Save image metafile /// </summary> /// <param name="FileName">File name</param> public void SaveMetafile ( string FileName ) { // Get a handle to the metafile var MetafileHandle = Metafile.GetHenhmetafile(); // allocate character table buffer in global memory (two bytes per char) var CharBuffer = Marshal.AllocHGlobal(2 * FileName.Length + 2); // move file name inclusing terminating zer0 to the buffer for (var Index = 0; Index < FileName.Length; Index++) { Marshal.WriteInt16(CharBuffer, 2 * Index, (short)FileName[Index]); } Marshal.WriteInt16(CharBuffer, 2 * FileName.Length, 0); // Export metafile to an image file CopyEnhMetaFile(MetafileHandle, CharBuffer); // free local buffer Marshal.FreeHGlobal(CharBuffer); }
// Metafile mf is set to a state that is not valid inside this function. public static bool PutEnhMetafileOnClipboard(IntPtr hWnd, Metafile mf) { var bResult = false; var hEMF = mf.GetHenhmetafile(); if (!hEMF.Equals(new IntPtr(0))) { var hEMF2 = CopyEnhMetaFile(hEMF, new IntPtr(0)); if (!hEMF2.Equals(new IntPtr(0))) { if (OpenClipboard(hWnd)) { // even if the clipboard is opened with the same owner and not emptied, this still seems to overwrite any previous data added by .net //If OpenClipboard(GetClipboardOwner()) Then if (EmptyClipboard()) { var hRes = SetClipboardData(14, hEMF2); bResult = hRes.Equals(hEMF2); CloseClipboard(); } } } DeleteEnhMetaFile(hEMF); } return(bResult); }
// Metafile mf is set to a state that is not valid inside this function. static internal bool PutEnhMetafileOnClipboard(IntPtr hWnd, Metafile mf) { bool bResult = false; IntPtr hEMF, hEMF2; hEMF = mf.GetHenhmetafile(); // invalidates mf if (!hEMF.Equals(new IntPtr(0))) { hEMF2 = CopyEnhMetaFile(hEMF, null); if (!hEMF2.Equals(new IntPtr(0))) { if (OpenClipboard(hWnd)) { if (EmptyClipboard()) { IntPtr hRes = SetClipboardData(14 /*CF_ENHMETAFILE*/, hEMF2); bResult = hRes.Equals(hEMF2); CloseClipboard(); } } } DeleteEnhMetaFile(hEMF); } return(bResult); }
/// <summary> /// Copies the given <see cref="T:System.Drawing.Imaging.MetaFile" /> to the clipboard. /// The given <see cref="T:System.Drawing.Imaging.MetaFile" /> is set to an invalid state and deleted inside this function. /// </summary> public static bool AddEnhMetafileToClipboard(Metafile metafile) { if (metafile == null) { throw new ArgumentNullException("metafile"); } bool result = false; IntPtr hEMF, hEMF2; hEMF = metafile.GetHenhmetafile(); // invalidates metafile if (!hEMF.Equals(IntPtr.Zero)) { try { hEMF2 = CopyEnhMetaFile(hEMF, null); if (!hEMF2.Equals(IntPtr.Zero)) { IntPtr hRes = SetClipboardData(CF_ENHMETAFILE, hEMF2); result = hRes.Equals(hEMF2); } } finally { DeleteEnhMetaFile(hEMF); } } return(result); }
public static void SaveAsEmf(Metafile me, string fileName) { /* http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/12a1c749-b320-4ce9-aff7-9de0d7fd30ea * How to save or serialize a Metafile: Solution found * by : SWAT Team member _1 * Date : Friday, February 01, 2008 1:38 PM */ int enfMetafileHandle = me.GetHenhmetafile().ToInt32(); int bufferSize = GetEnhMetaFileBits(enfMetafileHandle, 0, null); // Get required buffer size. byte[] buffer = new byte[bufferSize]; // Allocate sufficient buffer if (GetEnhMetaFileBits(enfMetafileHandle, bufferSize, buffer) <= 0) // Get raw metafile data. { throw new SystemException("Fail"); } FileStream ms = File.Open(fileName, FileMode.Create); ms.Write(buffer, 0, bufferSize); ms.Close(); ms.Dispose(); if (!DeleteEnhMetaFile(enfMetafileHandle)) //free handle { throw new SystemException("Fail Free"); } }
/// <summary> /// Delete image metafile. /// </summary> public void DeleteMetafile() { // Get a handle to the metafile var MetafileHandle = Metafile.GetHenhmetafile(); // Delete the metafile from memory DeleteEnhMetaFile(MetafileHandle); }
/// <summary> /// Convierte la imagen en un Enhanced Metafile desde un Windows Metafile y devuelve los bits /// del Windows Metafile en hexadecimal /// </summary> private string GetRtfImage(Image _image) { StringBuilder sbRtf = null; MemoryStream stmStream = null; // Almacena el enhanced metafile Graphics grpGraphics = null; // Utilizado para crear el metafile y dibujar la imagen Metafile mfMetafile = null; // El enhanced metafile IntPtr hndDC; // Manejador al contexto del dispositivo utilizado para crear el metafile try { // Inicializa las variables sbRtf = new StringBuilder(); stmStream = new MemoryStream(); // Obtiene el contexto gráfico del RichTextBox using (grpGraphics = CreateGraphics()) { // Obtiene el contexto de dispositivo a partir del contexto gráfico hndDC = grpGraphics.GetHdc(); // Crea un nuevo Enhanced Metafile desde el contexto de dispositivo mfMetafile = new Metafile(stmStream, hndDC); // Libera el contexto del dispositivo grpGraphics.ReleaseHdc(hndDC); } // Obtiene el contexto gráfico del Enhanced Metafile using (grpGraphics = Graphics.FromImage(mfMetafile)) { // Dibuja la imagen sobre el Enhanced Metafile grpGraphics.DrawImage(_image, new Rectangle(0, 0, _image.Width, _image.Height)); } // Obtiene el manejador del Enhanced Metafile IntPtr _hEmf = mfMetafile.GetHenhmetafile(); // Llama a EmfToWmfBits con un buffer nulo para obtener el tamaño necesario para almacenar // los bits del WMF uint _bufferSize = GdipEmfToWmfBits(_hEmf, 0, null, MM_ANISOTROPIC, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); // Crea un array para mantener los bits byte[] _buffer = new byte[_bufferSize]; // Llama a EmfToWmfBits con un buffer correcto para copiar los en el buffer // y devolver el número de bits del WMF uint _convertedSize = GdipEmfToWmfBits(_hEmf, _bufferSize, _buffer, MM_ANISOTROPIC, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); // Añade los bits a la cadena RTF en hexadecimal for (int i = 0; i < _buffer.Length; i++) { sbRtf.Append(String.Format("{0:X2}", _buffer[i])); } // Devuelve la cadena con la imagen return(sbRtf.ToString()); } finally { if (mfMetafile != null) { mfMetafile.Dispose(); } if (stmStream != null) { stmStream.Close(); } } }
public static PICTDESC FromMetafile(Metafile metafile) { PICTDESC desc = new PICTDESC { picType = PICTYPE.ENHMETAFILE }; desc.Union.emf.hemf = metafile.GetHenhmetafile(); return(desc); }
private void ExportEmf(Metafile metafile) { Logger.Info("ExportEmf: exporting..."); IntPtr handle = metafile.GetHenhmetafile(); PercentCompleted = 50; Logger.Info("ExportEmf, handle: {0}", handle); Bovender.Unmanaged.Pinvoke.CopyEnhMetaFile(handle, FileName); PercentCompleted = 100; }
public void WriteEnhMetafile(Stream stream) { m_graphics.Dispose(); IntPtr h = m_metafile.GetHenhmetafile(); uint size = GetEnhMetaFileBits(h, 0, null); byte[] data = new byte[size]; GetEnhMetaFileBits(h, size, data); stream.Write(data, 0, (int)size); }
/// <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> // ReSharper disable UnusedMember.Local public static string GetRtfImage(Image image) { // Allows the x-coordinates and y-coordinates of the metafile to be adjusted // independently const int mmAnisotropic = 8; var rtf = new StringBuilder(); var stream = new MemoryStream(); // Get a graphics context from the RichTextBox Graphics graphics; Metafile metaFile; using (graphics = Graphics.FromHwnd(new IntPtr(0))) { // Get the device context from the graphics context var hdc = graphics.GetHdc(); // Create a new Enhanced Metafile from the device context metaFile = new Metafile(stream, hdc); // Release the device context graphics.ReleaseHdc(hdc); } // Get a graphics context from the Enhanced Metafile using (graphics = Graphics.FromImage(metaFile)) graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height)); // Get the handle of the Enhanced Metafile var 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. var bufferSize = NativeMethods.GdipEmfToWmfBits(hEmf, 0, null, mmAnisotropic, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); // Create an array to hold the bits var 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. NativeMethods.GdipEmfToWmfBits(hEmf, bufferSize, buffer, mmAnisotropic, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); // Append the bits to the RTF string foreach (var b in buffer) { rtf.Append(String.Format("{0:X2}", b)); } return(rtf.ToString()); }
private string GenerateImageRtf(Image image) { MemoryStream metaFileStream = null; Graphics graphics = null; Metafile metaFile = null; try { StringBuilder stringBuilder = new StringBuilder(); metaFileStream = new MemoryStream(); using (graphics = this.CreateGraphics()) { IntPtr hdc = graphics.GetHdc(); metaFile = new Metafile(metaFileStream, hdc); graphics.ReleaseHdc(hdc); } using (graphics = Graphics.FromImage(metaFile)) { graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height)); } IntPtr hMetaFile = metaFile.GetHenhmetafile(); // get size (buller = null) uint bufferSize = GdipEmfToWmfBits(hMetaFile, 0, null, MM_ANISOTROPIC, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); byte[] buffer = new byte[bufferSize]; // do copy (buffer != null, return ignored) GdipEmfToWmfBits(hMetaFile, bufferSize, buffer, MM_ANISOTROPIC, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); stringBuilder.Append(BitConverter.ToString(buffer).Replace("-", "")); return(stringBuilder.ToString()); } finally { if (graphics != null) { graphics.Dispose(); } if (metaFile != null) { metaFile.Dispose(); } if (metaFileStream != null) { metaFileStream.Close(); } } }
public void Static_GetMetafileHeader_IntPtr() { string filename = MetafileTest.WmfPlaceable; using (Metafile mf = new Metafile(filename)) { IntPtr hemf = mf.GetHenhmetafile(); Assert.IsTrue(hemf != IntPtr.Zero, "GetHenhmetafile"); Assert.Throws <ArgumentException> (() => Metafile.GetMetafileHeader(hemf)); } }
public static String GetRTFExEmoticon(int image_index, Color back_color, Graphics richtextbox) { StringBuilder result = new StringBuilder(); int width = ex_emotic[image_index].Img.Width; int height = ex_emotic[image_index].Img.Height; using (Bitmap bmp = new Bitmap(width, height)) { using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(back_color); g.DrawImage(ex_emotic[image_index].Img, new Point(0, 0)); result.Append(@"{\pict\wmetafile8\picw"); result.Append((int)Math.Round((width / richtextbox.DpiX) * 2540)); result.Append(@"\pich"); result.Append((int)Math.Round((height / richtextbox.DpiY) * 2540)); result.Append(@"\picwgoal"); result.Append((int)Math.Round((width / richtextbox.DpiX) * 1440)); result.Append(@"\pichgoal"); result.Append((int)Math.Round((height / richtextbox.DpiY) * 1440)); result.Append(" "); using (MemoryStream ms = new MemoryStream()) { IntPtr ptr = g.GetHdc(); using (Metafile meta = new Metafile(ms, ptr)) { g.ReleaseHdc(ptr); using (Graphics gfx = Graphics.FromImage(meta)) gfx.DrawImage(bmp, new Rectangle(0, 0, width, height)); ptr = meta.GetHenhmetafile(); uint size = GdipEmfToWmfBits(ptr, 0, null, 8, 0); byte[] buffer = new byte[size]; GdipEmfToWmfBits(ptr, (uint)buffer.Length, buffer, 8, 0); DeleteEnhMetaFile(ptr); foreach (byte b in buffer) { result.Append(String.Format("{0:x2}", b)); } result.Append("}"); buffer = null; } } } } return(result.ToString()); }
public void Static_GetMetafileHeader_IntPtr() { string filename = MetafileTest.getInFile(MetafileTest.WmfPlaceable); using (Metafile mf = new Metafile(filename)) { IntPtr hemf = mf.GetHenhmetafile(); Assert.IsTrue(hemf != IntPtr.Zero, "GetHenhmetafile"); Metafile.GetMetafileHeader(hemf); } }
internal static bool SaveEnhMetafileToFile(Metafile mf, string fileName) { var hEMF = mf.GetHenhmetafile(); if (!hEMF.Equals(new IntPtr(0))) { var tempName = new StringBuilder(fileName); CopyEnhMetaFile(hEMF, tempName); DeleteEnhMetaFile(hEMF); } return(false); }
internal override IntPtr GetHandleFromMetafile(Object data) { IntPtr hMetafile = IntPtr.Zero; Metafile metafile = data as Metafile; if (metafile != null) { // Get the Windows handle from the metafile object. hMetafile = metafile.GetHenhmetafile(); } return(hMetafile); }
// implementation byte[] GetBytes(Image img) { // use interop to get the metafile bits Metafile mf = img as Metafile; var enhMetafileHandle = mf.GetHenhmetafile().ToInt32(); var bufferSize = GetEnhMetaFileBits(enhMetafileHandle, 0, null); var buffer = new byte[bufferSize]; GetEnhMetaFileBits(enhMetafileHandle, bufferSize, buffer); // return bits return(buffer); }
static internal bool SaveEnhMetafileToFile(Metafile mf, string fileName) { bool bResult = false; IntPtr hEMF; hEMF = mf.GetHenhmetafile(); if (!hEMF.Equals(new IntPtr(0))) { StringBuilder tempName = new StringBuilder(fileName); CopyEnhMetaFile(hEMF, tempName); DeleteEnhMetaFile(hEMF); } return(bResult); }
// Metafile.GetHenhmetafile is just a wrapper of GdipGetHemfFromMetafile: // https://github.com/dotnet/runtime/blob/78c6505cffe2558b036fbe44cd27038affbb6cce/src/libraries/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Windows.cs#L379-L383 // and according to: // http://www.jose.it-berater.org/gdiplus/reference/flatapi/graphics/gdipgethemffrommetafile.htm // > GdipGetHemfFromMetafile: // > This method sets the Metafile object to an invalid state. The user is responsible for calling DeleteEnhMetafile, // > to delete the Windows handle. // If we want to get a native handle of Metafile object without invalidate the original Metafile object, we should // COPY the metafile instead: // Metafile.CopyMetaFile(string path); // var enhMetafileHandle = metafile_.CopyMetaFile(null); // Copy to memory. // Gdi32.DeleteEnhMetaFile(enhMetafileHandle); // Unfortunately, Metafile class doesn't provide a wrapper method for CopyMetaFileW function. // // Can we write an extension method like this? // public static IntPtr GetHenhmetafileEx(this Metafile metafile) // { // var handle = metafile.GetHenhmetafile(); // metafile = new Metafile(handle, false); // return handle; // } // [How can I get an extension method to change the original object?](https://stackoverflow.com/questions/2326734/how-can-i-get-an-extension-method-to-change-the-original-object) public static IntPtr GetMetafileHandle(ref Metafile metafile) { if (metafile == null) { throw new ArgumentNullException("metafile"); } var hEmf = metafile.GetHenhmetafile(); metafile = new Metafile(hEmf, true); return(hEmf); }
public static string GetEmbedImageString(Bitmap image) { Metafile metafile = null; float dpiX; float dpiY; using (Graphics g = Graphics.FromImage(image)) { IntPtr hDC = g.GetHdc(); metafile = new Metafile(hDC, EmfType.EmfOnly); g.ReleaseHdc(hDC); } using (Graphics g = Graphics.FromImage(metafile)) { g.DrawImage(image, 0, 0); dpiX = g.DpiX; dpiY = g.DpiY; } IntPtr _hEmf = metafile.GetHenhmetafile(); uint _bufferSize = GdipEmfToWmfBits(_hEmf, 0, null, MM_ANISOTROPIC, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); byte[] _buffer = new byte[_bufferSize]; GdipEmfToWmfBits(_hEmf, _bufferSize, _buffer, MM_ANISOTROPIC, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault); IntPtr hmf = SetMetaFileBitsEx(_bufferSize, _buffer); string tempfile = Path.GetTempFileName(); CopyMetaFile(hmf, tempfile); DeleteMetaFile(hmf); DeleteEnhMetaFile(_hEmf); var stream = new MemoryStream(); byte[] data = File.ReadAllBytes(tempfile); //File.Delete (tempfile); int count = data.Length; stream.Write(data, 0, count); string proto = @"{\rtf1{\pict\wmetafile8\picw" + (int)(((float)image.Width / dpiX) * 2540) + @"\pich" + (int)(((float)image.Height / dpiY) * 2540) + @"\picwgoal" + (int)(((float)image.Width / dpiX) * 1440) + @"\pichgoal" + (int)(((float)image.Height / dpiY) * 1440) + " " + BitConverter.ToString(stream.ToArray()).Replace("-", "") + "}}"; return(proto); }
/// <summary> /// Takes an image and writes it as an Image element to the Xml stream provided. /// </summary> private void GetImageAsXml(Image img, XmlTextWriter xml) { xml.WriteStartElement("Object"); xml.WriteAttributeString("guid", Guid.NewGuid().ToString("B")); xml.WriteStartElement("Position"); xml.WriteAttributeString("x", "0"); xml.WriteAttributeString("y", "0"); xml.WriteEndElement(); // end Position xml.WriteStartElement("Image"); xml.WriteAttributeString("backgroundImage", "true"); // Set size of image SizeF imageSize = GetSlideSize(img); xml.WriteAttributeString("width", (imageSize.Width).ToString()); xml.WriteAttributeString("height", (imageSize.Height).ToString()); // Write the image in the xml as Base64 xml.WriteStartElement("Data"); byte[] bits; if (img.RawFormat.Equals(ImageFormat.Emf) || img.RawFormat.Equals(ImageFormat.Wmf)) { // The image goes bad during serialization, so we have to clone it. Metafile mf = (Metafile)((Metafile)img).Clone(); IntPtr ptr = mf.GetHenhmetafile(); Debug.Assert(ptr != IntPtr.Zero, "Failed to get pointer to image."); uint size = GetEnhMetaFileBits(ptr, 0, null); bits = new byte[size]; uint numBits = GetEnhMetaFileBits(ptr, size, bits); mf.Dispose(); Debug.Assert(size == numBits, "Improper serialization of metafile!"); } else { MemoryStream imgMS = new MemoryStream(); img.Save(imgMS, System.Drawing.Imaging.ImageFormat.Jpeg); bits = imgMS.ToArray(); } xml.WriteBase64(bits, 0, bits.Length); xml.WriteEndElement(); // end Data xml.WriteEndElement(); // end Image xml.WriteEndElement(); // end Object }
private string method_2(Image image_0) { StringBuilder builder = null; MemoryStream stream = null; Graphics graphics = null; Metafile image = null; string str; try { builder = new StringBuilder(); stream = new MemoryStream(); using (graphics = base.CreateGraphics()) { IntPtr hdc = graphics.GetHdc(); image = new Metafile(stream, hdc); graphics.ReleaseHdc(hdc); } using (graphics = Graphics.FromImage(image)) { graphics.DrawImage(image_0, new Rectangle(0, 0, image_0.Width, image_0.Height)); } IntPtr henhmetafile = image.GetHenhmetafile(); uint num = GdipEmfToWmfBits(henhmetafile, 0, null, 8, (Enum5)0); byte[] buffer = new byte[num]; GdipEmfToWmfBits(henhmetafile, num, buffer, 8, (Enum5)0); for (int i = 0; i < buffer.Length; i++) { builder.Append(string.Format("{0:X2}", buffer[i])); } str = builder.ToString(); } finally { if (graphics != null) { graphics.Dispose(); } if (image != null) { image.Dispose(); } if (stream != null) { stream.Close(); } } return(str); }
private static string GetRtfImage(RichTextBox rtb, Image _image) { StringBuilder _rtf = null; MemoryStream _stream = null; Graphics _graphics = null; Metafile _metaFile = null; IntPtr _hdc; try { _rtf = new StringBuilder(); _stream = new MemoryStream(); using (_graphics = rtb.CreateGraphics()) { _hdc = _graphics.GetHdc(); _metaFile = new Metafile(_stream, _hdc); _graphics.ReleaseHdc(_hdc); } using (_graphics = Graphics.FromImage(_metaFile)) { _graphics.DrawImage(_image, new Rectangle(0, 0, _image.Width, _image.Height)); } IntPtr _hEmf = _metaFile.GetHenhmetafile(); uint _bufferSize = GdipEmfToWmfBits(_hEmf, 0, null, MM_ANISOTROPIC, EmfToWmfBitsFlagsDefault); byte[] _buffer = new byte[_bufferSize]; uint _convertedSize = GdipEmfToWmfBits(_hEmf, _bufferSize, _buffer, MM_ANISOTROPIC, EmfToWmfBitsFlagsDefault); 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(); } } }
public static void SaveMetafile(Metafile mf, Stream stream) { IntPtr henh = mf.GetHenhmetafile(); int size = GetEnhMetaFileBits(henh, 0, null); byte[] buffer = new byte[size]; if (GetEnhMetaFileBits(henh, size, buffer) <= 0) { throw new SystemException("GetEnhMetaFileBits"); } stream.Write(buffer, 0, buffer.Length); stream.Flush(); }
// Metafile mf is set to a state that is not valid inside this function. static public bool PutEnhMetafileOnClipboard( IntPtr hWnd, Metafile mf ) { bool bResult = false; IntPtr hEMF, hEMF2; hEMF = mf.GetHenhmetafile(); // invalidates mf if( ! hEMF.Equals( new IntPtr(0) ) ) { hEMF2 = CopyEnhMetaFile( hEMF, new IntPtr(0) ); if( ! hEMF2.Equals( new IntPtr(0) ) ) { if( OpenClipboard( hWnd ) ) { if( EmptyClipboard() ) { IntPtr hRes = SetClipboardData( 14 /*CF_ENHMETAFILE*/, hEMF2 ); bResult = hRes.Equals( hEMF2 ); CloseClipboard(); } } } DeleteEnhMetaFile( hEMF ); } return bResult; }
/// <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 MemoryStream _stream = null; // Used to create the metafile and draw the image Graphics _graphics = null; // The enhanced metafile Metafile _metaFile = null; // Handle to the device context used to create the metafile IntPtr _hdc = default(IntPtr); try { _rtf = new StringBuilder(); _stream = new MemoryStream(); // Get a graphics context from the RichTextBox using (var __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 Metafile(_stream, _hdc); // Release the device context __graphics.ReleaseHdc(_hdc); } // Get a graphics context from the Enhanced Metafile using (var __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 - 1; 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(); } } }