Beispiel #1
0
 /// <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 inside this function.
 /// </summary>
 public static bool PutEnhMetafileOnClipboard(IntPtr hWnd, Metafile metafile, bool clearClipboard)
 {
     if (metafile == null) throw new ArgumentNullException("metafile");
     bool bResult = false;
     IntPtr hEMF, hEMF2;
     hEMF = metafile.GetHenhmetafile(); // invalidates mf
     if (!hEMF.Equals(IntPtr.Zero)) {
         try {
             hEMF2 = CopyEnhMetaFile(hEMF, null);
             if (!hEMF2.Equals(IntPtr.Zero)) {
                 if (OpenClipboard(hWnd)) {
                     try {
                         if (clearClipboard) {
                             if (!EmptyClipboard())
                                 return false;
                         }
                         IntPtr hRes = SetClipboardData(14 /*CF_ENHMETAFILE*/, hEMF2);
                         bResult = hRes.Equals(hEMF2);
                     } finally {
                         CloseClipboard();
                     }
                 }
             }
         } finally {
             DeleteEnhMetaFile(hEMF);
         }
     }
     return bResult;
 }
Beispiel #2
0
        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 ();
        }
Beispiel #3
0
        /// <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();
        }
Beispiel #4
0
 /// <summary>
 /// Copies the given <see cref="T:System.Drawing.Imaging.MetaFile" /> to the specified file. If the file does not exist, it will be created.
 /// The given <see cref="T:System.Drawing.Imaging.MetaFile" /> is set to an invalid state inside this function.
 /// </summary>
 public static bool SaveEnhMetaFile(string fileName, Metafile metafile)
 {
     if (metafile == null) throw new ArgumentNullException("metafile");
     bool result = false;
     IntPtr hEmf = metafile.GetHenhmetafile();
     if (hEmf != IntPtr.Zero) {
         IntPtr resHEnh = CopyEnhMetaFile(hEmf, fileName);
         if (resHEnh != IntPtr.Zero) {
             DeleteEnhMetaFile(resHEnh);
             result = true;
         }
         DeleteEnhMetaFile(hEmf);
         metafile.Dispose();
     }
     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");
        }
Beispiel #6
0
 // Metafile mf is set to an invalid state inside this function
 public static bool PutEnhMetafileOnClipboard(IntPtr hWnd, Metafile mf)
 {
     bool bResult = false;
     IntPtr hEMF = mf.GetHenhmetafile(); // invalidates mf
     if (!hEMF.Equals(new IntPtr(0)))
     {
         IntPtr hEMF2 = CopyEnhMetaFile(hEMF, new IntPtr(0));
         if (!hEMF2.Equals(new IntPtr(0)))
         {
             if (OpenClipboard(hWnd))
             {
                 if (EmptyClipboard())
                 {
                     IntPtr hRes = SetClipboardData(14, hEMF2); // 14 == CF_ENHMETAFILE()
                     bResult = hRes.Equals(hEMF2);
                     CloseClipboard();
                 }
             }
         }
         DeleteEnhMetaFile(hEMF);
     }
     return bResult;
 }
 public static void FillSection_Png( object sender, Leadtools.Printer.EmfEventArgs e )
 {
     ConsoleMethods.Info( "EMF Event: FillSection_Png" );
      const string format = "png";
      string path = Path.Combine(
     GetOutputRootPath(),
     format + @"\",
     GetRandomFileName( format ) );
      Directory.CreateDirectory( Path.GetDirectoryName( path ) );
      // Get the EMF in memory and save as PNG.
      Metafile metaFile = null;
      try
      {
     metaFile = new Metafile( e.Stream );
     IntPtr hEmf = metaFile.GetHenhmetafile();
     using ( RasterImage image = RasterImageConverter.FromEmf( hEmf, 0, 0, RasterColor.White ) )
     {
        using ( RasterRegion region = new RasterRegion( new LeadRect( 20, 30, 100, 200 ) ) )
        {
           image.SetRegion( null, region, RasterRegionCombineMode.Set );
           new FillCommand( RasterColor.FromKnownColor( RasterKnownColor.Black ) ).Run( image );
        }
        using ( RasterCodecs codecs = new RasterCodecs() )
        {
           codecs.Options.Png.Save.QualityFactor = 9;
           codecs.Save( image, path, RasterImageFormat.Png, 32 );
        }
     }
     ConsoleMethods.Success( "FillSection_Png: PNG saved. " );
     ConsoleMethods.Verbose( path );
      }
      catch ( Exception ex )
      {
     ConsoleMethods.Error( ex.Message, 4000 );
      }
 }
Beispiel #8
0
        private string convertCoordinatesToHex()
        {
            string signatureHex = string.Empty;

            if (SignatureCoordinate.Length > 0)
            {
                StringBuilder signatureHexVaule = new StringBuilder();
                MemoryStream memoryStream = new MemoryStream();
                System.Drawing.Image signatureTemplateImg = new System.Drawing.Bitmap(SignatureWidth, SignatureHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                Graphics SignatureGraphs = Graphics.FromImage(signatureTemplateImg);
                SignatureGraphs.FillRectangle(Brushes.White, 0, 0, signatureTemplateImg.Width, signatureTemplateImg.Height);

                Metafile signatureMetaFile = null;
                IntPtr hdc;
                try
                {
                    using (SignatureGraphs = Graphics.FromImage(signatureTemplateImg))
                    {
                        hdc = SignatureGraphs.GetHdc();
                        signatureMetaFile = new Metafile(memoryStream, hdc);
                        SignatureGraphs.ReleaseHdc(hdc);
                    }
                    using (SignatureGraphs = Graphics.FromImage(signatureMetaFile))
                    {
                        SignatureGraphs.DrawImage(signatureTemplateImg, new System.Drawing.Rectangle(0, 0, signatureTemplateImg.Width, signatureTemplateImg.Height));
                        SignatureGraphs.DrawRectangle(new Pen(Color.White, 1), 0, 0, SignatureWidth, SignatureHeight);

                        Pen pen = new Pen(Color.Black, 1);
                        string[] points = SignatureCoordinate.Split(':');
                        string[] point = null;

                        for (int i = 0; i < points.Length - 1; i++)
                        {
                            point = points[i].Split('~');
                            if (point.Length == 4)
                            {
                                SignatureGraphs.DrawRectangle(pen, float.Parse(point[0]), float.Parse(point[1]), float.Parse(point[2]), float.Parse(point[3]));
                            }
                        }
                    }

                    IntPtr hEmf = signatureMetaFile.GetHenhmetafile();

                    uint bufferSize = GdipEmfToWmfBits(hEmf, 0, null, MM_ANISOTROPIC, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);
                    byte[] buffer = new byte[bufferSize];

                    GdipEmfToWmfBits(hEmf, bufferSize, buffer, MM_ANISOTROPIC, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);

                    for (int i = 0; i < buffer.Length; ++i)
                    {
                        signatureHexVaule.Append(String.Format("{0:X2}", buffer[i]));
                    }

                    signatureHex = signatureHexVaule.ToString();
                }
                finally
                {
                    if (SignatureGraphs != null)
                    {
                        SignatureGraphs.Dispose();
                    }

                    if (signatureMetaFile != null)
                    {
                        signatureMetaFile.Dispose();
                    }

                    if (memoryStream != null)
                    {
                        memoryStream.Close();
                    }
                }
            }

            return signatureHex;
        }
 internal static bool SaveEnhMetafileToFile(Metafile mf)
 {
     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;
 }
 internal static bool SaveEnhMetafileToFile(Metafile mf, string fileName)
 {
     bool bResult = false;
     IntPtr hEMF;
     hEMF = mf.GetHenhmetafile(); // invalidates mf
     if (!hEMF.Equals(new IntPtr(0))) {
         StringBuilder tempName = new StringBuilder(fileName);
         CopyEnhMetaFile(hEMF, tempName);
         DeleteEnhMetaFile(hEMF);
     }
     return bResult;
 }
Beispiel #11
0
        private void CopyToClip( GraphPane thePane )
        {
            Graphics g = this.CreateGraphics();
            IntPtr hdc = g.GetHdc();
            //metaFile = new Metafile( hdc, EmfType.EmfPlusDual, "ZedGraph" );
            Metafile metaFile = new Metafile(hdc, EmfType.EmfPlusOnly);
            g.ReleaseHdc(hdc);
            g.Dispose();

            Graphics gMeta = Graphics.FromImage( metaFile );
            thePane.Draw( gMeta );
            gMeta.Dispose();

            //You can call this function with code that is similar to the following code:
            //ClipboardMetafileHelper.PutEnhMetafileOnClipboard( this.Handle, metaFile );

            IntPtr hMeta = metaFile.GetHenhmetafile();
            System.Windows.Forms.Clipboard.SetDataObject( hMeta, true  );

            MessageBox.Show( "Copied to ClipBoard" );
        }
Beispiel #12
0
        /// <summary>
        /// The following code will load the SVGDOM, render to a emf, and
        /// place the EMF on the clipboard. Kt seems more complicated than it should
        /// see http://www.dotnet247.com/247reference/msgs/23/118514.aspx
        /// for why the straight forward solution does not work.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void miCopy_Click(
			object sender,
			System.EventArgs e)
        {
            if (svgUrlCombo.Text.Length > 0)
            {
                int width = 500;
                int height = 500;

                // make SVG document with associated window so we can render it.
                SvgWindow window = new SvgWindow(width, height, null);
                GdiRenderer renderer = new GdiRenderer();
                renderer.Window = window;
                window.Renderer = renderer;
                window.Src = svgUrlCombo.Text;

                // copy and paste code taken from
                // http://www.dotnet247.com/247reference/msgs/23/117611.aspx
                // putting a plain MetaFile on the clipboard does not work.
                // .Net's metafile format is not recognised by most programs.
                Graphics g = CreateGraphics();
                IntPtr hdc = g.GetHdc();
                Metafile m = new Metafile(hdc, EmfType.EmfOnly);
                g.ReleaseHdc(hdc);
                g.Dispose();
                g = Graphics.FromImage(m);

                // draw the SVG here
                // NOTE: the graphics object is automatically Disposed by the
                // GdiRenderer.
                renderer.Graphics = g;
                renderer.Render(window.Document as SvgDocument);
                //window.Render();

                // put meta file on the clipboard.
                IntPtr hwnd = this.Handle;
                if (Win32.OpenClipboard(hwnd))
                {
                    Win32.EmptyClipboard();
                    IntPtr hemf = m.GetHenhmetafile();
                    Win32.SetClipboardData(14, hemf); //CF_ENHMETAFILE=14
                    Win32.CloseClipboard();
                }
            }
        }
Beispiel #13
0
		/// <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>
		public static string GetRtfImage(Image image)
		{
			StringBuilder rtf = null;

			// Used to store the enhanced metafile
			MemoryStream stream = null;

			// The enhanced metafile
			Metafile metaFile = null;

			// Handle to the device context used to create the metafile
			IntPtr hdc;

			try
			{
				rtf = new StringBuilder();
				stream = new MemoryStream();

				using (Graphics gr = Graphics.FromImage(image))
				{
					// Get the device context from the graphics context
					hdc = gr.GetHdc();
					// Create a new Enhanced Metafile from the device context
					metaFile = new Metafile(stream, hdc);
					// Release the device context
					gr.ReleaseHdc(hdc);
				}

				// Get a graphics context from the Enhanced Metafile
				using (Graphics gr = Graphics.FromImage(metaFile))
				{
					// Draw the image on the Enhanced Metafile
					gr.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 (metaFile != null)
					metaFile.Dispose();
				if (stream != null)
					stream.Close();
			}
		}
 private string GetRtfImage(Image _image)
 {
     MemoryStream stream = null;
     Graphics graphics = null;
     Metafile image = null;
     string ret;
     try
     {
         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, new Rectangle(0, 0, _image.Width, _image.Height));
         }
         IntPtr henhmetafile = image.GetHenhmetafile();
         uint num = GdipEmfToWmfBits(henhmetafile, 0, null, 1, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);
         byte[] buffer = new byte[num];
         GdipEmfToWmfBits(henhmetafile, num, buffer, 1, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);
         StringBuilder builder = new StringBuilder();
         for (int i = 0; i < buffer.Length; i++)
         {
             builder.Append(string.Format("{0:X2}", buffer[i]));
         }
         ret = builder.ToString();
     }
     finally
     {
         if (graphics != null)
         {
             graphics.Dispose();
         }
         if (image != null)
         {
             image.Dispose();
         }
         if (stream != null)
         {
             stream.Close();
         }
     }
     return ret;
 }
		/// <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();
					}
		}
 // 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 = NativeMethods.CopyEnhMetaFile(hEMF, null);
         if (!hEMF2.Equals(new IntPtr(0)))
         {
             if (NativeMethods.OpenClipboard(hWnd))
             {
                 if (NativeMethods.EmptyClipboard())
                 {
                     IntPtr hRes = NativeMethods.SetClipboardData(14 /*CF_ENHMETAFILE*/, hEMF2);
                     bResult = hRes.Equals(hEMF2);
                     NativeMethods.CloseClipboard();
                 }
             }
         }
         NativeMethods.DeleteEnhMetaFile(hEMF);
     }
     return bResult;
 }
Beispiel #17
0
        private static string GetRtfImage(Image _image, Control CurControl) 
        {
            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;

            try 
            {
                _rtf = new StringBuilder();
                _stream = new MemoryStream();

                // Get a graphics context from the RichTextBox
                using (_graphics = CurControl.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);
                }
            
                using(_graphics = Graphics.FromImage(_metaFile)) 
                {

                    // Draw the image on the Enhanced Metafile
                    _graphics.DrawImage(_image, new Rectangle(0, 0, _image.Width, _image.Height));
                }
                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();
            }
        }
Beispiel #18
0
		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);
			}
		}
Beispiel #19
0
        private static string GetRtfImage(Image image, Graphics gfx)
        {
            // Used to store the enhanced metafile
            MemoryStream stream = null;
            // Used to create the metafile and draw the image
            Graphics graphics = gfx;
            // The enhanced metafile
            Metafile metaFile = null;
            try
            {
                var rtf = new StringBuilder();
                stream = new MemoryStream();

                // Get the device context from the graphics context
                IntPtr 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))
                {
                    // 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 = GdiPlus.GdipEmfToWmfBits(hEmf, 0, null, 8, 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.  
                uint _convertedSize = GdiPlus.GdipEmfToWmfBits(hEmf, bufferSize, buffer, 8, EmfToWmfBitsFlags.EmfToWmfBitsFlagsDefault);
                // Append the bits to the RTF string
                foreach (byte t in buffer)
                    rtf.Append($"{t:X2}");

                return rtf.ToString();
            }
            finally
            {
                graphics?.Dispose();
                metaFile?.Dispose();
                stream?.Close();
            }
        }
Beispiel #20
0
        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();
            }
        }
Beispiel #21
0
        /*
        [DllImport("gdi32")]
        static extern int GetEnhMetaFileBits(int hemf, int cbBuffer, byte[] lpbBuffer);
        */
        // 
        /// <summary>
        /// Puts the metafile to the clipboard
        /// </summary>
        /// <param name="hWnd">The handle</param>
        /// <param name="mf">The metafie</param>
        /// <remarks>Metafile mf is set to a state that is not valid inside this function.</remarks>
        /// <returns><see langword="true"/> if operation was successfull</returns>
        static public bool PutEnhMetafileOnClipboard(IntPtr hWnd, Metafile mf)
        {
            bool bResult = false;
            IntPtr hEmf = mf.GetHenhmetafile();

            if (!hEmf.Equals(new IntPtr(0)))
            {
                IntPtr 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;
        }
Beispiel #22
0
        public static string GetEmbedImageString(string path)
        {
            string fileName = path.Substring(path.LastIndexOf("/") + 1);
            fileName = fileName.Substring(0, fileName.Length - 4);
            string filePath = Environment.CurrentDirectory + @"\cache\" + Program.MakeValidFileName(fileName) + ".cache";
            string proto = "";
            if (File.Exists(filePath))
            {
                proto = File.ReadAllText(filePath);
            }
            else
            {
                try
                {
                    byte[] imageData = null;
                    using (var webClient = new WebClient())
                    {
                        imageData = webClient.DownloadData(path);
                    }

                    if (imageData == null) return String.Empty;

                    Bitmap image;
                    using (var ms = new MemoryStream(imageData))
                    {
                        image = new Bitmap(ms);
                    }

                    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);

                    proto = @"{\pict\wmetafile8\picw" + (int) ((image.Width/dpiX)*2540)
                            + @"\pich" + (int) ((image.Height/dpiY)*2540)
                            + @"\picwgoal" + (int) ((image.Width/dpiX)*1440)
                            + @"\pichgoal" + (int) ((image.Height/dpiY)*1440)
                            + " "
                            + BitConverter.ToString(stream.ToArray()).Replace("-", "")
                            + "}";

                    StreamWriter file = new StreamWriter(filePath);
                    file.WriteLine(proto);

                    file.Close();
                }
                catch (Exception e)
                {
                    proto = null;
                }
                
            }
            
            return proto;
        }