System.Drawing.Graphics.Dispose()

Here are the examples of the csharp api System.Drawing.Graphics.Dispose() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

521 Examples 7

19 Source : MainFormHandler.cs
with GNU General Public License v3.0
from 2dust

public Icon GetNotifyIcon(Config config, Icon def)
        {
            try
            {
                Color color = ColorTranslator.FromHtml("#3399CC");
                int index = (int)config.sysProxyType;
                if (index > 0)
                {
                    color = (new Color[] { Color.Red, Color.Purple, Color.DarkGreen, Color.Orange, Color.DarkSlateBlue, Color.RoyalBlue })[index - 1];
                    //color = ColorTranslator.FromHtml(new string[] { "#CC0066", "#CC6600", "#99CC99", "#666699" }[index - 1]);
                }

                int width = 128;
                int height = 128;

                Bitmap bitmap = new Bitmap(width, height);
                Graphics graphics = Graphics.FromImage(bitmap);
                SolidBrush drawBrush = new SolidBrush(color);

                graphics.FillEllipse(drawBrush, new Rectangle(0, 0, width, height));
                int zoom = 16;
                graphics.DrawImage(new Bitmap(Properties.Resources.notify, width - zoom, width - zoom), zoom / 2, zoom / 2);

                Icon createdIcon = Icon.FromHandle(bitmap.GetHicon());

                drawBrush.Dispose();
                graphics.Dispose();
                bitmap.Dispose();

                return createdIcon;
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
                return def;
            }
        }

19 Source : GraphicsManager.cs
with GNU General Public License v3.0
from aglab2

public void TestFont()
        {
            Image randomImage = new Bitmap(300, 50);
            Graphics g = Graphics.FromImage(randomImage);

            // Setup draw font: 20 symbols in max 170 width
            float l = 0, r = 40, m = -1;
            String measureString = new string('W', 2);

            // 10 iterations is enough
            for (int iter = 0; iter < 10; iter++)
            {
                m = (l + r) / 2;

                Font drawFont = new Font(FontFamily, m);

                // Measure string.
                SizeF stringSize = new SizeF();
                stringSize = g.MeasureString(measureString, drawFont);

                float width = stringSize.Width; //should take 170
                if (width < SWidth)
                    l = m;
                else
                    r = m;
            }
            drawFontSize = m;
            Console.WriteLine("Draw: {0}", m);

            // Setup med font: 1 symbols in max 20 height
            l = 0; r = 40; m = -1;
            measureString = "W";

            // 10 iterations is enough
            for (int iter = 0; iter < 10; iter++)
            {
                m = (l + r) / 2;

                Font drawFont = new Font(FontFamily, m);
                
                // Measure string.
                SizeF stringSize = new SizeF();
                stringSize = g.MeasureString(measureString, drawFont);

                float height = stringSize.Height; //should take HalfWidth
                if (height < SWidth)
                    l = m;
                else
                    r = m;
            }
            medFontSize = m;
            Console.WriteLine("Med: {0}", m);

            // Setup med font: 1 symbols in max 20 height
            l = 0; r = 40; m = -1;
            measureString = new string('W', 27);

            // 10 iterations is enough
            for (int iter = 0; iter < 10; iter++)
            {
                m = (l + r) / 2;

                Font drawFont = new Font(FontFamily, m);

                // Measure string.
                SizeF stringSize = new SizeF();
                stringSize = g.MeasureString(measureString, drawFont);

                float width = stringSize.Width; //should take 170
                float localScaleCoef = ld == null ? 1 : scaleCoef;

                if (width < HalfWidth * 2 * localScaleCoef)
                    l = m;
                else
                    r = m;
            }
            bigFontSize = m;
            Console.WriteLine("Big: {0}", m);

            g.Dispose();
            randomImage.Dispose();
        }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from aglab2

private void UpdateStars(object sender)
        {
            isEmulatorStarted = false;
            isHackLoaded = false;
            isOffsetsFound = false;

            try
            {
                if (um.IsCompleted())
                {
                    if (!isUpdateRequested && !um.IsUpdated())
                    {
                        isUpdateRequested = true;
                        this.SafeInvoke((MethodInvoker)delegate
                        {
                            DialogResult result = MessageBox.Show(String.Format("Update for Star Display available!\n\n{0}\nDo you want to download it now? Press cancel to skip update", um.UpdateName()), "Update",
                            MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk);
                            if (result == DialogResult.Yes)
                            {
                                Process.Start(um.DownloadPath());
                            }
                            if (result == DialogResult.Cancel)
                            {
                                um.WritebackUpdate();
                            }
                        });
                    }
                }
            }
            catch (Exception) { }

            try
            {
                //if (slf != null && slf.sm != null && slf.sm.isServer)
                //    goto bla;

                if (mm.ProcessActive())
                {
                    this.SafeInvoke((MethodInvoker)delegate { DrawIntro(); ResetForm(); });
                    return;
                }
                
                isEmulatorStarted = true;

                // Well, that's just a minor magic but it works
                if (mm.Getreplacedle().Contains("-"))
                    isHackLoaded = true;

                if (!mm.isMagicDone())
                {
                    if (magicThread == null || !magicThread.IsAlive)
                    {
                        magicThread = new Thread(doMagicThread);
                        magicThread.Start();
                    }

                    this.SafeInvoke((MethodInvoker)delegate { DrawIntro(); });
                    return;
                }
                
                isOffsetsFound = true;


                try
                {
                    // Just do nothing
                    if (!mm.isReadyToRead())
                        return;

                    mm.PerformRead();
                }
                catch (Exception)
                {
                    this.SafeInvoke((MethodInvoker)delegate { DrawIntro(); ResetForm(); });
                    return;
                }
 
                bool mmIsInvalidated = mm == null ? false : mm.CheckInvalidated();
                bool gmIsInvalidated = gm == null ? false : gm.CheckInvalidated();
                bool dmIsInvalidated = dm == null ? false : dm.CheckInvalidated();
                bool smIsInvalidated = false;
                if (slf != null && slf.sm != null)
                    smIsInvalidated = slf.sm.CheckInvalidated();

                bool nmIsInvalidated = false;
                if (slf != null && slf.nm != null)
                    nmIsInvalidated = slf.nm.CheckInvalidated();

                if (smIsInvalidated && slf.sm.dropFile)
                {
                    slf.sm.dropFile = false;
                    mm.Stars = new byte[MemoryManager.FileLength];
                    mm.WriteToFile(ld.starsShown);
                    mm.isStarsInvalidated = true;
                }

                if (mmIsInvalidated && mm.isStarsInvalidated)
                {
                    mm.isStarsInvalidated = false;
                    if (slf != null && slf.sm != null)
                    {
                        slf.sm.SendData(mm.Stars);
                    }

                    Console.WriteLine("MM Invalidated!");
                }

                if (gmIsInvalidated)
                    Console.WriteLine("GM Invalidated!");
                if (dmIsInvalidated)
                    Console.WriteLine("DM Invalidated!");

                if (smIsInvalidated)
                {
                    Console.WriteLine("SM Invalidated!");
                    {
                        byte[] stars = slf.sm.AcquiredData;

                        bool shouldSendHelp = false;
                        for (int i = 0; i < stars.Count(); i++)
                        {
                            byte diff = (byte)(mm.Stars[i] ^ stars[i]);
                            if ((mm.Stars[i] & diff) != 0)
                                shouldSendHelp = true;

                            otherStars[i] |= (byte)(diff & stars[i]);
                            mm.Stars[i] = (byte)(mm.Stars[i] | stars[i]);
                        }

                        if (shouldSendHelp)
                        {
                            slf.sm.SendData(mm.Stars);
                        }

                        mm.WriteToFile(ld.starsShown);
                    }
                    if (!mm.IsDecomp)
                    {
                        var location = mm.GetLocation();
                        var netData = slf.sm.getNetData();
                        foreach (var item in netData)
                        {
                            var player = item.Key;
#if DEBUG == false
                            if (player != slf.GetPlayerName())
#endif
                            {
                                var data = item.Value;

                                if (slf is object && slf.nm is object)
                                {
                                    var id = slf.nm.RegisterPlayer(player);
                                    if (data.location == location)
                                        mm.WriteNetState(id, data.state);
                                    else
                                        mm.WriteNetState(id, null);
                                }
                            }
                        }
                    }
                }

                if (nmIsInvalidated)
                {
                    if (!mm.IsDecomp)
                    {
                        mm.WriteNetPatch();
                        var state = mm.GetMarioState();
                        if (slf.sm is object)
                        {
                            slf.sm.SendNet64Data(slf.GetNet64Name(), state, mm.GetLocation());
                        }

                        if (slf.nm.mustReload)
                        {
                            for (int i = 0; i < 16; i++)
                            {
                                mm.WriteNetState(i, null);
                            }
                            slf.nm.mustReload = false;
                        }

                        this.SafeInvoke((MethodInvoker)delegate { slf.UpdatePlayers(slf.nm.GetPlayers()); });
                    }
                }

                // We do not draw anything!
                if (!mmIsInvalidated && !gmIsInvalidated && !smIsInvalidated && !dmIsInvalidated)
                {
                    return;
                }

                gm.TestFont();

                if (enableAutoDeleteToolStripMenuItem.Checked)
                {
                    try
                    {
                        mm.DeleteStars();
                    }
                    catch (IOException)
                    {
                        MessageBox.Show("Can not modify savefiles. Trying launching with elevated rights!", "Write Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        enableAutoDeleteToolStripMenuItem.Checked = false;
                    }
                }

                //Display stars routine
                baseImage = new Bitmap(starPicture.Width, starPicture.Width * 4);

                Graphics baseGraphics = Graphics.FromImage(baseImage);
                baseGraphics.Clear(Color.Black);
                baseGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
                gm.graphics = Graphics.FromImage(baseImage);

                if (!sm.GetConfig(MainWindowsSettingsAction.collectablesOnlyConfigureName, false))
                {
                    TextHighlightAction act = mm.GetCurrentLineAction(ld);
                    if (act != null)
                    {
                        gm.AddLineHighlight(act);
                    }
                }

                UInt16 currentCRC = mm.GetRomCRC();
                if (currentCRC != oldCRC || rm == null || dmIsInvalidated)
                {
                    oldCRC = currentCRC;
                    try
                    {
                        rm = new ROMManager(mm.GetROM());
                        try
                        {
                            if (dm != null)
                            {
                                dm.GetData();
                            }

                            string exePath = Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location);
                            LoadLayoutNoInvalidate(exePath + "\\layout\\" + rm.GetROMName() + ".jsml", false);
                        }
                        catch (IOException)
                        {
                            try
                            {
                                dm = new DownloadManager(rm.GetROMName() + ".jsml");
                            }
                            catch(Exception) { }
                            LoadDefaultLayoutNoInvalidate();
                        }

                        gm.IsFirstCall = true;
                    }
                    catch (IndexOutOfRangeException) //can be generated by box reader
                    { }
                    catch (Exception)
                    { oldCRC = 0; }

                    InvalidateCache();
                }

                int lineOffset = 0;
                var actions = sm.GetConfig(MainWindowsSettingsAction.collectablesOnlyConfigureName, false) ?
                    mm.GetCollectablesOnlyDrawActions(ld, rm) : 
                    mm.GetDrawActions(ld, rm, enableLockoutToolStripMenuItem.Checked ? otherStars : null);

                if (actions == null) return;

                foreach (var entry in actions)
                {
                    lineOffset += entry.Execute(gm, lineOffset, sm);
                }
                
                baseGraphics.Dispose();
                this.SafeInvoke(delegate {
                    menuStrip.Enabled = true;
                    starPicture.Image = baseImage;
                    starPicture.Height = (int) (lineOffset * gm.SHeight) + 10;
                    this.Height = (int)(lineOffset * gm.SHeight) + 48;
                });
            }
            catch (Win32Exception)
            {
                this.SafeInvoke((MethodInvoker)delegate { ResetForm(); DrawIntro(); });
            }
            catch (NullReferenceException)
            {
                this.SafeInvoke((MethodInvoker)delegate { ResetForm(); DrawIntro(); });
            }
            catch (ObjectDisposedException)
            {
            }
            finally
            {
                int period = (isEmulatorStarted && isHackLoaded && isOffsetsFound) ? updatePeriod : scanPeriod;
                timer.Change(period, Timeout.Infinite);
            }
        }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from aglab2

private void DrawIntro()
        {
            menuStrip.Enabled = false;

            //Steps to achieve success here!
            baseImage = new Bitmap(starPicture.Width, starPicture.Height);
            Graphics baseGraphics = Graphics.FromImage(baseImage);
            baseGraphics.Clear(Color.Black);
            baseGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
            gm.graphics = Graphics.FromImage(baseImage);

            gm.DrawIntro(isEmulatorStarted, isHackLoaded, isOffsetsFound);
            baseGraphics.Dispose();
            starPicture.Image = baseImage;
        }

19 Source : TextureEncoder.cs
with GNU General Public License v3.0
from ahmed605

internal static void Encode(Texture texture, Image image, int level)
        {
            var width = texture.GetWidth(level);
            var height = texture.GetHeight(level);
            var data = new byte[width * height * 4];  // R G B A

            var bitmap = new Bitmap((int)width, (int)height);

            Graphics g = Graphics.FromImage(bitmap);
            g.InterpolationMode = InterpolationMode.HighQualityBilinear;
            g.DrawImage(image, 0, 0, (int)width, (int)height);
            g.Dispose();

            var rect = new Rectangle(0, 0, (int) width, (int) height);
            BitmapData bmpdata = bitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

            if (texture.TextureType == TextureType.A8R8G8B8)
            {
                Marshal.Copy(bmpdata.Scan0, data, 0, (int) width*(int) height*4);
            }
            else if (texture.TextureType == TextureType.L8)
            {
                var newData = new byte[width * height];

                // Convert to L8
                unsafe
                {
                    var p = (byte*)bmpdata.Scan0;
                    for (var y = 0; y < bitmap.Height; y++)
                    {
                        for (var x = 0; x < bitmap.Width; x++)
                        {
                            var offset = y * bmpdata.Stride + x * 4;
                            var dataOffset = y * width + x;

                            newData[dataOffset] = (byte)((p[offset + 2] + p[offset + 1] + p[offset + 0])/3);
                        }
                    }
                }

                data = newData;
            }
            else
            {
                // Convert from the B G R A format stored by GDI+ to R G B A
                unsafe
                {
                    var p = (byte*)bmpdata.Scan0;
                    for (var y = 0; y < bitmap.Height; y++)
                    {
                        for (var x = 0; x < bitmap.Width; x++)
                        {
                            var offset = y * bmpdata.Stride + x * 4;
                            var dataOffset = y * width * 4 + x * 4;
                            data[dataOffset + 0] = p[offset + 2];       // R
                            data[dataOffset + 1] = p[offset + 1];       // G
                            data[dataOffset + 2] = p[offset + 0];       // B
                            data[dataOffset + 3] = p[offset + 3];       // A
                        }
                    }
                }
            }

            bitmap.UnlockBits(bmpdata);

            bitmap.Dispose();

            switch (texture.TextureType)
            {
                case TextureType.DXT1:
                    data = DXTEncoder.EncodeDXT1(data, (int) width, (int) height);
                    break;
                case TextureType.DXT3:
                    data = DXTEncoder.EncodeDXT3(data, (int) width, (int) height);
                    break;
                case TextureType.DXT5:
                    data = DXTEncoder.EncodeDXT5(data, (int) width, (int) height);
                    break;
                case TextureType.A8R8G8B8:
                case TextureType.L8:
                    // Nothing to do
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            texture.SetTextureData(level, data);
        }

19 Source : Graphics.cs
with Mozilla Public License 2.0
from ahyahy

public void Dispose()
        {
            M_Graphics.Dispose();
        }

19 Source : ImageColorsConverter.cs
with GNU General Public License v3.0
from aiportal

public unsafe Image SaveImageWithNewColorTable(Image image)
		{
			Bitmap bitmap = null;
			Bitmap bitmap2 = null;
			Graphics graphics = null;
			BitmapData bitmapdata = null;
			BitmapData data2 = null;
			if (this._imgColors > 0x100)
			{
				this._imgColors = 0x100;
			}
			if (this._imgColors < 2)
			{
				this._imgColors = 2;
			}
			int width = image.Width;
			int height = image.Height;
			try
			{
				byte* numPtr;
				byte* numPtr2;
				bitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
				bitmap.Palette = this.pal;
				bitmap2 = new Bitmap(width, height, PixelFormat.Format32bppArgb);
				graphics = Graphics.FromImage(bitmap2);
				graphics.PageUnit = GraphicsUnit.Pixel;
				graphics.DrawImage(image, 0, 0, width, height);
				Rectangle rect = new Rectangle(0, 0, width, height);
				bitmapdata = bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
				data2 = bitmap2.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
				IntPtr ptr = bitmapdata.Scan0;
				IntPtr ptr2 = data2.Scan0;
				if (bitmapdata.Stride > 0)
				{
					numPtr = (byte*)ptr.ToPointer();
				}
				else
				{
					numPtr = (byte*)ptr.ToPointer() + (bitmapdata.Stride * (height - 1));
				}
				if (data2.Stride > 0)
				{
					numPtr2 = (byte*)ptr2.ToPointer();
				}
				else
				{
					numPtr2 = (byte*)ptr2.ToPointer() + (data2.Stride * (height - 1));
				}
				uint num3 = (uint)Math.Abs(bitmapdata.Stride);
				uint num4 = (uint)Math.Abs(data2.Stride);
				for (uint i = 0; i < height; i++)
				{
					PixelData* dataPtr = (PixelData*)(numPtr2 + (i * num4));
					byte* numPtr3 = numPtr + (i * num3);
					for (uint j = 0; j < width; j++)
					{
						double num7 = ((dataPtr->red * 0.299) + (dataPtr->green * 0.587)) + (dataPtr->blue * 0.114);
						numPtr3[0] = (byte)(((num7 * (this._imgColors - 1)) / 255.0) + 0.5);
						dataPtr++;
						numPtr3++;
					}
				}
				bitmap.UnlockBits(bitmapdata);
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			finally
			{
				bitmap2.UnlockBits(data2);
				bitmap2.Dispose();
				graphics.Dispose();
				bitmapdata = null;
				data2 = null;
			}
			return bitmap;
		}

19 Source : ImageCompression.cs
with GNU General Public License v3.0
from aiportal

public static void SaveGrayScale(
			Image image,
			string filename,
			uint nColors,
			bool fTransparent
			)
		{

			// GIF codec supports 256 colors maximum, monochrome minimum.
			if (nColors > 256)
				nColors = 256;
			if (nColors < 2)
				nColors = 2;

			// Make a new 8-BPP indexed bitmap that is the same size as the source image.
			int Width = image.Width;
			int Height = image.Height;

			// Always use PixelFormat8bppIndexed because that is the color
			// table-based interface to the GIF codec.
			Bitmap bitmap = new Bitmap(Width,
									Height,
									PixelFormat.Format8bppIndexed);

			// Create a color palette big enough to hold the colors you want.
			ColorPalette pal = GetColorPalette(nColors);

			// Initialize a new color table with entries that are determined
			// by some optimal palette-finding algorithm; for demonstration 
			// purposes, use a grayscale.
			for (uint i = 0; i < nColors; i++)
			{
				uint Alpha = 0xFF;                      // Colors are opaque.
				uint Intensity = i * 0xFF / (nColors - 1);    // Even distribution. 

				// The GIF encoder makes the first entry in the palette
				// that has a ZERO alpha the transparent color in the GIF.
				// Pick the first one arbitrarily, for demonstration purposes.

				if (i == 0 && fTransparent) // Make this color index...
					Alpha = 0;          // Transparent

				// Create a gray scale for demonstration purposes.
				// Otherwise, use your favorite color reduction algorithm
				// and an optimum palette for that algorithm generated here.
				// For example, a color histogram, or a median cut palette.
				pal.Entries[i] = Color.FromArgb((int)Alpha,
												(int)Intensity,
												(int)Intensity,
												(int)Intensity);
			}

			// Set the palette into the new Bitmap object.
			bitmap.Palette = pal;


			// Use GetPixel below to pull out the color data of Image.
			// Because GetPixel isn't defined on an Image, make a copy 
			// in a Bitmap instead. Make a new Bitmap that is the same size as the
			// image that you want to export. Or, try to
			// interpret the native pixel format of the image by using a LockBits
			// call. Use PixelFormat32BppARGB so you can wrap a Graphics  
			// around it.
			Bitmap BmpCopy = new Bitmap(Width,
									Height,
									PixelFormat.Format32bppArgb);
			{
				Graphics g = Graphics.FromImage(BmpCopy);

				g.PageUnit = GraphicsUnit.Pixel;

				// Transfer the Image to the Bitmap
				g.DrawImage(image, 0, 0, Width, Height);

				// g goes out of scope and is marked for garbage collection.
				// Force it, just to keep things clean.
				g.Dispose();
			}

			// Lock a rectangular portion of the bitmap for writing.
			BitmapData bitmapData;
			Rectangle rect = new Rectangle(0, 0, Width, Height);

			bitmapData = bitmap.LockBits(
				rect,
				ImageLockMode.WriteOnly,
				PixelFormat.Format8bppIndexed);

			// Write to the temporary buffer that is provided by LockBits.
			// Copy the pixels from the source image in this loop.
			// Because you want an index, convert RGB to the appropriate
			// palette index here.
			IntPtr pixels = bitmapData.Scan0;

			unsafe
			{
				// Get the pointer to the image bits.
				// This is the unsafe operation.
				byte* pBits;
				if (bitmapData.Stride > 0)
					pBits = (byte*)pixels.ToPointer();
				else
					// If the Stide is negative, Scan0 points to the last 
					// scanline in the buffer. To normalize the loop, obtain
					// a pointer to the front of the buffer that is located 
					// (Height-1) scanlines previous.
					pBits = (byte*)pixels.ToPointer() + bitmapData.Stride * (Height - 1);
				uint stride = (uint)Math.Abs(bitmapData.Stride);

				for (uint row = 0; row < Height; ++row)
				{
					for (uint col = 0; col < Width; ++col)
					{
						// Map palette indexes for a gray scale.
						// If you use some other technique to color convert,
						// put your favorite color reduction algorithm here.
						Color pixel;    // The source pixel.

						// The destination pixel.
						// The pointer to the color index byte of the
						// destination; this real pointer causes this
						// code to be considered unsafe.
						byte* p8bppPixel = pBits + row * stride + col;

						pixel = BmpCopy.GetPixel((int)col, (int)row);

						// Use luminance/chrominance conversion to get grayscale.
						// Basically, turn the image into black and white TV.
						// Do not calculate Cr or Cb because you 
						// discard the color anyway.
						// Y = Red * 0.299 + Green * 0.587 + Blue * 0.114

						// This expression is best as integer math for performance,
						// however, because GetPixel listed earlier is the slowest 
						// part of this loop, the expression is left as 
						// floating point for clarity.

						double luminance = (pixel.R * 0.299) +
							(pixel.G * 0.587) +
							(pixel.B * 0.114);

						// Gray scale is an intensity map from black to white.
						// Compute the index to the grayscale entry that
						// approximates the luminance, and then round the index.
						// Also, constrain the index choices by the number of
						// colors to do, and then set that pixel's index to the 
						// byte value.
						*p8bppPixel = (byte)(luminance * (nColors - 1) / 255 + 0.5);

					} /* end loop for col */
				} /* end loop for row */
			} /* end unsafe */

			// To commit the changes, unlock the portion of the bitmap.  
			bitmap.UnlockBits(bitmapData);

			bitmap.Save(filename, ImageFormat.Png);

			// Bitmap goes out of scope here and is also marked for
			// garbage collection.
			// Pal is referenced by bitmap and goes away.
			// BmpCopy goes out of scope here and is marked for garbage
			// collection. Force it, because it is probably quite large.
			// The same applies to bitmap.
			BmpCopy.Dispose();
			bitmap.Dispose();
		}

19 Source : ImageCompression.cs
with GNU General Public License v3.0
from aiportal

public static void SaveGrayScale(Image image, string filename, uint nColors, bool fTransparent)
		{

			// GIF codec supports 256 colors maximum, monochrome minimum.
			if (nColors > 256)
				nColors = 256;
			if (nColors < 2)
				nColors = 2;

			// Make a new 8-BPP indexed bitmap that is the same size as the source image.
			int Width = image.Width;
			int Height = image.Height;

			// Always use PixelFormat8bppIndexed because that is the color
			// table-based interface to the GIF codec.
			Bitmap bitmap = new Bitmap(Width,
									Height,
									PixelFormat.Format8bppIndexed);

			// Create a color palette big enough to hold the colors you want.
			ColorPalette pal = GetColorPalette(nColors);

			// Initialize a new color table with entries that are determined
			// by some optimal palette-finding algorithm; for demonstration 
			// purposes, use a grayscale.
			for (uint i = 0; i < nColors; i++)
			{
				uint Alpha = 0xFF;                      // Colors are opaque.
				uint Intensity = i * 0xFF / (nColors - 1);    // Even distribution. 

				// The GIF encoder makes the first entry in the palette
				// that has a ZERO alpha the transparent color in the GIF.
				// Pick the first one arbitrarily, for demonstration purposes.

				if (i == 0 && fTransparent) // Make this color index...
					Alpha = 0;          // Transparent

				// Create a gray scale for demonstration purposes.
				// Otherwise, use your favorite color reduction algorithm
				// and an optimum palette for that algorithm generated here.
				// For example, a color histogram, or a median cut palette.
				pal.Entries[i] = Color.FromArgb((int)Alpha,
												(int)Intensity,
												(int)Intensity,
												(int)Intensity);
			}

			// Set the palette into the new Bitmap object.
			bitmap.Palette = pal;


			// Use GetPixel below to pull out the color data of Image.
			// Because GetPixel isn't defined on an Image, make a copy 
			// in a Bitmap instead. Make a new Bitmap that is the same size as the
			// image that you want to export. Or, try to
			// interpret the native pixel format of the image by using a LockBits
			// call. Use PixelFormat32BppARGB so you can wrap a Graphics  
			// around it.
			Bitmap BmpCopy = new Bitmap(Width,
									Height,
									PixelFormat.Format32bppArgb);
			{
				Graphics g = Graphics.FromImage(BmpCopy);

				g.PageUnit = GraphicsUnit.Pixel;

				// Transfer the Image to the Bitmap
				g.DrawImage(image, 0, 0, Width, Height);

				// g goes out of scope and is marked for garbage collection.
				// Force it, just to keep things clean.
				g.Dispose();
			}

			// Lock a rectangular portion of the bitmap for writing.
			BitmapData bitmapData;
			Rectangle rect = new Rectangle(0, 0, Width, Height);

			bitmapData = bitmap.LockBits(
				rect,
				ImageLockMode.WriteOnly,
				PixelFormat.Format8bppIndexed);

			// Write to the temporary buffer that is provided by LockBits.
			// Copy the pixels from the source image in this loop.
			// Because you want an index, convert RGB to the appropriate
			// palette index here.
			IntPtr pixels = bitmapData.Scan0;

			unsafe
			{
				// Get the pointer to the image bits.
				// This is the unsafe operation.
				byte* pBits;
				if (bitmapData.Stride > 0)
					pBits = (byte*)pixels.ToPointer();
				else
					// If the Stide is negative, Scan0 points to the last 
					// scanline in the buffer. To normalize the loop, obtain
					// a pointer to the front of the buffer that is located 
					// (Height-1) scanlines previous.
					pBits = (byte*)pixels.ToPointer() + bitmapData.Stride * (Height - 1);
				uint stride = (uint)Math.Abs(bitmapData.Stride);

				for (uint row = 0; row < Height; ++row)
				{
					for (uint col = 0; col < Width; ++col)
					{
						// Map palette indexes for a gray scale.
						// If you use some other technique to color convert,
						// put your favorite color reduction algorithm here.
						Color pixel;    // The source pixel.

						// The destination pixel.
						// The pointer to the color index byte of the
						// destination; this real pointer causes this
						// code to be considered unsafe.
						byte* p8bppPixel = pBits + row * stride + col;

						pixel = BmpCopy.GetPixel((int)col, (int)row);

						// Use luminance/chrominance conversion to get grayscale.
						// Basically, turn the image into black and white TV.
						// Do not calculate Cr or Cb because you 
						// discard the color anyway.
						// Y = Red * 0.299 + Green * 0.587 + Blue * 0.114

						// This expression is best as integer math for performance,
						// however, because GetPixel listed earlier is the slowest 
						// part of this loop, the expression is left as 
						// floating point for clarity.

						double luminance = (pixel.R * 0.299) +
							(pixel.G * 0.587) +
							(pixel.B * 0.114);

						// Gray scale is an intensity map from black to white.
						// Compute the index to the grayscale entry that
						// approximates the luminance, and then round the index.
						// Also, constrain the index choices by the number of
						// colors to do, and then set that pixel's index to the 
						// byte value.
						*p8bppPixel = (byte)(luminance * (nColors - 1) / 255 + 0.5);

					} /* end loop for col */
				} /* end loop for row */
			} /* end unsafe */

			// To commit the changes, unlock the portion of the bitmap.  
			bitmap.UnlockBits(bitmapData);

			bitmap.Save(filename, ImageFormat.Png);

			// Bitmap goes out of scope here and is also marked for
			// garbage collection.
			// Pal is referenced by bitmap and goes away.
			// BmpCopy goes out of scope here and is marked for garbage
			// collection. Force it, because it is probably quite large.
			// The same applies to bitmap.
			BmpCopy.Dispose();
			bitmap.Dispose();
		}

19 Source : ImageCompression.cs
with GNU General Public License v3.0
from aiportal

public static Image GrayScaleCompress(Image image)
		{
			uint nColors = 256;
			bool fTransparent = true;

			// Make a new 8-BPP indexed bitmap that is the same size as the source image.
			int Width = image.Width;
			int Height = image.Height;

			// Always use PixelFormat8bppIndexed because that is the color
			// table-based interface to the GIF codec.
			Bitmap bitmap = new Bitmap(Width,
									Height,
									PixelFormat.Format8bppIndexed);

			// Create a color palette big enough to hold the colors you want.
			ColorPalette pal = GetColorPalette(nColors);

			// Initialize a new color table with entries that are determined
			// by some optimal palette-finding algorithm; for demonstration 
			// purposes, use a grayscale.
			for (uint i = 0; i < nColors; i++)
			{
				uint Alpha = 0xFF;                      // Colors are opaque.
				uint Intensity = i * 0xFF / (nColors - 1);    // Even distribution. 

				// The GIF encoder makes the first entry in the palette
				// that has a ZERO alpha the transparent color in the GIF.
				// Pick the first one arbitrarily, for demonstration purposes.

				if (i == 0 && fTransparent) // Make this color index...
					Alpha = 0;          // Transparent

				// Create a gray scale for demonstration purposes.
				// Otherwise, use your favorite color reduction algorithm
				// and an optimum palette for that algorithm generated here.
				// For example, a color histogram, or a median cut palette.
				pal.Entries[i] = Color.FromArgb((int)Alpha,
												(int)Intensity,
												(int)Intensity,
												(int)Intensity);
			}

			// Set the palette into the new Bitmap object.
			bitmap.Palette = pal;


			// Use GetPixel below to pull out the color data of Image.
			// Because GetPixel isn't defined on an Image, make a copy 
			// in a Bitmap instead. Make a new Bitmap that is the same size as the
			// image that you want to export. Or, try to
			// interpret the native pixel format of the image by using a LockBits
			// call. Use PixelFormat32BppARGB so you can wrap a Graphics  
			// around it.
			Bitmap BmpCopy = new Bitmap(Width,
									Height,
									PixelFormat.Format32bppArgb);
			{
				Graphics g = Graphics.FromImage(BmpCopy);

				g.PageUnit = GraphicsUnit.Pixel;

				// Transfer the Image to the Bitmap
				g.DrawImage(image, 0, 0, Width, Height);

				// g goes out of scope and is marked for garbage collection.
				// Force it, just to keep things clean.
				g.Dispose();
			}

			// Lock a rectangular portion of the bitmap for writing.
			BitmapData bitmapData;
			Rectangle rect = new Rectangle(0, 0, Width, Height);

			bitmapData = bitmap.LockBits(
				rect,
				ImageLockMode.WriteOnly,
				PixelFormat.Format8bppIndexed);

			// Write to the temporary buffer that is provided by LockBits.
			// Copy the pixels from the source image in this loop.
			// Because you want an index, convert RGB to the appropriate
			// palette index here.
			IntPtr pixels = bitmapData.Scan0;

			unsafe
			{
				// Get the pointer to the image bits.
				// This is the unsafe operation.
				byte* pBits;
				if (bitmapData.Stride > 0)
					pBits = (byte*)pixels.ToPointer();
				else
					// If the Stide is negative, Scan0 points to the last 
					// scanline in the buffer. To normalize the loop, obtain
					// a pointer to the front of the buffer that is located 
					// (Height-1) scanlines previous.
					pBits = (byte*)pixels.ToPointer() + bitmapData.Stride * (Height - 1);
				uint stride = (uint)Math.Abs(bitmapData.Stride);

				for (uint row = 0; row < Height; ++row)
				{
					for (uint col = 0; col < Width; ++col)
					{
						// Map palette indexes for a gray scale.
						// If you use some other technique to color convert,
						// put your favorite color reduction algorithm here.
						Color pixel;    // The source pixel.

						// The destination pixel.
						// The pointer to the color index byte of the
						// destination; this real pointer causes this
						// code to be considered unsafe.
						byte* p8bppPixel = pBits + row * stride + col;

						pixel = BmpCopy.GetPixel((int)col, (int)row);

						// Use luminance/chrominance conversion to get grayscale.
						// Basically, turn the image into black and white TV.
						// Do not calculate Cr or Cb because you 
						// discard the color anyway.
						// Y = Red * 0.299 + Green * 0.587 + Blue * 0.114

						// This expression is best as integer math for performance,
						// however, because GetPixel listed earlier is the slowest 
						// part of this loop, the expression is left as 
						// floating point for clarity.

						double luminance = (pixel.R * 0.299) +
							(pixel.G * 0.587) +
							(pixel.B * 0.114);

						// Gray scale is an intensity map from black to white.
						// Compute the index to the grayscale entry that
						// approximates the luminance, and then round the index.
						// Also, constrain the index choices by the number of
						// colors to do, and then set that pixel's index to the 
						// byte value.
						*p8bppPixel = (byte)(luminance * (nColors - 1) / 255 + 0.5);

					} /* end loop for col */
				} /* end loop for row */
			} /* end unsafe */

			// To commit the changes, unlock the portion of the bitmap.  
			bitmap.UnlockBits(bitmapData);

			// Bitmap goes out of scope here and is also marked for
			// garbage collection.
			// Pal is referenced by bitmap and goes away.
			// BmpCopy goes out of scope here and is marked for garbage
			// collection. Force it, because it is probably quite large.
			// The same applies to bitmap.
			BmpCopy.Dispose();
			//bitmap.Dispose();
			return bitmap;
		}

19 Source : SensorNotifyIcon.cs
with MIT License
from AlexGyver

public void Dispose() {      
      Icon icon = notifyIcon.Icon;
      notifyIcon.Icon = null;
      if (icon != null)
        icon.Dispose();      
      notifyIcon.Dispose();

      if (brush != null)
        brush.Dispose();
      if (darkBrush != null)
        darkBrush.Dispose();
      pen.Dispose();
      graphics.Dispose();      
      bitmap.Dispose();
      font.Dispose();
      smallFont.Dispose();
    }

19 Source : TabBar.cs
with GNU General Public License v3.0
from alexgracianoarj

private float MeasureWidth(string text)
			{
				Graphics g = parent.CreateGraphics();

				SizeF textSize = g.MeasureString(text, parent.activeTabFont,
					parent.MaxTabWidth, parent.stringFormat);
				g.Dispose();

				return textSize.Width;
			}

19 Source : GadgetWindow.cs
with MIT License
from AlexGyver

private void DisposeBuffer() {
      graphics.Dispose();
      NativeMethods.DeleteDC(handleBitmapDC);
    }

19 Source : GifDecoder.cs
with MIT License
from AlexGyver

private void SetPixels() 
		{
			// expose destination image's pixels as int array
			//		int[] dest =
			//			(( int ) image.getRaster().getDataBuffer()).getData();
			int[] dest = GetPixels( bitmap );

			// fill in starting image contents based on last image's dispose code
			if (lastDispose > 0) 
			{
				if (lastDispose == 3) 
				{
					// use image before last
					int n = frameCount - 2;
					if (n > 0) 
					{
						lastImage = GetFrame(n - 1).Image;
					} 
					else 
					{
						lastImage = null;
					}
				}

				if (lastImage != null) 
				{
					//				int[] prev =
					//					((DataBufferInt) lastImage.getRaster().getDataBuffer()).getData();
					int[] prev = GetPixels( new Bitmap( lastImage ) );
					Array.Copy(prev, 0, dest, 0, width * height);
					// copy pixels

					if (lastDispose == 2) 
					{
						// fill last image rect area with background color
						Graphics g = Graphics.FromImage( image );
						Color c = Color.Empty;
						if (transparency) 
						{
							c = Color.FromArgb( 0, 0, 0, 0 ); 	// replacedume background is transparent
						} 
						else 
						{
							c = Color.FromArgb( lastBgColor ) ;
							//						c = new Color(lastBgColor); // use given background color
						}
						Brush brush = new SolidBrush( c );
						g.FillRectangle( brush, lastRect );
						brush.Dispose();
						g.Dispose();
					}
				}
			}

			// copy each source line to the appropriate place in the destination
			int preplaced = 1;
			int inc = 8;
			int iline = 0;
			for (int i = 0; i < ih; i++) 
			{
				int line = i;
				if (interlace) 
				{
					if (iline >= ih) 
					{
						preplaced++;
						switch (preplaced) 
						{
							case 2 :
								iline = 4;
								break;
							case 3 :
								iline = 2;
								inc = 4;
								break;
							case 4 :
								iline = 1;
								inc = 2;
								break;
						}
					}
					line = iline;
					iline += inc;
				}
				line += iy;
				if (line < height) 
				{
					int k = line * width;
					int dx = k + ix; // start of line in dest
					int dlim = dx + iw; // end of dest line
					if ((k + width) < dlim) 
					{
						dlim = k + width; // past dest edge
					}
					int sx = i * iw; // start of line in source
					while (dx < dlim) 
					{
						// map color and insert in destination
						int index = ((int) pixels[sx++]) & 0xff;
						int c = act[index];
						if (c != 0) 
						{
							dest[dx] = c;
						}
						dx++;
					}
				}
			}
			SetPixels( dest );
		}

19 Source : ImageCreator.cs
with GNU General Public License v3.0
from alexgracianoarj

private static void SaveAsImage(IPrintable doreplacedent, string path,
			ImageFormat format, bool selectedOnly, bool transparent)
		{
			const int Margin = 20;

			RectangleF areaF = doreplacedent.GetPrintingArea(selectedOnly);
			areaF.Offset(0.5F, 0.5F);
			Rectangle area = Rectangle.FromLTRB((int) areaF.Left, (int) areaF.Top,
				(int) Math.Ceiling(areaF.Right), (int) Math.Ceiling(areaF.Bottom));

			if (format == ImageFormat.Emf) // Save to metafile
			{
				Graphics metaG = control.CreateGraphics();
				IntPtr hc = metaG.GetHdc();
				Graphics g = null;

				try
				{
					// Set drawing parameters
					Metafile meta = new Metafile(path, hc);
					g = Graphics.FromImage(meta);
					g.SmoothingMode = SmoothingMode.HighQuality;
					if (DiagramEditor.Settings.Default.UseClearTypeForImages)
						g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
					else
						g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
					g.TranslateTransform(-area.Left, -area.Top);

					// Draw image
					IGraphics graphics = new GdiGraphics(g);
					doreplacedent.Print(graphics, selectedOnly, Style.CurrentStyle);

					meta.Dispose();
				}
				catch (Exception ex)
				{
					MessageBox.Show(
						string.Format("{0}\n{1}: {2}", Strings.ErrorInSavingImage,
							Strings.ErrorsReason, ex.Message),
						Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				finally
				{
					metaG.ReleaseHdc();
					metaG.Dispose();
					if (g != null)
						g.Dispose();
				}
			}
			else // Save to rastered image
			{
				int width = area.Width + Margin * 2;
				int height = area.Height + Margin * 2;
				PixelFormat pixelFormat;

				if (transparent)
					pixelFormat = PixelFormat.Format32bppArgb;
				else
					pixelFormat = PixelFormat.Format24bppRgb;

				using (Bitmap image = new Bitmap(width, height, pixelFormat))
				using (Graphics g = Graphics.FromImage(image))
				{
					// Set drawing parameters
					g.SmoothingMode = SmoothingMode.HighQuality;
					if (DiagramEditor.Settings.Default.UseClearTypeForImages && !transparent)
						g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
					else
						g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit;
					g.TranslateTransform(Margin - area.Left, Margin - area.Top);

					// Draw image
					if (!transparent)
						g.Clear(Style.CurrentStyle.BackgroundColor);

					IGraphics graphics = new GdiGraphics(g);
					doreplacedent.Print(graphics, selectedOnly, Style.CurrentStyle);

					try
					{
						image.Save(path, format);
					}
					catch (Exception ex)
					{
						MessageBox.Show(
							string.Format("{0}\n{1}: {2}", Strings.ErrorInSavingImage,
								Strings.ErrorsReason, ex.Message),
							Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
				}
			}
		}

19 Source : MainForm.cs
with Apache License 2.0
from alibaba

private void mainPictureBox_Move(object sender, MouseEventArgs e)
        {
            if (e.X < rgIMD[cur].w + 2 * extend && e.Y < rgIMD[cur].h + 2 * extend)
            {
                this.Cursor = Cursors.Cross;
                Click0Label.Text = "" + e.X + "/" + (rgIMD[cur].w + 2 * extend) + ", " + e.Y + "/" + (rgIMD[cur].w + 2 * extend);

                if (ptr == -1)
                {
                    Bitmap dest = (Bitmap)bmp.Clone();
                    Graphics g = Graphics.FromImage(dest);
                    Pen p = new Pen(Color.Blue, 1);
                    g.DrawLine(p, new Point(e.X, e.Y - 20), new Point(e.X, e.Y + 20));
                    g.DrawLine(p, new Point(e.X - 20, e.Y), new Point(e.X + 20, e.Y));
                    g.Dispose();
                    p.Dispose();
                    Graphics g1 = this.mainPictureBox.CreateGraphics();
                    g1.DrawImage(dest, new Point(0, 0));
                    g1.Dispose();
                    dest.Dispose();
                }
                else if (ptr == 0) {
                    Bitmap dest = (Bitmap)bmp.Clone();
                    Graphics g = Graphics.FromImage(dest);
                    Pen p = new Pen(Color.Blue, 1);
                    newpoint[0] = clkpoint[0];
                    newpoint[2].X = e.X;
                    newpoint[2].Y = e.Y;
                    newpoint[1].X = clkpoint[0].X;
                    newpoint[1].Y = e.Y;
                    newpoint[3].X = e.X;
                    newpoint[3].Y = clkpoint[0].Y;
                    g.DrawPolygon(p, newpoint);
                    g.Dispose();
                    p.Dispose();
                    Graphics g1 = this.mainPictureBox.CreateGraphics();
                    g1.DrawImage(dest, new Point(0, 0));
                    g1.Dispose();
                    dest.Dispose();
                }
                else if (ptr == 1)
                {
                    Bitmap dest = (Bitmap)bmp.Clone();
                    Graphics g = Graphics.FromImage(dest);
                    Pen p = new Pen(Color.Blue, 1);
                    if (clkpoint[1].X < clkpoint[0].X)
                    {
                        newpoint[0] = new Point(clkpoint[1].X, clkpoint[1].Y);
                        newpoint[2] = new Point(clkpoint[0].X, clkpoint[0].Y);
                    }
                    else
                    {
                        newpoint[0] = new Point(clkpoint[0].X, clkpoint[0].Y);
                        newpoint[2] = new Point(clkpoint[1].X, clkpoint[1].Y);
                    }
                    double pang = Math.Atan2((double)(e.Y - newpoint[0].Y), (double)(e.X - newpoint[0].X));
                    ang = (int)(pang / Math.PI * 180.0);
                    Click2Label.Text = "" + ang + "°";
                    if (ang == 0 || ang == 90 || ang == -90)
                    {
                        newpoint[1] = new Point(newpoint[0].X, newpoint[2].Y);
                        newpoint[3] = new Point(newpoint[2].X, newpoint[0].Y);
                    }
                    else
                    {
                        double alp = ang / 180.0 * Math.PI;
                        double beta = Math.Atan2((double)(newpoint[2].Y - newpoint[0].Y), (double)(newpoint[2].X - newpoint[0].X));
                        double le = Math.Sqrt((newpoint[2].Y - newpoint[0].Y) * (newpoint[2].Y - newpoint[0].Y) + (newpoint[2].X - newpoint[0].X) * (newpoint[2].X - newpoint[0].X));
                        int mx = (int)(le * Math.Cos(alp - beta) * Math.Cos(alp));
                        int my = (int)(le * Math.Cos(alp - beta) * Math.Sin(alp));
                        newpoint[1] = new Point(newpoint[0].X + mx, newpoint[0].Y + my);
                        newpoint[3] = new Point(newpoint[2].X - mx, newpoint[2].Y - my);
                    }
                    g.DrawPolygon(p,newpoint);
                    g.Dispose();
                    p.Dispose();
                    Graphics g1 = this.mainPictureBox.CreateGraphics();
                    g1.DrawImage(dest, new Point(0, 0));
                    g1.Dispose();
                    dest.Dispose();
                }
            }
            else
            {
                this.Cursor = Cursors.Default;
                Click0Label.Text = "" + e.X + "/" + (rgIMD[cur].w + 2 * extend) + ", " + e.Y + "/" + (rgIMD[cur].w + 2 * extend);
            }
        }

19 Source : MainForm.cs
with Apache License 2.0
from alibaba

private void sealButton_Click(object sender, EventArgs e)
        {
            if (1 == ptr && clkpoint[0].X != clkpoint[1].X && clkpoint[0].Y != clkpoint[1].Y)
            {
                newpoint[0] = clkpoint[0];
                newpoint[2] = clkpoint[1];
                newpoint[1].X = clkpoint[0].X;
                newpoint[1].Y = clkpoint[1].Y;
                newpoint[3].X = clkpoint[1].X;
                newpoint[3].Y = clkpoint[0].Y;
                ang = 0;
                Bitmap dest = (Bitmap)bmp.Clone();
                Graphics g = Graphics.FromImage(dest);
                Pen p = new Pen(Color.Blue, 1);
                g.DrawPolygon(p, newpoint);
                g.Dispose();
                p.Dispose();
                Graphics g1 = this.mainPictureBox.CreateGraphics();
                g1.DrawImage(dest, new Point(0, 0));
                g1.Dispose();
                dest.Dispose();
                ptr = 2;
                sealButton.Enabled = false;
                Confirm.Enabled = true;
                Click2Label.Text = "" + ang + "°";
            }
            else
            {
                MessageBox.Show("Wrong Seal!");
            }
            //OperateClick();
        }

19 Source : MainForm.cs
with Apache License 2.0
from alibaba

private void mainPictureBox_Click(object sender, MouseEventArgs e)
        {
            if (e.X < rgIMD[cur].w+2*extend && e.Y < rgIMD[cur].h+2*extend)
            {
                ptr++;
                if (ptr < 2)
                    clkpoint[ptr] = new Point(e.X, e.Y);

                sealButton.Enabled = false;
                if (0 == ptr)
                {
                    undoButton.Enabled = false;
                    clearButton.Enabled = false;
                    redrawButton.Enabled = true;
                }
                else if (1 == ptr)
                {
                    sealButton.Enabled = true;
                }
                else if (2 == ptr)
                {
                    Bitmap dest = (Bitmap)bmp.Clone();
                    Graphics g = Graphics.FromImage(dest);
                    Pen p = new Pen(Color.Blue, 1);
                    if (clkpoint[1].X < clkpoint[0].X)
                    {
                        newpoint[0] = new Point(clkpoint[1].X, clkpoint[1].Y);
                        newpoint[2] = new Point(clkpoint[0].X, clkpoint[0].Y);
                    }
                    else
                    {
                        newpoint[0] = new Point(clkpoint[0].X, clkpoint[0].Y);
                        newpoint[2] = new Point(clkpoint[1].X, clkpoint[1].Y);
                    }
                    double pang = Math.Atan2((double)(e.Y - newpoint[0].Y), (double)(e.X - newpoint[0].X));
                    ang = (int)(pang / Math.PI * 180.0);
                    Click2Label.Text = "" + ang + "°";
                    if (ang == 0 || ang == 90 || ang == -90)
                    {
                        newpoint[1] = new Point(newpoint[0].X, newpoint[2].Y);
                        newpoint[3] = new Point(newpoint[2].X, newpoint[0].Y);
                    }
                    else
                    {
                        double alp = ang / 180.0 * Math.PI;
                        double beta = Math.Atan2((double)(newpoint[2].Y - newpoint[0].Y), (double)(newpoint[2].X - newpoint[0].X));
                        double le = Math.Sqrt((newpoint[2].Y - newpoint[0].Y) * (newpoint[2].Y - newpoint[0].Y) + (newpoint[2].X - newpoint[0].X) * (newpoint[2].X - newpoint[0].X));
                        int mx = (int)(le * Math.Cos(alp - beta) * Math.Cos(alp));
                        int my = (int)(le * Math.Cos(alp - beta) * Math.Sin(alp));
                        newpoint[1] = new Point(newpoint[0].X + mx, newpoint[0].Y + my);
                        newpoint[3] = new Point(newpoint[2].X - mx, newpoint[2].Y - my);
                    }
                    g.DrawPolygon(p, newpoint);
                    g.Dispose();
                    p.Dispose();
                    Graphics g1 = this.mainPictureBox.CreateGraphics();
                    g1.DrawImage(dest, new Point(0, 0));
                    g1.Dispose();
                    dest.Dispose();
                    sealButton.Enabled = false;
                    Confirm.Enabled = true;
                }
            }
        }

19 Source : loading.cs
with MIT License
from Amine-Smahi

private void t_Tick(object sender, EventArgs e)
        {
            g = Graphics.FromImage(bmp);
            g.Clear(Color.White);
            var myBrush = new SolidBrush(Color.FromArgb(37, 155, 36));
            g.FillRectangle(myBrush, new Rectangle(0, 0, (int) (pbComplete * pbUnit), pbHEIGHT));


            if (pbComplete == 60)
            {

                FileInfo fi = new FileInfo(@".\a\lang.txt");
                DirectoryInfo di = new DirectoryInfo(@".\a");
                if (!di.Exists)
                {
                    di.Create();
                }
                if (!fi.Exists)
                {
                    fi.Create().Dispose();
                }

                /* if (!File.Exists(path))
                 {
                     File.Create(path).Dispose();
                     using (TextWriter tw = new StreamWriter(path))
                     {
                         tw.WriteLine("english");
                         tw.Close();
                     }
                 }
                 */
            }

            if (pbComplete == 70)
                if (File.Exists(path))
                    using (TextReader tr = new StreamReader(path))
                    {
                        var langugeChoused = tr.ReadLine();

                        if (langugeChoused == "arabic")
                        {
                            fom.bunifuTileButton1.LabelText = "إفتح صورة";
                            fom.bunifuTileButton2.LabelText = "إحفظ الصورة";
                            fom.bunifuTileButton3.LabelText = "أكتب الرسالة";
                            fom.bunifuTileButton4.LabelText = "أظهر الصورة";
                            fom.about_us.LabelText = "عن البرنامج";
                            fom.bunifuTileButton6.LabelText = "إعداداتي";
                        }
                    }

            picboxPB.Image = bmp;
            pbComplete++;

            if (pbComplete > 100)
            {
                g.Dispose();
                t.Stop();
                Hide();

                fom.Show();
            }
        }

19 Source : DiffOverview.cs
with Apache License 2.0
from AmpScm

private void RenderImage()
        {
            if (m_Image != null)
            {
                m_Image.Dispose();
                m_Image = null;
            }

            int iWidth = ClientSize.Width;
            int iHeight = ClientSize.Height;

            if (iWidth > 0 && iHeight > 0 && m_View != null && m_View.Lines != null)
            {
                //Draw a bitmap in memory that we can render from
                m_Image = new Bitmap(iWidth, iHeight);
                Graphics G = Graphics.FromImage(m_Image);

                SolidBrush B = new SolidBrush(BackColor);
                G.FillRectangle(B, 0, 0, iWidth, iHeight);

                const float c_fGutter = 2.0F;
                //Make sure each line is at least 1 pixel high
                float fLineHeight = (float)Math.Max(1.0, GetPixelLineHeightF(1));
                DiffViewLines Lines = m_View.Lines;
                int iNumLines = Lines.Count;
                for (int i = 0; i < iNumLines; i++)
                {
                    DiffViewLine L = Lines[i];
                    if (L.Edited)
                    {
                        B.Color = DiffOptions.GetColorForEditType(L.EditType);
                        float fY = GetPixelLineHeightF(i);
                        G.FillRectangle(B, c_fGutter, fY, iWidth - 2 * c_fGutter, fLineHeight);
                    }
                }

                B.Dispose();
                G.Dispose();
            }
        }

19 Source : DockersTabsControl.cs
with GNU General Public License v3.0
from anotak

protected unsafe void RedrawTabs()
		{
			// Determine length and width in pixels
			int tabslength = 0;
			for(int i = 0; i < this.TabPages.Count; i++)
			{
				Rectangle r = this.GetTabRect(i);
				tabslength += r.Height;
			}
			tabslength += 4;
			int tabswidth = this.ItemSize.Height + 2;
			
			// Dispose old image
			if(tabsimage != null)
			{
				tabsimage.Dispose();
				tabsimage = null;
			}
			
			if(VisualStyleInformation.IsSupportedByOS && VisualStyleInformation.IsEnabledByUser)
			{
				StringFormat drawformat = new StringFormat();
				drawformat.Alignment = StringAlignment.Center;
				drawformat.HotkeyPrefix = HotkeyPrefix.None;
				drawformat.LineAlignment = StringAlignment.Center;
				
				// Create images
				tabsimage = new Bitmap(tabswidth, tabslength, PixelFormat.Format32bppArgb);
				Bitmap drawimage = new Bitmap(tabslength, tabswidth, PixelFormat.Format32bppArgb);
				Graphics g = Graphics.FromImage(drawimage);
				
				// Render the tabs (backwards when right-aligned)
				int posoffset = 0;
				int selectedposoffset = -1;
				int start = (this.Alignment == TabAlignment.Left) ? 0 : (this.TabPages.Count - 1);
				int end = (this.Alignment == TabAlignment.Left) ? this.TabPages.Count : -1;
				int step = (this.Alignment == TabAlignment.Left) ? 1 : -1;
				for(int i = start; i != end; i += step)
				{
					VisualStyleRenderer renderer;
					Rectangle tr = this.GetTabRect(i);
					
					// Tab selected?
					if(i == this.SelectedIndex)
					{
						// We will draw this later
						selectedposoffset = posoffset;
					}
					else
					{
						if(i == highlighttab)
							renderer = new VisualStyleRenderer(VisualStyleElement.Tab.TabItem.Hot);
						else
							renderer = new VisualStyleRenderer(VisualStyleElement.Tab.TabItem.Normal);
						
						// Draw tab
						Rectangle r = new Rectangle(posoffset + 2, 2, tr.Height, tr.Width - 2);
						renderer.DrawBackground(g, r);
						g.DrawString(this.TabPages[i].Text, this.Font, SystemBrushes.ControlText, new RectangleF(r.Location, r.Size), drawformat);
					}
					
					posoffset += tr.Height;
				}
				
				// Render the selected tab, because it is slightly larger and overlapping the others
				if(selectedposoffset > -1)
				{
					VisualStyleRenderer renderer = new VisualStyleRenderer(VisualStyleElement.Tab.TabItem.Pressed);
					Rectangle tr = this.GetTabRect(this.SelectedIndex);
					Rectangle r = new Rectangle(selectedposoffset, 0, tr.Height + 4, tr.Width);
					renderer.DrawBackground(g, r);
					g.DrawString(this.TabPages[this.SelectedIndex].Text, this.Font, SystemBrushes.ControlText, new RectangleF(r.X, r.Y, r.Width, r.Height - 2), drawformat);
				}
				
				// Rotate the image and copy to tabsimage
				BitmapData drawndata = drawimage.LockBits(new Rectangle(0, 0, drawimage.Size.Width, drawimage.Size.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
				BitmapData targetdata = tabsimage.LockBits(new Rectangle(0, 0, tabsimage.Size.Width, tabsimage.Size.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);
				int* dd = (int*)drawndata.Scan0.ToPointer();
				int* td = (int*)targetdata.Scan0.ToPointer();
				if(this.Alignment == TabAlignment.Right)
				{
					for(int y = 0; y < drawndata.Height; y++)
					{
						for(int x = 0; x < drawndata.Width; x++)
						{
							td[(drawndata.Width - 1 - x) * targetdata.Width + y] = *dd;
							dd++;
						}
					}
				}
				else
				{
					for(int y = 0; y < drawndata.Height; y++)
					{
						for(int x = 0; x < drawndata.Width; x++)
						{
							td[x * targetdata.Width + (drawndata.Height - 1 - y)] = *dd;
							dd++;
						}
					}
				}
				drawimage.UnlockBits(drawndata);
				tabsimage.UnlockBits(targetdata);
				
				// Clean up
				g.Dispose();
				drawimage.Dispose();
			}
		}

19 Source : ImageData.cs
with GNU General Public License v3.0
from anotak

protected virtual void LocalLoadImage()
		{
			BitmapData bmpdata = null;
			
			lock(this)
			{
				// Bitmap loaded successfully?
				if(bitmap != null)
				{
					// Bitmap has incorrect format?
					if(bitmap.PixelFormat != PixelFormat.Format32bppArgb)
					{
						if(dynamictexture)
							throw new Exception("Dynamic images must be in 32 bits ARGB format.");
						
						//General.ErrorLogger.Add(ErrorType.Warning, "Image '" + name + "' does not have A8R8G8B8 pixel format. Conversion was needed.");
						Bitmap oldbitmap = bitmap;
						try
						{
							// Convert to desired pixel format
							bitmap = new Bitmap(oldbitmap.Size.Width, oldbitmap.Size.Height, PixelFormat.Format32bppArgb);
							Graphics g = Graphics.FromImage(bitmap);
							g.PageUnit = GraphicsUnit.Pixel;
							g.CompositingQuality = CompositingQuality.HighQuality;
							g.InterpolationMode = InterpolationMode.NearestNeighbor;
							g.SmoothingMode = SmoothingMode.None;
							g.PixelOffsetMode = PixelOffsetMode.None;
							g.Clear(Color.Transparent);
							g.DrawImage(oldbitmap, 0, 0, oldbitmap.Size.Width, oldbitmap.Size.Height);
							g.Dispose();
							oldbitmap.Dispose();
						}
						catch(Exception e)
						{
							bitmap = oldbitmap;
							General.ErrorLogger.Add(ErrorType.Warning, "Cannot lock image '" + name + "' for pixel format conversion. The image may not be displayed correctly.\n" + e.GetType().Name + ": " + e.Message);
						}
					}
					
					// This applies brightness correction on the image
					if(usecolorcorrection)
					{
						try
						{
							// Try locking the bitmap
							bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Size.Width, bitmap.Size.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
						}
						catch(Exception e)
						{
							General.ErrorLogger.Add(ErrorType.Warning, "Cannot lock image '" + name + "' for color correction. The image may not be displayed correctly.\n" + e.GetType().Name + ": " + e.Message);
						}

						// Bitmap locked?
						if(bmpdata != null)
						{
							// Apply color correction
							PixelColor* pixels = (PixelColor*)(bmpdata.Scan0.ToPointer());
							General.Colors.ApplColorCorrection(pixels, bmpdata.Width * bmpdata.Height);
							bitmap.UnlockBits(bmpdata);
						}
					}
				}
				else
				{
					// Loading failed
					// We still mark the image as ready so that it will
					// not try loading again until Reload Resources is used
					loadfailed = true;
					bitmap = new Bitmap(Properties.Resources.Failed);
				}

				if(bitmap != null)
				{
					width = bitmap.Size.Width;
					height = bitmap.Size.Height;

					if(dynamictexture)
					{
						if((width != General.NextPowerOf2(width)) || (height != General.NextPowerOf2(height)))
							throw new Exception("Dynamic images must have a size in powers of 2.");
					}

					// Do we still have to set a scale?
					if((scale.x == 0.0f) && (scale.y == 0.0f))
					{
						if((General.Map != null) && (General.Map.Config != null))
						{
							scale.x = General.Map.Config.DefaultTextureScale;
							scale.y = General.Map.Config.DefaultTextureScale;
						}
						else
						{
							scale.x = 1.0f;
							scale.y = 1.0f;
						}
					}
				}
				
				// Image is ready
				imagestate = ImageLoadState.Ready;
			}
		}

19 Source : PreviewManager.cs
with GNU General Public License v3.0
from anotak

private void MakeImagePreview(ImageData img)
		{
			int previewwidth, previewheight;
			int imagewidth, imageheight;
			Bitmap preview;
			Graphics g;
			
			lock(img)
			{
				// Load image if needed
				if(!img.IsImageLoaded) img.LoadImage();
				if(!img.LoadFailed)
				{
					imagewidth = img.Width;
					imageheight = img.Height;
				}
				else
				{
					imagewidth = img.GetBitmap().Size.Width;
					imageheight = img.GetBitmap().Size.Height;
				}
				
				// Determine preview size
				float scalex = (img.Width > maxpreviewwidth) ? ((float)maxpreviewwidth / (float)imagewidth) : 1.0f;
				float scaley = (img.Height > maxpreviewheight) ? ((float)maxpreviewheight / (float)imageheight) : 1.0f;
				float scale = Math.Min(scalex, scaley);
				previewwidth = (int)((float)imagewidth * scale);
				previewheight = (int)((float)imageheight * scale);
				if(previewwidth < 1) previewwidth = 1;
				if(previewheight < 1) previewheight = 1;

				// Make new image
				preview = new Bitmap(previewwidth, previewheight, IMAGE_FORMAT);
				g = Graphics.FromImage(preview);
				g.PageUnit = GraphicsUnit.Pixel;
				g.CompositingQuality = CompositingQuality.HighQuality;
				g.InterpolationMode = InterpolationMode.HighQualityBicubic;
				g.SmoothingMode = SmoothingMode.HighQuality;
				g.PixelOffsetMode = PixelOffsetMode.None;
				g.Clear(Color.Transparent);
				
				// Draw image onto atlas
				Rectangle atlasrect = new Rectangle(0, 0, previewwidth, previewheight);
				RectangleF imgrect = General.MakeZoomedRect(new Size(imagewidth, imageheight), atlasrect);
				if(imgrect.Width < 1.0f)
				{
					imgrect.X -= 0.5f - imgrect.Width * 0.5f;
					imgrect.Width = 1.0f;
				}
				if(imgrect.Height < 1.0f)
				{
					imgrect.Y -= 0.5f - imgrect.Height * 0.5f;
					imgrect.Height = 1.0f;
				}
				g.DrawImage(img.GetBitmap(), imgrect);
				g.Dispose();
				
				// Unload image if no longer needed
				if(!img.IsReferenced) img.UnloadImage();
				
				lock(images)
				{
					// Set numbers
					img.PreviewIndex = images.Count;
					img.PreviewState = ImageLoadState.Ready;
					
					// Add to previews list
					images.Add(preview);
				}
			}
		}

19 Source : ScreenCapture.cs
with MIT License
from AristotelisChantzaras

public static IEnumerable<Image> Snapshots(int width, int height, bool showCursor, Func<bool> stop=null)
        {
            Size size = new Size(System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width, System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height);

            Bitmap srcImage = new Bitmap(size.Width, size.Height);
            Graphics srcGraphics = Graphics.FromImage(srcImage);

            bool scaled = (width != size.Width || height != size.Height);

            Bitmap dstImage = srcImage;
            Graphics dstGraphics = srcGraphics;

            if (scaled)
            {
                dstImage = new Bitmap(width, height);
                dstGraphics = Graphics.FromImage(dstImage);
            }

            Rectangle src = new Rectangle(0, 0, size.Width, size.Height);
            Rectangle dst = new Rectangle(0, 0, width, height);
            Size curSize = new Size(32, 32);

            while (true)
            {
                if ((stop != null) && stop())
                {
                    //cleanup
                    srcGraphics.Dispose();
                    dstGraphics.Dispose();
                    srcImage.Dispose();
                    dstImage.Dispose();

                    yield break;
                }

                srcGraphics.CopyFromScreen(0, 0, 0, 0, size);

                if (showCursor)
                    Cursors.Default.Draw(srcGraphics, new Rectangle(Cursor.Position, curSize));

                if (scaled)
                    dstGraphics.DrawImage(srcImage, dst, src, GraphicsUnit.Pixel);

                yield return dstImage;
            }

        }

19 Source : Functions.cs
with MIT License
from arsium

private static byte[] Capture(int W, int H, int Q, string F, short M = 0)
		{
			try
			{
				Bitmap img = new Bitmap(Screen.AllScreens[0].Bounds.Width, Screen.AllScreens[M].Bounds.Height);

				Graphics graphics = Graphics.FromImage(img);

				graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;

				graphics.CopyFromScreen(0, 0, 0, 0, new Size(Screen.AllScreens[M].Bounds.Width, Screen.AllScreens[M].Bounds.Height), CopyPixelOperation.SourceCopy);

				Point P = new Point();

				GetCursorPos(out P);

				CURSORINFOHELPER CS = new CURSORINFOHELPER();

				CS.cbSize = Marshal.SizeOf(CS);

				GetCursorInfo(ref CS);

				if (CS.flags == 0x1) 
				{
					graphics.DrawIcon(Icon.FromHandle(CS.hCursor), P.X, P.Y);
				}

				Bitmap Resize = new Bitmap(W, H);
				Graphics g2 = Graphics.FromImage(Resize);
				g2.CompositingQuality = CompositingQuality.HighSpeed;
				g2.DrawImage(img, new Rectangle(0, 0, W, H), new Rectangle(0, 0, Screen.AllScreens[M].Bounds.Width, Screen.AllScreens[M].Bounds.Height), GraphicsUnit.Pixel);

				EncoderParameter encoderParameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Q);
				ImageCodecInfo encoderInfo = null;

				if (F == "PNG")
				{
					encoderInfo = GetEncoderInfo(ImageFormat.Png);
				}
				else if (F == "JPEG")
				{
					encoderInfo = GetEncoderInfo(ImageFormat.Jpeg);
				}
				else if (F == "GIF")
				{
					encoderInfo = GetEncoderInfo(ImageFormat.Gif);
				}

				EncoderParameters encoderParameters = new EncoderParameters(1);
				encoderParameters.Param[0] = encoderParameter;
				System.IO.MemoryStream MS = new System.IO.MemoryStream();
				Resize.Save(MS, encoderInfo, encoderParameters);
				graphics.Dispose();
				g2.Dispose();
				img.Dispose();
				Resize.Dispose();
				MS.Dispose();
				encoderParameter.Dispose();
				encoderParameters.Dispose();
				return MS.ToArray();
			}
			catch{}
			return null;
		}

19 Source : Textures.cs
with GNU General Public License v2.0
from Asixa

public static Bitmap KiResizeImage(Bitmap bmp, int newW, int newH)
        {
            try
            {
                var b = new Bitmap(newW, newH);
                var g = Graphics.FromImage(b);

                // 插值算法的质量
                g.InterpolationMode = InterpolationMode.HighQualityBilinear;

                g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
                g.Dispose();

                return b;
            }
            catch
            {
                return null;
            }
        }

19 Source : Input.cs
with Apache License 2.0
from atasoyhus

private Bitmap resizeBitmap(Bitmap b, ResizingMethod resizingMethod)
        {
            Bitmap resizedBmp = new Bitmap(inputSize[1], inputSize[0], PixelFormat.Format24bppRgb);
            Graphics gr = Graphics.FromImage(resizedBmp);

            if (resizingMethod == ResizingMethod.Stretch)
                gr.DrawImage(b, 0, 0, inputSize[1], inputSize[0]);
            else
            {
                float inputAspRatio = inputSize[0] / inputSize[1];

                int newHeight, newWidth;
                float multiplier = (float)b.Width / b.Height;
                if (multiplier > inputAspRatio)
                {
                    multiplier = inputAspRatio / multiplier;
                    newWidth = inputSize[1];
                    newHeight = (int)(newWidth * multiplier);
                }
                else
                {
                    newHeight = inputSize[0];
                    newWidth = (int)(newHeight * multiplier);
                }

                gr.DrawImage(b, (inputSize[1] - newWidth) / 2.0f, (inputSize[0] - newHeight) / 2.0f, newWidth, newHeight);
            }

            gr.Dispose();

            return resizedBmp;
        }

19 Source : SimpleProgressBar.cs
with MIT License
from AutoItConsulting

protected override void OnPaint(PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            var brush = new SolidBrush(ForeColor);
            float percent = (_val - _min) / (float)(_max - _min);
            Rectangle rect = ClientRectangle;

            // Calculate area for drawing the progress.
            rect.Width = (int)(rect.Width * percent);

            // Draw the progress meter.
            g.FillRectangle(brush, rect);

            // Draw a three-dimensional border around the control.
            if (DrawBorder)
            {
                Draw3DBorder(g);
            }

            // Clean up.
            brush.Dispose();
            g.Dispose();
        }

19 Source : 图印Tabpage.cs
with Apache License 2.0
from becomequantum

private void 初始化原图(Bitmap 图片) {
            原图 = new Bitmap(图片.Width, 图片.Height, PixelFormat.Format32bppArgb);//要用这个Argb而不是PArgb.
            水印图 = new Bitmap(图片.Width, 图片.Height, PixelFormat.Format32bppArgb);

            if (图片.PixelFormat == PixelFormat.Format24bppRgb)
                图像.原图24刷新图32(图片, 原图);
            else if (图片.PixelFormat == PixelFormat.Format32bppPArgb || 图片.PixelFormat == PixelFormat.Format32bppArgb || 图片.PixelFormat == PixelFormat.Format32bppRgb)
                图像.原图刷新图32(图片, 原图);
            else {
                Graphics g = Graphics.FromImage(原图);
                g.DrawImage(图片, 0, 0);
                g.Dispose();
            }
            图片框.Image = 原图;
            图像.原图刷新图32(原图, 水印图);

        }

19 Source : 水印.cs
with Apache License 2.0
from becomequantum

public static void 加水印(Bitmap 原图, Bitmap 水印图, List<文印参数> 文印参数表, List<图印参数> 图印参数表) {
            Graphics g = Graphics.FromImage(水印图);
            if (原图.PixelFormat == PixelFormat.Format24bppRgb)
                图像.原图刷新图24(原图, 水印图);
            else if(原图.PixelFormat == PixelFormat.Format32bppArgb || 原图.PixelFormat == PixelFormat.Format32bppRgb || 原图.PixelFormat == PixelFormat.Format32bppPArgb)
                图像.原图刷新图32(原图, 水印图);
            else {
                g.DrawImage(原图, 0, 0);
            }
            
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            foreach (var 参数 in 图印参数表)
                加图印(g, 参数, 水印图.Width, 水印图.Height);
            foreach (var 参数 in 文印参数表) 
                加文印(g, 参数, 水印图.Width, 水印图.Height);
            
            g.Dispose();
        }

19 Source : 水印.cs
with Apache License 2.0
from becomequantum

private static void 加图印(Graphics g水印图, 图印参数 参数, int 图宽, int 图高) {
            if (参数.画啥 == 图形类别.图 && 参数.图印页 == null) return;
            Graphics g, g空 = g水印图;
            Bitmap 空背景 = null;
            if (参数.透明度波动 > 0) {
                空背景 = new Bitmap(图宽, 图高, PixelFormat.Format32bppArgb);
                g空 = Graphics.FromImage(空背景);
                g = g空;
            }
            else
                g = g水印图;
            Bitmap 水印图 = null;
            PointF 图印中心点= 参数.中心点 = new PointF(图宽 * 参数.X百分比, 图高 * 参数.Y百分比);
            int 短边长度 = 图宽 >= 图高 ? 图高 : 图宽;
            float 横间距 = 参数.横向百分比间距 * 图宽;
            横间距 = 横间距 > 33 ? 横间距 : 33;
            float 纵间距 = 参数.纵向百分比间距 * 图高;
            纵间距 = 纵间距 > 33 ? 纵间距 : 33;
            float 绘图矩形高度 = 短边长度 * 参数.大小百分比;
            绘图矩形高度 = 绘图矩形高度 < 33 ? 33 : 绘图矩形高度;
            float 绘图矩形宽度;
            float 字粗细 = 短边长度 * 参数.粗细 * 0.5f;
            Color 框颜色 = Color.FromArgb(参数.透明度, 参数.颜色);
            Pen 画框笔 = new Pen(框颜色, 字粗细);

            if (参数.画啥 == 图形类别.图) {
                水印图 = (Bitmap)参数.图印页.水印图;
                if (参数.图印页 == null || 水印图 == null) return;
                绘图矩形宽度 = 绘图矩形高度 * 水印图.Width / 水印图.Height;
                参数.大小 = new SizeF(绘图矩形宽度, 绘图矩形高度);
                图像.调透明度(参数.图印页.原图, 水印图, 参数.透明度);
            }
            else {
                绘图矩形宽度 = 绘图矩形高度 * 参数.宽高比;
                参数.大小 = new SizeF(绘图矩形宽度, 绘图矩形高度);
            }



            if (参数.横向复制个数 > 0 && 参数.纵向复制个数 > 0) {
                for (int i = 0; i <= 参数.纵向复制个数; i++)
                    for (int j = 0; j <= 参数.横向复制个数; j++) {
                        PointF 新图片中心点 = new PointF(图印中心点.X + 横间距 * j, 图印中心点.Y + 纵间距 * i);
                        画图片(g, 新图片中心点, 参数.旋转角度, 水印图, 绘图矩形宽度, 绘图矩形高度, 参数.画啥, 画框笔);
                    }
            }
            else {
                画图片(g, 图印中心点, 参数.旋转角度, 水印图, 绘图矩形宽度, 绘图矩形高度, 参数.画啥, 画框笔);
                if (参数.横向复制个数 > 0) {
                    for (int i = 1; i <= 参数.横向复制个数; i++) {
                        图印中心点 = new PointF(图印中心点.X + 横间距, 图印中心点.Y);
                        画图片(g, 图印中心点, 参数.旋转角度, 水印图, 绘图矩形宽度, 绘图矩形高度, 参数.画啥, 画框笔);
                    }
                }
                else if (参数.纵向复制个数 > 0) {
                    for (int i = 1; i <= 参数.纵向复制个数; i++) {
                        图印中心点 = new PointF(图印中心点.X, 图印中心点.Y + 纵间距);
                        画图片(g, 图印中心点, 参数.旋转角度, 水印图, 绘图矩形宽度, 绘图矩形高度, 参数.画啥, 画框笔);
                    }
                }
            }
            if (参数.透明度波动 > 0) {
                图像.颜色随机化(空背景, 参数.透明度波动);
                g水印图.DrawImage(空背景, 0, 0);
                g空.Dispose();
                空背景.Dispose();
            }
        }

19 Source : 水印.cs
with Apache License 2.0
from becomequantum

private static void 加文印(Graphics g水印图, 文印参数 参数, int 图宽, int 图高) {
            if (参数.文本.Length == 0) return;
            Graphics g, g空 = g水印图;
            Bitmap 空背景 = null;
            if (参数.透明度波动 > 0) {
                空背景 = new Bitmap(图宽, 图高, PixelFormat.Format32bppArgb);
                g空 = Graphics.FromImage(空背景);
                g = g空;
            }
            else
                g = g水印图;

            PointF 文本中心点 = 参数.中心点 = new PointF(图宽 * 参数.X百分比, 图高 * 参数.Y百分比);
            string 待绘文本 = 日期时间替换(参数.文本);
            int 短边长度 = 图宽 >= 图高 ? 图高 : 图宽;
            float 字体大小 = 短边长度 * 参数.大小百分比 * 0.8f;
            if (字体大小 < 11) 字体大小 = 11;
            Font 字体 = new Font(参数.字体, 字体大小,参数.粗体 | 参数.斜体 | 参数.下划线 | 参数.删除线);
            SizeF 文本大小 = 参数.大小 = g.MeasureString(待绘文本, 字体);
            PointF 文本位置 = new PointF( - 文本大小.Width / 2,  - 文本大小.Height / 2);
            Brush 画刷 = new SolidBrush(Color.FromArgb(参数.透明度,参数.颜色));
            float 横间距 = 参数.横向百分比间距 * 图宽;
            横间距 = 横间距 > 7 ? 横间距 : 7;
            float 纵间距 = 参数.纵向百分比间距 * 图高;
            纵间距 = 纵间距 > 7 ? 纵间距 : 7;



            if (参数.横向复制个数 > 0 && 参数.纵向复制个数 > 0) {
                for (int i = 0; i <= 参数.纵向复制个数; i++)
                    for (int j = 0; j <= 参数.横向复制个数; j++) {
                        PointF 新文本中心点 = new PointF(文本中心点.X + 横间距 * j, 文本中心点.Y + 纵间距 * i);
                        画文本(g, 新文本中心点, 参数.旋转角度, 待绘文本, 字体, 画刷, 文本位置);
                    }
            }
            else {
                画文本(g, 文本中心点, 参数.旋转角度, 待绘文本, 字体, 画刷, 文本位置);
                if (参数.横向复制个数 > 0) {
                    for (int i = 1; i <= 参数.横向复制个数; i++) {
                        文本中心点 = new PointF(文本中心点.X + 横间距, 文本中心点.Y);
                        画文本(g, 文本中心点, 参数.旋转角度, 待绘文本, 字体, 画刷, 文本位置);
                    }
                }
                else if (参数.纵向复制个数 > 0) {
                    for (int i = 1; i <= 参数.纵向复制个数; i++) {
                        文本中心点 = new PointF(文本中心点.X, 文本中心点.Y + 纵间距);
                        画文本(g, 文本中心点, 参数.旋转角度, 待绘文本, 字体, 画刷, 文本位置);
                    }
                }
            }

            if (参数.透明度波动 > 0) {
                图像.颜色随机化(空背景, 参数.透明度波动);
                g水印图.DrawImage(空背景, 0, 0);
                g空.Dispose();
                空背景.Dispose();
            }
            
        }

19 Source : MainForm.cs
with MIT License
from betacode-projects

private Image get_screen()
        {
            Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Graphics g = Graphics.FromImage(bmp);

            g.CopyFromScreen(new Point(0, 0), new Point(0, 0), bmp.Size);
            g.Dispose();

            return bmp;
        }

19 Source : SlippyRaster_DEPRECATED2021114.cs
with MIT License
from blueherongis

protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<Curve> boundary = new List<Curve>();
            DA.GetDataList(0, boundary);

            int zoom = -1;
            DA.GetData(1, ref zoom);

            string filePath = string.Empty;
            DA.GetData(2, ref filePath);
            if (!filePath.EndsWith(@"\")) filePath = filePath + @"\";

            string prefix = string.Empty;
            DA.GetData(3, ref prefix);
            if (prefix == string.Empty)
            {
                prefix = slippySource;
            }

            string URL = slippyURL;
            //DA.GetData<string>(4, ref URL);

            string userAgent = string.Empty;
            DA.GetData(4, ref userAgent);

            bool run = false;
            DA.GetData<bool>("Run", ref run);

            GH_Structure<GH_String> mapList = new GH_Structure<GH_String>();
            GH_Structure<GH_Rectangle> imgFrame = new GH_Structure<GH_Rectangle>();
            GH_Structure<GH_String> tCount = new GH_Structure<GH_String>();


            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path = new GH_Path(i);
                int tileTotalCount = 0;
                int tileDownloadedCount = 0;


                ///Get image frame for given boundary and  make sure it's valid
                if (!boundary[i].GetBoundingBox(true).IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                    return;
                }
                BoundingBox boundaryBox = boundary[i].GetBoundingBox(true);

                ///TODO: look into scaling boundary to get buffer tiles

                ///file path for final image
                string imgPath = filePath + prefix + "_" + i + ".jpg";

                ///location of final image file
                mapList.Append(new GH_String(imgPath), path);

                ///create cache folder for images
                string cacheLoc = filePath + @"HeronCache\";
                List<string> cachefilePaths = new List<string>();
                if (!Directory.Exists(cacheLoc))
                {
                    Directory.CreateDirectory(cacheLoc);
                }

                ///tile bounding box array
                List<Point3d> boxPtList = new List<Point3d>();

                ///get the tile coordinates for all tiles within boundary
                var ranges = Convert.GetTileRange(boundaryBox, zoom);
                List<List<int>> tileList = new List<List<int>>();
                var x_range = ranges.XRange;
                var y_range = ranges.YRange;

                if (x_range.Length > 100 || y_range.Length > 100)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units.");
                    return;
                }

                ///cycle through tiles to get bounding box
                for (int y = (int)y_range.Min; y <= y_range.Max; y++)
                {
                    for (int x = (int)x_range.Min; x <= x_range.Max; x++)
                    {
                        ///add bounding box of tile to list
                        boxPtList.AddRange(Convert.GetTileAsPolygon(zoom, y, x).ToList());
                        cachefilePaths.Add(cacheLoc + slippySource.Replace(" ", "") + zoom + x + y + ".jpg");
                        tileTotalCount = tileTotalCount + 1;
                    }
                }

                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                ///bounding box of tile boundaries
                BoundingBox bbox = new BoundingBox(boxPtList);

                var rect = BBoxToRect(bbox);
                imgFrame.Append(new GH_Rectangle(rect), path);

                AddPreviewItem(imgPath, boundary[i], rect);

                ///tile range as string for (de)serialization of TileCacheMeta
                string tileRangeString = zoom.ToString()
                    + x_range[0].ToString()
                    + y_range[0].ToString()
                    + x_range[1].ToString()
                    + y_range[1].ToString();

                ///check if the existing final image already covers the boundary. 
                ///if so, no need to download more or rereplacedemble the cached tiles.
                if ((TileCacheMeta == tileRangeString) && Convert.CheckCacheImagesExist(cachefilePaths))
                {
                    if (File.Exists(imgPath))
                    {
                        using (Bitmap imageT = new Bitmap(imgPath))
                        {
                            ///getting commments currently only working for JPG
                            ///TODO: get this to work for any image type or
                            ///find another way to check if the cached image covers the boundary.
                            string imgComment = imageT.GetCommentsFromJPG();

                            imageT.Dispose();

                            ///check to see if tilerange in comments matches current tilerange
                            if (imgComment == (slippySource.Replace(" ", "") + tileRangeString))
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using existing image.");
                                continue;
                            }

                        }

                    }

                }



                ///Query Slippy URL
                ///download all tiles within boundary
                ///merge tiles into one bitmap
                ///API to query


                ///Do the work of replacedembling image
                ///setup final image container bitmap
                int fImageW = ((int)x_range.Length + 1) * 256;
                int fImageH = ((int)y_range.Length + 1) * 256;
                Bitmap finalImage = new Bitmap(fImageW, fImageH);


                int imgPosW = 0;
                int imgPosH = 0;

                if (run == true)
                {
                    using (Graphics g = Graphics.FromImage(finalImage))
                    {
                        g.Clear(Color.Black);
                        for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++)
                        {
                            for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++)
                            {
                                //create tileCache name 
                                string tileCache = slippySource.Replace(" ", "") + zoom + x + y + ".jpg";
                                string tileCacheLoc = cacheLoc + tileCache;

                                //check cache folder to see if tile image exists locally
                                if (File.Exists(tileCacheLoc))
                                {
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCacheLoc));
                                    ///add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 256, imgPosH * 256);
                                    tmpImage.Dispose();
                                }

                                else
                                {
                                    tileList.Add(new List<int> { zoom, y, x });
                                    string urlAuth = Convert.GetZoomURL(x, y, zoom, slippyURL);

                                    System.Net.WebClient client = new System.Net.WebClient();

                                    ///insert header if required
                                    client.Headers.Add("user-agent", userAgent);

                                    client.DownloadFile(urlAuth, tileCacheLoc);
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCacheLoc));
                                    client.Dispose();

                                    //add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 256, imgPosH * 256);
                                    tmpImage.Dispose();
                                    tileDownloadedCount = tileDownloadedCount + 1;
                                }

                                //increment x insert position, goes left to right
                                imgPosW++;
                            }
                            //increment y insert position, goes top to bottom
                            imgPosH++;
                            imgPosW = 0;

                        }
                        //garbage collection
                        g.Dispose();

                        //add tile range meta data to image comments
                        finalImage.AddCommentsToJPG(slippySource.Replace(" ", "") + tileRangeString);

                        //save the image
                        finalImage.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                }

                //garbage collection
                finalImage.Dispose();


                //add to tile count total
                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                //write out new tile range metadata for serialization
                TileCacheMeta = tileRangeString;

            }


            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, tCount);
            ///Add copyright info here
            DA.SetDataList(3, "");

        }

19 Source : MapboxRaster_DEPRECATED20211114.cs
with MIT License
from blueherongis

protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<Curve> boundary = new List<Curve>();
            DA.GetDataList<Curve>(0, boundary);

            int zoom = -1;
            DA.GetData<int>(1, ref zoom);

            string folderPath = string.Empty;
            DA.GetData<string>(2, ref folderPath);
            if (!folderPath.EndsWith(@"\")) folderPath = folderPath + @"\";

            string prefix = string.Empty;
            DA.GetData<string>(3, ref prefix);
            if (prefix == "")
            {
                prefix = mbSource;
            }

            string URL = mbURL;
            //DA.GetData<string>(4, ref URL);

            ///get a valid mapbox token to send along with query
            string mbToken = string.Empty;
            DA.GetData<string>(4, ref mbToken);
            if (mbToken == "")
            {
                string hmbToken = System.Environment.GetEnvironmentVariable("HERONMAPBOXTOKEN");
                if (hmbToken != null)
                {
                    mbToken = hmbToken;
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using Mapbox token stored in Environment Variable HERONMAPBOXTOKEN.");
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No Mapbox token is specified.  Please get a valid token from mapbox.com");
                    return;
                }
            }

            bool run = false;
            DA.GetData<bool>("Run", ref run);

            GH_Structure<GH_String> mapList = new GH_Structure<GH_String>();
            GH_Structure<GH_Rectangle> imgFrame = new GH_Structure<GH_Rectangle>();
            GH_Structure<GH_String> tCount = new GH_Structure<GH_String>();


            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path = new GH_Path(i);
                int tileTotalCount = 0;
                int tileDownloadedCount = 0;


                //Get image frame for given boundary and  make sure it's valid
                if (!boundary[i].GetBoundingBox(true).IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                    return;
                }
                BoundingBox boundaryBox = boundary[i].GetBoundingBox(true);

                ///TODO: look into scaling boundary to get buffer tiles

                ///file path for final image
                string imgPath = folderPath + prefix + "_" + i + ".jpg";

                //location of final image file
                mapList.Append(new GH_String(imgPath), path);

                //create cache folder for images
                string cacheLoc = folderPath + @"HeronCache\";
                List<string> cachefolderPaths = new List<string>();
                if (!Directory.Exists(cacheLoc))
                {
                    Directory.CreateDirectory(cacheLoc);
                }

                //tile bounding box array
                List<Point3d> boxPtList = new List<Point3d>();

                //get the tile coordinates for all tiles within boundary
                var ranges = Convert.GetTileRange(boundaryBox, zoom);
                List<List<int>> tileList = new List<List<int>>();
                var x_range = ranges.XRange;
                var y_range = ranges.YRange;

                if (x_range.Length > 100 || y_range.Length > 100)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units.");
                    return;
                }

                //cycle through tiles to get bounding box
                for (int y = (int)y_range.Min; y <= y_range.Max; y++)
                {
                    for (int x = (int)x_range.Min; x <= x_range.Max; x++)
                    {
                        //add bounding box of tile to list
                        boxPtList.AddRange(Convert.GetTileAsPolygon(zoom, y, x).ToList());
                        cachefolderPaths.Add(cacheLoc + mbSource.Replace(" ", "") + zoom + x + y + ".jpg");
                        tileTotalCount = tileTotalCount + 1;
                    }
                }

                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                //bounding box of tile boundaries
                BoundingBox bbox = new BoundingBox(boxPtList);

                var rect = BBoxToRect(bbox);
                imgFrame.Append(new GH_Rectangle(rect), path);

                AddPreviewItem(imgPath, boundary[i], rect);

                ///tile range as string for (de)serialization of TileCacheMeta
                string tileRangeString = zoom.ToString()
                    + x_range[0].ToString()
                    + y_range[0].ToString()
                    + x_range[1].ToString()
                    + y_range[1].ToString();

                ///check if the existing final image already covers the boundary. 
                ///if so, no need to download more or rereplacedemble the cached tiles.
                if ((TileCacheMeta == tileRangeString) && Convert.CheckCacheImagesExist(cachefolderPaths))
                {
                    if (File.Exists(imgPath))
                    {
                        using (Bitmap imageT = new Bitmap(imgPath))
                        {
                            ///getting commments currently only working for JPG
                            ///TODO: get this to work for any image type or
                            ///find another way to check if the cached image covers the boundary.
                            string imgComment = imageT.GetCommentsFromJPG();

                            imageT.Dispose();

                            ///check to see if tilerange in comments matches current tilerange
                            if (imgComment == (mbSource.Replace(" ", "") + tileRangeString))
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using existing image.");
                                continue;
                            }

                        }

                    }

                }



                ///Query Mapbox URL
                ///download all tiles within boundary
                ///merge tiles into one bitmap
                ///API to query
                string mbURLauth = mbURL + mbToken;


                ///Do the work of replacedembling image
                ///setup final image container bitmap
                int fImageW = ((int)x_range.Length + 1) * 512;
                int fImageH = ((int)y_range.Length + 1) * 512;
                Bitmap finalImage = new Bitmap(fImageW, fImageH);


                int imgPosW = 0;
                int imgPosH = 0;

                if (run == true)
                {
                    using (Graphics g = Graphics.FromImage(finalImage))
                    {
                        g.Clear(Color.Black);
                        for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++)
                        {
                            for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++)
                            {
                                ///create tileCache name 
                                string tileCache = mbSource.Replace(" ", "") + zoom + x + y + ".jpg";
                                string tileCahceLoc = cacheLoc + tileCache;

                                ///check cache folder to see if tile image exists locally
                                if (File.Exists(tileCahceLoc))
                                {
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCahceLoc));
                                    ///add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 512, imgPosH * 512);
                                    tmpImage.Dispose();
                                }

                                else
                                {
                                    tileList.Add(new List<int> { zoom, y, x });
                                    string urlAuth = Convert.GetZoomURL(x, y, zoom, mbURLauth);

                                    System.Net.WebClient client = new System.Net.WebClient();
                                    client.DownloadFile(urlAuth, tileCahceLoc);
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCahceLoc));
                                    client.Dispose();

                                    ///add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 512, imgPosH * 512);
                                    tmpImage.Dispose();
                                    tileDownloadedCount = tileDownloadedCount + 1;
                                }

                                ///increment x insert position, goes left to right
                                imgPosW++;
                            }
                            ///increment y insert position, goes top to bottom
                            imgPosH++;
                            imgPosW = 0;

                        }
                        ///garbage collection
                        g.Dispose();

                        ///add tile range meta data to image comments
                        finalImage.AddCommentsToJPG(mbSource.Replace(" ", "") + tileRangeString);

                        ///save the image
                        finalImage.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                }

                //garbage collection
                finalImage.Dispose();


                //add to tile count total
                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                //write out new tile range metadata for serialization
                TileCacheMeta = tileRangeString;

                //AddPreviewItem(imgPath, boundary[i], rect);

            }


            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, tCount);
            DA.SetDataList(3, "copyright Mapbox");

        }

19 Source : MapboxRaster.cs
with MIT License
from blueherongis

protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<Curve> boundary = new List<Curve>();
            DA.GetDataList<Curve>(0, boundary);

            int zoom = -1;
            DA.GetData<int>(1, ref zoom);

            string folderPath = string.Empty;
            DA.GetData<string>(2, ref folderPath);
            if (!folderPath.EndsWith(@"\")) folderPath = folderPath + @"\";

            string prefix = string.Empty;
            DA.GetData<string>(3, ref prefix);
            if (prefix == "")
            {
                prefix = mbSource;
            }

            string URL = mbURL;

            ///get a valid mapbox token to send along with query
            string mbToken = string.Empty;
            DA.GetData<string>(4, ref mbToken);
            if (mbToken == "")
            {
                string hmbToken = System.Environment.GetEnvironmentVariable("HERONMAPBOXTOKEN");
                if (hmbToken != null)
                {
                    mbToken = hmbToken;
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using Mapbox token stored in Environment Variable HERONMAPBOXTOKEN.");
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No Mapbox token is specified.  Please get a valid token from mapbox.com");
                    return;
                }
            }

            bool run = false;
            DA.GetData<bool>("Run", ref run);

            GH_Structure<GH_String> mapList = new GH_Structure<GH_String>();
            GH_Structure<GH_Rectangle> imgFrame = new GH_Structure<GH_Rectangle>();
            GH_Structure<GH_String> tCount = new GH_Structure<GH_String>();

            /*
            ///Save for later development of warping
            ///Setup for warping
            RESTful.GdalConfiguration.ConfigureGdal();
            RESTful.GdalConfiguration.ConfigureOgr();

            OSGeo.OSR.SpatialReference userSRS = new OSGeo.OSR.SpatialReference("");
            userSRS.SetFromUserInput("WGS84");

            OSGeo.OSR.SpatialReference mapboxSRS = new OSGeo.OSR.SpatialReference("");
            mapboxSRS.SetFromUserInput("EPSG:3857");

            ///Set transform from input spatial reference to Rhino spatial reference
            OSGeo.OSR.SpatialReference rhinoSRS = new OSGeo.OSR.SpatialReference("");
            rhinoSRS.SetWellKnownGeogCS("WGS84");

            ///This transform moves and scales the points required in going from userSRS to XYZ and vice versa
            //Transform userSRSToModelTransform = Heron.Convert.GetUserSRSToModelTransform(userSRS);
            Transform modelToUserSRSTransform = Heron.Convert.GetModelToUserSRSTransform(userSRS);
            Transform mapboxSRSToModelTransform = Heron.Convert.GetUserSRSToModelTransform(mapboxSRS);
            Transform modelToMapboxSRSTransform = Heron.Convert.GetModelToUserSRSTransform(mapboxSRS);
            */

            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path = new GH_Path(i);
                int tileTotalCount = 0;
                int tileDownloadedCount = 0;


                //Get image frame for given boundary and  make sure it's valid
                if (!boundary[i].GetBoundingBox(true).IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                    return;
                }
                BoundingBox boundaryBox = boundary[i].GetBoundingBox(true);

                ///TODO: look into scaling boundary to get buffer tiles

                ///file path for final image
                string imgPath = folderPath + prefix + "_" + i + ".jpg";

                if (!tilesOut)
                {
                    //location of final image file
                    mapList.Append(new GH_String(imgPath), path);
                }

                //create cache folder for images
                string cacheLoc = folderPath + @"HeronCache\";
                List<string> cacheFilePaths = new List<string>();
                if (!Directory.Exists(cacheLoc))
                {
                    Directory.CreateDirectory(cacheLoc);
                }

                //tile bounding box array
                List<Point3d> boxPtList = new List<Point3d>();

                //get the tile coordinates for all tiles within boundary
                var ranges = Convert.GetTileRange(boundaryBox, zoom);
                List<List<int>> tileList = new List<List<int>>();
                var x_range = ranges.XRange;
                var y_range = ranges.YRange;

                if (x_range.Length > 100 || y_range.Length > 100)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units.");
                    return;
                }

                List<Rectangle3d> tileRectangles = new List<Rectangle3d>();

                //cycle through tiles to get bounding box
                for (int y = (int)y_range.Min; y <= y_range.Max; y++)
                {
                    for (int x = (int)x_range.Min; x <= x_range.Max; x++)
                    {
                        //add bounding box of tile to list
                        List<Point3d> boxPts = Convert.GetTileAsPolygon(zoom, y, x).ToList();
                        boxPtList.AddRange(boxPts);
                        string cacheFilePath = cacheLoc + mbSource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".jpg";
                        cacheFilePaths.Add(cacheFilePath);

                        tileTotalCount = tileTotalCount + 1;

                        if (tilesOut)
                        {
                            mapList.Append(new GH_String(cacheFilePath), path);
                            Rectangle3d tileRectangle = BBoxToRect(new BoundingBox(boxPts));
                            tileRectangles.Add(tileRectangle);
                            imgFrame.Append(new GH_Rectangle(tileRectangle), path);
                        }
                    }
                }

                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                //bounding box of tile boundaries
                BoundingBox bbox = new BoundingBox(boxPtList);

                var rect = BBoxToRect(bbox);
                if (!tilesOut)
                {
                    imgFrame.Append(new GH_Rectangle(rect), path);
                }

                ///tile range as string for (de)serialization of TileCacheMeta
                string tileRangeString = zoom.ToString()
                    + x_range[0].ToString()
                    + y_range[0].ToString()
                    + x_range[1].ToString()
                    + y_range[1].ToString();

                ///check if the existing final image already covers the boundary. 
                ///if so, no need to download more or rereplacedemble the cached tiles.

                if ((TileCacheMeta == tileRangeString) && Convert.CheckCacheImagesExist(cacheFilePaths))
                {
                    if (File.Exists(imgPath) && !tilesOut)
                    {
                        using (Bitmap imageT = new Bitmap(imgPath))
                        {
                            ///getting commments currently only working for JPG
                            ///TODO: get this to work for any image type or
                            ///find another way to check if the cached image covers the boundary.
                            string imgComment = string.Empty;

                            ///Save for later development of warping
                            //if (!warped)
                            imgComment = imageT.GetCommentsFromJPG();

                            imageT.Dispose();

                            ///check to see if tilerange in comments matches current tilerange
                            if (imgComment == (mbSource.Replace(" ", "") + tileRangeString))
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using existing image.");
                                AddPreviewItem(imgPath, boundary[i], rect);
                                continue;
                            }

                        }

                    }

                    if (tilesOut)
                    {
                        for (int t = 0; t < cacheFilePaths.Count; t++)
                        {
                            if (File.Exists(cacheFilePaths[t]))
                            {
                                AddPreviewItem(cacheFilePaths[t], tileRectangles[t].ToNurbsCurve(), tileRectangles[t]);
                            }
                        }
                        continue;
                    }

                }



                ///Query Mapbox URL
                ///download all tiles within boundary
                ///merge tiles into one bitmap
                ///API to query
                string mbURLauth = mbURL + mbToken;


                ///Do the work of replacedembling image
                ///setup final image container bitmap
                int fImageW = ((int)x_range.Length + 1) * 512;
                int fImageH = ((int)y_range.Length + 1) * 512;
                Bitmap finalImage = new Bitmap(fImageW, fImageH);


                int imgPosW = 0;
                int imgPosH = 0;

                /*
                ///Save for later development of warping
                List<GCP> gcpList = new List<GCP>();
                */

                using (Graphics g = Graphics.FromImage(finalImage))
                {
                    g.Clear(Color.Black);
                    for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++)
                    {
                        for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++)
                        {
                            ///create tileCache name 
                            string tileCache = mbSource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".jpg";
                            string tileCacheLoc = cacheLoc + tileCache;

                            /*
                            ///Save for later development of warping
                            ///Get GCPs for warping 
                            Point3d tileCorner = Heron.Convert.GetTileAsPolygon(zoom, y, x)[3];
                            var tileCorner3857 = Convert.Point3dToOgrPoint(tileCorner, modelToMapboxSRSTransform);
                            GCP gcp = new GCP(tileCorner3857.GetX(0), tileCorner3857.GetY(0), tileCorner3857.GetZ(0), imgPosW * 512, imgPosH * 512, tileCorner3857.ToString(), zoom + x + y + "");
                            gcpList.Add(gcp);
                            */

                            ///check cache folder to see if tile image exists locally
                            if (File.Exists(tileCacheLoc))
                            {
                                Bitmap tmpImage = new Bitmap(Image.FromFile(tileCacheLoc));
                                ///add tmp image to final
                                g.DrawImage(tmpImage, imgPosW * 512, imgPosH * 512);
                                tmpImage.Dispose();
                            }

                            else
                            {
                                tileList.Add(new List<int> { zoom, y, x });
                                string urlAuth = Convert.GetZoomURL(x, y, zoom, mbURLauth);

                                Bitmap tmpImage = new Bitmap(512, 512);

                                System.Net.WebClient client = new System.Net.WebClient();
                                if (run == true)
                                {
                                    try
                                    {
                                        client.DownloadFile(urlAuth, tileCacheLoc);
                                        tmpImage = new Bitmap(Image.FromFile(tileCacheLoc));
                                    }
                                    catch (WebException e)
                                    {
                                        using (Graphics tmp = Graphics.FromImage(tmpImage)) { tmp.Clear(Color.White); }
                                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, e.Message);
                                    }
                                }
                                client.Dispose();


                                ///add tmp image to final
                                g.DrawImage(tmpImage, imgPosW * 512, imgPosH * 512);
                                tmpImage.Dispose();
                                tileDownloadedCount = tileDownloadedCount + 1;
                            }

                            ///increment x insert position, goes left to right
                            imgPosW++;
                        }
                        ///increment y insert position, goes top to bottom
                        imgPosH++;
                        imgPosW = 0;

                    }
                    ///garbage collection
                    g.Dispose();

                    ///add tile range meta data to image comments
                    finalImage.AddCommentsToJPG(mbSource.Replace(" ", "") + tileRangeString);

                    ///Save for later development of warping
                    ///if (!warped)
                    ///save the image
                    finalImage.Save(imgPath, ImageFormat.Jpeg);
                }

                /*
                ///Save for later development of warping
                byte[] imageBuffer;
                string memFilename = "/vsimem/inmemfile";
                string memTranslated = "/vsimem/inmemfileTranslated";
                string memWarped = "/vsimem/inmemfileWarped";
                using (MemoryStream stream = new MemoryStream())
                {
                    finalImage.Save(stream, ImageFormat.Jpeg);
                    imageBuffer = stream.ToArray();
                }
                */

                //garbage collection
                finalImage.Dispose();

                /*
                ///Save for later development of warping
                Gdal.FileFromMemBuffer(memFilename, imageBuffer);
                Dataset gdalImage = Gdal.Open(memFilename, Access.GA_ReadOnly);
                var upperLeft3857 = Convert.Point3dToOgrPoint(rect.Corner(3), modelToMapboxSRSTransform);
                var lowerRight3857 = Convert.Point3dToOgrPoint(rect.Corner(1), modelToMapboxSRSTransform);
                var upperLeft4326 = Convert.Point3dToOgrPoint(rect.Corner(3), modelToUserSRSTransform);
                var lowerRight4326 = Convert.Point3dToOgrPoint(rect.Corner(1), modelToUserSRSTransform);
                List<string> translateOptions = new List<string> { "-a_srs", "EPSG:3857", 
                    "-r", "bilinear",
                    "-a_ullr", upperLeft3857.GetX(0).ToString(), upperLeft3857.GetY(0).ToString(), lowerRight3857.GetX(0).ToString(), lowerRight3857.GetY(0).ToString() };
                Dataset gdalTranslated = Gdal.wrapper_GDALTranslate(memTranslated, gdalImage, new GDALTranslateOptions(translateOptions.ToArray()), null, null);

                var wkt = gdalTranslated.GetProjection();
                //gdalTranslated.SetGCPs(gcpList.ToArray(), wkt);

                List<string> warpOptions = new List<string> { "-t_srs", "EPSG:4326", 
                    "-r", "bilinear", 
                    //"-multi", 
                    //"-wo", "NUM_THREADS=6", 
                    "-overwrite", 
                    //"-order", "1",
                    //"-tps",
                    "-te_srs", "EPSG:3857",
                    "-te", upperLeft3857.GetX(0).ToString(), lowerRight3857.GetY(0).ToString(), lowerRight3857.GetX(0).ToString(), upperLeft3857.GetY(0).ToString() };

                ///https://github.com/OSGeo/gdal/issues/813
                ///https://lists.osgeo.org/pipermail/gdal-dev/2017-February/046046.html
                ///Odd way to go about setting source dataset in parameters for Warp is a known issue

                var ptr = new[] { Dataset.getCPtr(gdalTranslated).Handle };
                var gcHandle = GCHandle.Alloc(ptr, GCHandleType.Pinned);
                try
                {
                    var dss = new SWIGTYPE_p_p_GDALDatasetShadow(gcHandle.AddrOfPinnedObject(), false, null);
                    Dataset gdalWarped = Gdal.wrapper_GDALWarpDestName(memWarped, 1, dss, new GDALWarpAppOptions(warpOptions.ToArray()), null, null);
                    var driver = Gdal.GetDriverByName("JPEG");
                    List<string> copyOptions = new List<string> { "QUALITY=95", "COMMENT=" + mbSource.Replace(" ", "") + tileRangeString};
                    var copy = driver.CreateCopy(imgPath, gdalWarped, 0, copyOptions.ToArray(), null, null);
                    copy.Dispose();
                    driver.Dispose();
                    gdalWarped.Dispose();
                }
                finally
                {
                    if (gcHandle.IsAllocated)
                        gcHandle.Free();
                }

                gdalImage.Dispose();
                gdalTranslated.Dispose();
                Gdal.Unlink(memFilename);
                Gdal.Unlink(memTranslated);
                Gdal.Unlink(memWarped);
                */

                if (!tilesOut)
                {
                    AddPreviewItem(imgPath, boundary[i], rect);
                }
                else
                {
                    for (int t = 0; t < cacheFilePaths.Count; t++)
                    {
                        if (File.Exists(cacheFilePaths[t]))
                        {
                            AddPreviewItem(cacheFilePaths[t], tileRectangles[t].ToNurbsCurve(), tileRectangles[t]);
                        }
                    }
                }

                //add to tile count total
                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                //write out new tile range metadata for serialization
                TileCacheMeta = tileRangeString;

            }


            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, tCount);
            DA.SetDataList(3, "copyright Mapbox");

        }

19 Source : MapboxTopo.cs
with MIT License
from blueherongis

protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<Curve> boundary = new List<Curve>();
            DA.GetDataList<Curve>(0, boundary);

            int zoom = -1;
            DA.GetData<int>(1, ref zoom);

            string filePath = string.Empty;
            DA.GetData<string>(2, ref filePath);
            if (!filePath.EndsWith(@"\")) filePath = filePath + @"\";

            string prefix = string.Empty;
            DA.GetData<string>(3, ref prefix);
            if (prefix == string.Empty)
            {
                prefix = mbSource;
            }

            string URL = mbURL;
            //DA.GetData<string>(4, ref URL);


            string mbToken = string.Empty;
            DA.GetData<string>(4, ref mbToken);
            if (mbToken == string.Empty)
            {
                string hmbToken = System.Environment.GetEnvironmentVariable("HERONMAPBOXTOKEN");
                if (hmbToken != null)
                {
                    mbToken = hmbToken;
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using Mapbox token stored in Environment Variable HERONMAPBOXTOKEN.");
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No Mapbox token is specified.  Please get a valid token from mapbox.com");
                    return;
                }
            }

            bool run = false;
            DA.GetData<bool>("Run", ref run);

            GH_Structure<GH_String> mapList = new GH_Structure<GH_String>();
            GH_Structure<GH_Curve> imgFrame = new GH_Structure<GH_Curve>();
            GH_Structure<GH_String> tCount = new GH_Structure<GH_String>();
            GH_Structure<GH_Mesh> tMesh = new GH_Structure<GH_Mesh>();

            for (int i = 0; i < boundary.Count; i++)
            {

                GH_Path path = new GH_Path(i);
                int tileTotalCount = 0;
                int tileDownloadedCount = 0;

                ///Get image frame for given boundary
                if (!boundary[i].GetBoundingBox(true).IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                    return;
                }
                BoundingBox boundaryBox = boundary[i].GetBoundingBox(true);

                ///TODO: look into scaling boundary to get buffer tiles

                ///file path for final image
                string imgPath = filePath + prefix + "_" + i + ".png";

                //location of final image file
                mapList.Append(new GH_String(imgPath), path);

                //create cache folder for images
                string cacheLoc = filePath + @"HeronCache\";
                List<string> cachefilePaths = new List<string>();
                if (!Directory.Exists(cacheLoc))
                {
                    Directory.CreateDirectory(cacheLoc);
                }

                //tile bounding box array
                List<Point3d> boxPtList = new List<Point3d>();


                //get the tile coordinates for all tiles within boundary
                var ranges = Convert.GetTileRange(boundaryBox, zoom);
                List<List<int>> tileList = new List<List<int>>();
                var x_range = ranges.XRange;
                var y_range = ranges.YRange;

                if (x_range.Length > 100 || y_range.Length > 100)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units.");
                    return;
                }

                //cycle through tiles to get bounding box
                for (int y = (int)y_range.Min; y <= y_range.Max; y++)
                {
                    for (int x = (int)x_range.Min; x <= x_range.Max; x++)
                    {
                        //add bounding box of tile to list
                        boxPtList.AddRange(Convert.GetTileAsPolygon(zoom, y, x).ToList());
                        cachefilePaths.Add(cacheLoc + mbSource.Replace(" ", "") + zoom + x + y + ".png");
                        tileTotalCount = tileTotalCount + 1;
                    }
                }

                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                //bounding box of tile boundaries
                BoundingBox bboxPts = new BoundingBox(boxPtList);

                //convert bounding box to polyline
                List<Point3d> imageCorners = bboxPts.GetCorners().ToList();
                imageCorners.Add(imageCorners[0]);
                imgFrame.Append(new GH_Curve(new Rhino.Geometry.Polyline(imageCorners).ToNurbsCurve()), path);

                //tile range as string for (de)serialization of TileCacheMeta
                string tileRangeString = zoom.ToString()
                    + x_range[0].ToString()
                    + y_range[0].ToString()
                    + x_range[1].ToString()
                    + y_range[1].ToString();

                //check if the existing final image already covers the boundary. 
                //if so, no need to download more or rereplacedemble the cached tiles.
                ///temporarily disable until how to tag images with meta data is figured out
                /*
                if (TileCacheMeta == tileRangeString && Convert.CheckCacheImagesExist(cachefilePaths))
                {
                    if (File.Exists(imgPath))
                    {
                        using (Bitmap imageT = new Bitmap(imgPath))
                        {
                            //System.Drawing.Imaging.PropertyItem prop = imageT.GetPropertyItem(40092);
                            //string imgComment = Encoding.Unicode.GetString(prop.Value);
                            string imgComment = imageT.GetCommentsFromImage();
                            //AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, imgComment);
                            imageT.Dispose();
                            //check to see if tilerange in comments matches current tilerange
                            if (imgComment == (mbSource.Replace(" ", "") + tileRangeString))
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using existing topo image.");

                                Mesh eMesh = TopoMeshFromImage(imgPath, boundaryBox, zoom);
                                tMesh.Append(new GH_Mesh(eMesh), path);
                                continue;
                            }

                        }

                    }

                }
                */


                ///Query Mapbox URL
                ///download all tiles within boundary
                ///merge tiles into one bitmap

                ///API to query
                ///string mbURL = "https://api.mapbox.com/v4/mapbox.terrain-rgb/{z}/{x}/{y}@2x.pngraw?access_token=" + mbToken;
                string mbURLauth = mbURL + mbToken;


                ///Do the work of replacedembling image
                ///setup final image container bitmap
                int fImageW = ((int)x_range.Length + 1) * 512;
                int fImageH = ((int)y_range.Length + 1) * 512;
                Bitmap finalImage = new Bitmap(fImageW, fImageH, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                int imgPosW = 0;
                int imgPosH = 0;

                if (run == true)
                {
                    using (Graphics g = Graphics.FromImage(finalImage))
                    {
                        g.Clear(Color.Black);
                        for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++)
                        {
                            for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++)
                            {
                                //create tileCache name 
                                string tileCache = mbSource.Replace(" ", "") + zoom + x + y + ".png";
                                string tileCahceLoc = cacheLoc + tileCache;

                                //check cache folder to see if tile image exists locally
                                if (File.Exists(tileCahceLoc))
                                {
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCahceLoc));
                                    //add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 512, imgPosH * 512);
                                    tmpImage.Dispose();
                                }

                                else
                                {
                                    tileList.Add(new List<int> { zoom, y, x });
                                    string urlAuth = Convert.GetZoomURL(x, y, zoom, mbURLauth);
                                    System.Net.WebClient client = new System.Net.WebClient();
                                    client.DownloadFile(urlAuth, tileCahceLoc);
                                    Bitmap tmpImage = new Bitmap(Image.FromFile(tileCahceLoc));
                                    client.Dispose();

                                    //add tmp image to final
                                    g.DrawImage(tmpImage, imgPosW * 512, imgPosH * 512);
                                    tmpImage.Dispose();
                                    tileDownloadedCount = tileDownloadedCount + 1;
                                }

                                //increment x insert position, goes left to right
                                imgPosW++;
                            }
                            //increment y insert position, goes top to bottom
                            imgPosH++;
                            imgPosW = 0;

                        }
                        //garbage collection
                        g.Dispose();

                        //add tile range meta data to image comments
                        finalImage.AddCommentsToPNG(mbSource.Replace(" ", "") + tileRangeString);

                        //save out replacedembled image 
                        finalImage.Save(imgPath, System.Drawing.Imaging.ImageFormat.Png);
                    }
                }

                //garbage collection
                finalImage.Dispose();

                //add to tile count total
                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);


                Mesh nMesh = TopoMeshFromImage(imgPath, boundaryBox, zoom);

                //mesh.Flip(true, true, true);
                tMesh.Append(new GH_Mesh(nMesh), path);

                //write out new tile range metadata for serialization
                TileCacheMeta = tileRangeString;

                
            }

            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, tCount);
            DA.SetDataTree(3, tMesh);
            DA.SetDataList(4, "copyright Mapbox");
            
        }

19 Source : SlippyRaster.cs
with MIT License
from blueherongis

protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<Curve> boundary = new List<Curve>();
            DA.GetDataList(0, boundary);

            int zoom = -1;
            DA.GetData(1, ref zoom);

            string filePath = string.Empty;
            DA.GetData(2, ref filePath);
            if (!filePath.EndsWith(@"\")) filePath = filePath + @"\";

            string prefix = string.Empty;
            DA.GetData(3, ref prefix);
            if (prefix == string.Empty)
            {
                prefix = slippySource;
            }

            string URL = slippyURL;

            string userAgent = string.Empty;
            DA.GetData(4, ref userAgent);

            bool run = false;
            DA.GetData<bool>("Run", ref run);

            GH_Structure<GH_String> mapList = new GH_Structure<GH_String>();
            GH_Structure<GH_Rectangle> imgFrame = new GH_Structure<GH_Rectangle>();
            GH_Structure<GH_String> tCount = new GH_Structure<GH_String>();

            


            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path = new GH_Path(i);
                int tileTotalCount = 0;
                int tileDownloadedCount = 0;


                ///Get image frame for given boundary and  make sure it's valid
                if (!boundary[i].GetBoundingBox(true).IsValid)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                    return;
                }
                BoundingBox boundaryBox = boundary[i].GetBoundingBox(true);

                ///TODO: look into scaling boundary to get buffer tiles

                ///file path for final image
                string imgPath = filePath + prefix + "_" + i + ".jpg";

                if (!tilesOut)
                {
                    //location of final image file
                    mapList.Append(new GH_String(imgPath), path);
                }

                ///create cache folder for images
                string cacheLoc = filePath + @"HeronCache\";
                List<string> cacheFilePaths = new List<string>();
                if (!Directory.Exists(cacheLoc))
                {
                    Directory.CreateDirectory(cacheLoc);
                }

                ///tile bounding box array
                List<Point3d> boxPtList = new List<Point3d>();

                ///get the tile coordinates for all tiles within boundary
                var ranges = Convert.GetTileRange(boundaryBox, zoom);
                List<List<int>> tileList = new List<List<int>>();
                var x_range = ranges.XRange;
                var y_range = ranges.YRange;

                if (x_range.Length > 100 || y_range.Length > 100)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units.");
                    return;
                }

                List<Rectangle3d> tileRectangles = new List<Rectangle3d>();

                ///cycle through tiles to get bounding box
                for (int y = (int)y_range.Min; y <= y_range.Max; y++)
                {
                    for (int x = (int)x_range.Min; x <= x_range.Max; x++)
                    {
                        ///add bounding box of tile to list
                        List<Point3d> boxPts = Convert.GetTileAsPolygon(zoom, y, x).ToList();
                        boxPtList.AddRange(Convert.GetTileAsPolygon(zoom, y, x).ToList());
                        string cacheFilePath = cacheLoc + slippySource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".jpg";
                        cacheFilePaths.Add(cacheFilePath);

                        tileTotalCount = tileTotalCount + 1;

                        if (tilesOut)
                        {
                            mapList.Append(new GH_String(cacheFilePath), path);
                            Rectangle3d tileRectangle = BBoxToRect(new BoundingBox(boxPts));
                            tileRectangles.Add(tileRectangle);
                            imgFrame.Append(new GH_Rectangle(tileRectangle), path);
                        }
                    }
                }

                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                ///bounding box of tile boundaries
                BoundingBox bbox = new BoundingBox(boxPtList);

                var rect = BBoxToRect(bbox);
                if (!tilesOut)
                {
                    imgFrame.Append(new GH_Rectangle(rect), path);
                }

                //AddPreviewItem(imgPath, boundary[i], rect);

                ///tile range as string for (de)serialization of TileCacheMeta
                string tileRangeString = zoom.ToString()
                    + x_range[0].ToString()
                    + y_range[0].ToString()
                    + x_range[1].ToString()
                    + y_range[1].ToString();

                ///check if the existing final image already covers the boundary. 
                ///if so, no need to download more or rereplacedemble the cached tiles.
                if ((TileCacheMeta == tileRangeString) && Convert.CheckCacheImagesExist(cacheFilePaths))
                {
                    if (File.Exists(imgPath) && !tilesOut)
                    {
                        using (Bitmap imageT = new Bitmap(imgPath))
                        {
                            ///getting commments currently only working for JPG
                            ///TODO: get this to work for any image type or
                            ///find another way to check if the cached image covers the boundary.
                            string imgComment = imageT.GetCommentsFromJPG();

                            imageT.Dispose();

                            ///check to see if tilerange in comments matches current tilerange
                            if (imgComment == (slippySource.Replace(" ", "") + tileRangeString))
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using existing image.");
                                AddPreviewItem(imgPath, boundary[i], rect);
                                continue;
                            }

                        }

                    }

                    if (tilesOut)
                    {
                        for (int t = 0; t < cacheFilePaths.Count; t++)
                        {
                            if (File.Exists(cacheFilePaths[t]))
                            {
                                AddPreviewItem(cacheFilePaths[t], tileRectangles[t].ToNurbsCurve(), tileRectangles[t]);
                            }
                        }
                        continue;
                    }

                }



                ///Query Slippy URL
                ///download all tiles within boundary
                ///merge tiles into one bitmap
                ///API to query


                ///Do the work of replacedembling image
                ///setup final image container bitmap
                int fImageW = ((int)x_range.Length + 1) * 256;
                int fImageH = ((int)y_range.Length + 1) * 256;
                Bitmap finalImage = new Bitmap(fImageW, fImageH);


                int imgPosW = 0;
                int imgPosH = 0;

                using (Graphics g = Graphics.FromImage(finalImage))
                {
                    g.Clear(Color.Black);
                    for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++)
                    {
                        for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++)
                        {
                            //create tileCache name 
                            string tileCache = slippySource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".jpg";
                            string tileCacheLoc = cacheLoc + tileCache;

                            //check cache folder to see if tile image exists locally
                            if (File.Exists(tileCacheLoc))
                            {
                                Bitmap tmpImage = new Bitmap(Image.FromFile(tileCacheLoc));
                                ///add tmp image to final
                                g.DrawImage(tmpImage, imgPosW * 256, imgPosH * 256);
                                tmpImage.Dispose();
                            }

                            else
                            {
                                tileList.Add(new List<int> { zoom, y, x });
                                string urlAuth = Convert.GetZoomURL(x, y, zoom, slippyURL);

                                Bitmap tmpImage = new Bitmap(256, 256);
                                System.Net.WebClient client = new System.Net.WebClient();

                                ///insert header if required
                                client.Headers.Add("user-agent", userAgent);
                                if (run == true)
                                {
                                    try
                                    {
                                        client.DownloadFile(urlAuth, tileCacheLoc);
                                        tmpImage = new Bitmap(Image.FromFile(tileCacheLoc));
                                    }
                                    catch (WebException e)
                                    {
                                        using (Graphics tmp = Graphics.FromImage(tmpImage)) { tmp.Clear(Color.White); }
                                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, e.Message);
                                    }
                                }
                                client.Dispose();

                                //add tmp image to final
                                g.DrawImage(tmpImage, imgPosW * 256, imgPosH * 256);
                                tmpImage.Dispose();
                                tileDownloadedCount = tileDownloadedCount + 1;
                            }

                            //increment x insert position, goes left to right
                            imgPosW++;
                        }
                        //increment y insert position, goes top to bottom
                        imgPosH++;
                        imgPosW = 0;

                    }
                    //garbage collection
                    g.Dispose();

                    //add tile range meta data to image comments
                    finalImage.AddCommentsToJPG(slippySource.Replace(" ", "") + tileRangeString);

                    

                    //save the image
                    finalImage.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                }

                //garbage collection
                finalImage.Dispose();

                if (!tilesOut)
                {
                    AddPreviewItem(imgPath, boundary[i], rect);
                }
                else
                {
                    for (int t = 0; t < cacheFilePaths.Count; t++)
                    {
                        if (File.Exists(cacheFilePaths[t]))
                        {
                            AddPreviewItem(cacheFilePaths[t], tileRectangles[t].ToNurbsCurve(), tileRectangles[t]);
                        }
                    }
                }

                //add to tile count total
                tCount.Insert(new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)"), path, 0);

                //write out new tile range metadata for serialization
                TileCacheMeta = tileRangeString;

            }


            DA.SetDataTree(0, mapList);
            DA.SetDataTree(1, imgFrame);
            DA.SetDataTree(2, tCount);
            ///Add copyright info here
            DA.SetDataList(3, "");

        }

19 Source : PictureZoom.cs
with MIT License
from BluePointLilac

public static Image ZoomPic(Image image, double scale) {
			int ow = image.Width;
			int oh = image.Height;
			int nw = Convert.ToInt32(ow * scale);
			int nh = Convert.ToInt32(oh * scale);
			Bitmap bitmap = new Bitmap(nw, nh);
			Graphics g = Graphics.FromImage(bitmap);
			g.Clear(Color.Transparent);
			g.CompositingQuality = CompositingQuality.HighQuality;
			g.SmoothingMode = SmoothingMode.HighQuality;
			g.InterpolationMode = InterpolationMode.HighQualityBicubic;
			g.DrawImage(image, new Rectangle(0, 0, nw, nh), 0, 0, ow, oh, GraphicsUnit.Pixel);
			g.Dispose();
			return bitmap;
		}

19 Source : WrappedImage.cs
with GNU General Public License v3.0
from bp2008

public void TurnRed()
		{
			//if (bmp != null)
			//{
			if (bmp.PixelFormat != PixelFormat.Format24bppRgb)
				return;

			// Based on: http://www.codeproject.com/Articles/16403/Fast-Pointerless-Image-Processing-in-NET
			int BitsPerPixel = Image.GetPixelFormatSize(bmp.PixelFormat);
			int BytesPerPixel = BitsPerPixel / 8;
			int stride = 4 * ((bmp.Width * BitsPerPixel + 31) / 32);
			byte[] bits = new byte[stride * bmp.Height];
			GCHandle handle = GCHandle.Alloc(bits, GCHandleType.Pinned);
			try
			{
				IntPtr pointer = Marshal.UnsafeAddrOfPinnedArrayElement(bits, 0);
				Bitmap bitmap = new Bitmap(bmp.Width, bmp.Height, stride, bmp.PixelFormat, pointer);

				Graphics g = Graphics.FromImage(bitmap);
				g.DrawImageUnscaledAndClipped(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
				g.Dispose();

				for (int y = 0; y < bmp.Height; y++)
				{
					int start = stride * y;
					int end = start + (bmp.Width * BytesPerPixel);
					for (int i = start; i < end; i += 3)
					{
						bits[i + 2] = (byte)((bits[i] + bits[i + 1] + bits[i + 2]) / 3);
						bits[i] = bits[i + 1] = 0;
					}
				}
				bmp = new Bitmap(bitmap);
			}
			finally
			{
				handle.Free();
			}
			//}
			//else
			//{
			//    if (mi.ColorSpace == ColorSpace.sRGB && mi.ColorType == ColorType.TrueColor)
			//    {
			//        WritablePixelCollection data = mi.GetWritablePixels();
			//        byte[] vals = data.GetValues();
			//        int stride = data.Width * 4;
			//        for (int y = 0; y < data.Height; y++)
			//        {
			//            int start = stride * y;
			//            int end = start + stride;
			//            for (int i = start; i < end; i += 4)
			//            {
			//                vals[i] = ByteAverage(vals[i], vals[i + 1], vals[i + 2]);
			//                vals[i + 1] = vals[i + 2] = 0;
			//            }
			//        }
			//        data.Set(vals);
			//        data.Write();
			//    }
			//    else
			//    {
			//        Console.WriteLine(mi.ColorSpace + " " + mi.ColorType);
			//    }
			//}
		}

19 Source : Copy.cs
with GNU General Public License v3.0
from BRH-Media

public Image ToImage()
        {
            if (_cloneCopy && (_base._copyMode == CopyMode.Display || _base._copyMode == CopyMode.Video))
            {
                return _base.AV_DisplayCopy(_base._copyMode == CopyMode.Video, true);
            }

            Bitmap memoryImage = null;

            if (_base._hasDisplay && (_base._hasVideo || _base._hasOverlayShown))
            {
                Rectangle r;

                switch (_base._copyMode)
                {
                    case CopyMode.Display:
                        r = _base._display.RectangleToScreen(_base._display.DisplayRectangle);
                        break;
                    case CopyMode.Form:
                        r = _base._display.FindForm().RectangleToScreen(_base._display.FindForm().DisplayRectangle);
                        break;
                    case CopyMode.Parent:
                        r = _base._display.Parent.RectangleToScreen(_base._display.Parent.DisplayRectangle);
                        break;
                    case CopyMode.Screen:
                        r = Screen.GetBounds(_base._display);
                        break;

                    default: // CopyMode.Video
                        if (_base._hasVideo) r = _base._display.RectangleToScreen(_base._videoBoundsClip);
                        else r = _base._display.RectangleToScreen(_base._display.DisplayRectangle);
                        break;
                }

                try
                {
                    memoryImage = new Bitmap(r.Width, r.Height);
                    Graphics memoryGraphics = Graphics.FromImage(memoryImage);
                    memoryGraphics.CopyFromScreen(r.Location.X, r.Location.Y, 0, 0, r.Size);
                    memoryGraphics.Dispose();
                    _base._lastError = Player.NO_ERROR;
                }
                catch (Exception e)
                {
                    if (memoryImage != null) { memoryImage.Dispose(); memoryImage = null; }
                    _base._lastError = (HResult)Marshal.GetHRForException(e);
                }
            }
            else
            {
                _base._lastError = HResult.MF_E_NOT_AVAILABLE;
            }
            return memoryImage;
        }

19 Source : PaintLayerEventArgs.cs
with GNU General Public License v3.0
from brhinescot

public void Dispose()
        {
            if (Graphics != null)
                Graphics.Dispose();
            if (Image != null)
                Image.Dispose();
        }

19 Source : JJCManager.cs
with GNU Affero General Public License v3.0
from cc004

private Image GetImage(Result[] teams)
        {
            var n = teams.Length;
            var result = new Bitmap(1130 + 590, 120 * n + 20);
            var canvas = Graphics.FromImage(result);
            canvas.Clear(Color.White);
            for (int i = 0; i < n; ++i) DrawToGraphics(canvas, teams[i], 0, i * 120);
            canvas.DrawString($"powered by www.pcrdfans.com", font, Brushes.Black, 0, 120 * n);
            canvas.Dispose();
            return result;
        }

19 Source : CodeFile1.cs
with GNU Lesser General Public License v3.0
from ccbpm

public void Render(string replacedle, string subreplacedle, int width, int height, DataTable dt, Stream target)
        {
            const int SIDE_LENGTH = 400;
            const int CHART_TOP = 75;
            const int CHART_HEIGHT = 200;
            const int CHART_LEFT = 50;
            const int CHART_WIDTH = 300;
           // DataTable dt = chartData.Tables[0];

            //计算最高的点 
            float highPoint = 0;
            foreach (DataRow dr in dt.Rows)
            {
                if (highPoint < Convert.ToSingle(dr[1]))
                {
                    highPoint = Convert.ToSingle(dr[1]);
                }
            }
            //建立一个Graphics对象实例 
            Bitmap bm = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(bm);
            //设置条图图形和文字属性 
            g.ScaleTransform((Convert.ToSingle(width)) / SIDE_LENGTH, (Convert.ToSingle(height)) / SIDE_LENGTH);
            g.SmoothingMode = SmoothingMode.Default;
            g.TextRenderingHint = TextRenderingHint.AntiAlias;

            //设定画布和边 
            g.Clear(Color.White);
            g.DrawRectangle(Pens.Black, 0, 0, SIDE_LENGTH - 1, SIDE_LENGTH - 1);
            //画大标题 
            g.DrawString(replacedle, new Font("Tahoma", 24), Brushes.Black, new PointF(5, 5));
            //画小标题 
            g.DrawString(subreplacedle, new Font("Tahoma", 14), Brushes.Black, new PointF(7, 35));
            //画条形图 
            float barWidth = CHART_WIDTH / (dt.Rows.Count * 2);
            PointF barOrigin = new PointF(CHART_LEFT + (barWidth / 2), 0);
            float barHeight = dt.Rows.Count;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                barHeight = Convert.ToSingle(dt.Rows[i][1]) * 200 / highPoint;
                barOrigin.Y = CHART_TOP + CHART_HEIGHT - barHeight;
                g.FillRectangle(new SolidBrush(ChartUtil.GetCharreplacedemColor(i)), barOrigin.X, barOrigin.Y, barWidth, barHeight);
                barOrigin.X = barOrigin.X + (barWidth * 2);
            }
            //设置边 
            g.DrawLine(new Pen(Color.Black, 2), new Point(CHART_LEFT, CHART_TOP), new Point(CHART_LEFT, CHART_TOP + CHART_HEIGHT));
            g.DrawLine(new Pen(Color.Black, 2), new Point(CHART_LEFT, CHART_TOP + CHART_HEIGHT), new Point(CHART_LEFT + CHART_WIDTH, CHART_TOP + CHART_HEIGHT));
            //画图例框和文字 
            g.DrawRectangle(new Pen(Color.Black, 1), 200, 300, 199, 99);
            g.DrawString("Legend", new Font("Tahoma", 12, FontStyle.Bold), Brushes.Black, new PointF(200, 300));

            //画图例 
            PointF boxOrigin = new PointF(210, 330);
            PointF textOrigin = new PointF(235, 326);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                g.FillRectangle(new SolidBrush(ChartUtil.GetCharreplacedemColor(i)), boxOrigin.X, boxOrigin.Y, 20, 10);
                g.DrawRectangle(Pens.Black, boxOrigin.X, boxOrigin.Y, 20, 10);
                g.DrawString(dt.Rows[i][0].ToString() + " - " + dt.Rows[i][1].ToString(), new Font("Tahoma", 10), Brushes.Black, textOrigin);
                boxOrigin.Y += 15;
                textOrigin.Y += 15;
            }
            //输出图形 
            bm.Save(BP.Sys.SystemConfig.PathOfTemp+"Bar"+BP.Web.WebUser.No+".gif", ImageFormat.Gif);

            //资源回收 
            bm.Dispose();
            g.Dispose();
        }

19 Source : CodeFile1.cs
with GNU Lesser General Public License v3.0
from ccbpm

public void Render(string replacedle, string subreplacedle, int width, int height, DataTable dt)
        {
            const int SIDE_LENGTH = 400;
            const int PIE_DIAMETER = 200;

            //通过输入参数,取得饼图中的总基数 
            float sumData = 0;
            foreach (DataRow dr in dt.Rows)
            {
                sumData += Convert.ToSingle(dr[1]);
            }
            //产生一个image对象,并由此产生一个Graphics对象 
            Bitmap bm = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(bm);
            //设置对象g的属性 
            g.ScaleTransform((Convert.ToSingle(width)) / SIDE_LENGTH, (Convert.ToSingle(height)) / SIDE_LENGTH);
            g.SmoothingMode = SmoothingMode.Default;
            g.TextRenderingHint = TextRenderingHint.AntiAlias;

            //画布和边的设定 
            g.Clear(Color.White);
            g.DrawRectangle(Pens.Black, 0, 0, SIDE_LENGTH - 1, SIDE_LENGTH - 1);
            //画饼图标题 
            g.DrawString(replacedle, new Font("Tahoma", 24), Brushes.Black, new PointF(5, 5));
            //画饼图的图例 
            g.DrawString(subreplacedle, new Font("Tahoma", 14), Brushes.Black, new PointF(7, 35));
            //画饼图 
            float curAngle = 0;
            float totalAngle = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                curAngle = Convert.ToSingle(dt.Rows[i][1]) / sumData * 360;

                g.FillPie(new SolidBrush(ChartUtil.GetCharreplacedemColor(i)), 100, 65, PIE_DIAMETER, PIE_DIAMETER, totalAngle, curAngle);
                g.DrawPie(Pens.Black, 100, 65, PIE_DIAMETER, PIE_DIAMETER, totalAngle, curAngle);
                totalAngle += curAngle;
            }
            //画图例框及其文字 
            g.DrawRectangle(Pens.Black, 200, 300, 199, 99);
            g.DrawString("Legend", new Font("Tahoma", 12, FontStyle.Bold), Brushes.Black, new PointF(200, 300));

            //画图例各项 
            PointF boxOrigin = new PointF(210, 330);
            PointF textOrigin = new PointF(235, 326);
            float percent = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                g.FillRectangle(new SolidBrush(ChartUtil.GetCharreplacedemColor(i)), boxOrigin.X, boxOrigin.Y, 20, 10);
                g.DrawRectangle(Pens.Black, boxOrigin.X, boxOrigin.Y, 20, 10);
                percent = Convert.ToSingle(dt.Rows[i][1]) / sumData * 100;
                g.DrawString(dt.Rows[i][0].ToString() + " - " + dt.Rows[i][1].ToString() + " (" + percent.ToString("0") + "%)", new Font("Tahoma", 10), Brushes.Black, textOrigin);
                boxOrigin.Y += 15;
                textOrigin.Y += 15;
            }
            //通过Response.OutputStream,将图形的内容发送到浏览器 
            string file = SystemConfig.PathOfTemp + "Pie" + Web.WebUser.No + ".gif";
            bm.Save(file, ImageFormat.Gif);
            //回收资源 
            bm.Dispose();
            g.Dispose();
        }

19 Source : GenerSiganture.cs
with GNU Lesser General Public License v3.0
from ccbpm

public override object Do()
        {
            try
            {
                BP.Port.Emps emps = new Emps();
                emps.RetrieveAllFromDBSource();
                string path = BP.Sys.SystemConfig.PathOfDataUser + "\\Siganture\\T.JPG";
                string fontName = "宋体";
                string empOKs = "";
                string empErrs = "";
                foreach (Emp emp in emps)
                {
                    string pathMe = BP.Sys.SystemConfig.PathOfDataUser + "\\Siganture\\" + emp.No + ".JPG";
                    if (System.IO.File.Exists(pathMe))
                        continue;

                    File.Copy(BP.Sys.SystemConfig.PathOfDataUser + "\\Siganture\\Templete.JPG",
                        path, true);

                    System.Drawing.Image img = System.Drawing.Image.FromFile(path);
                    Font font = new Font(fontName, 15);
                    Graphics g = Graphics.FromImage(img);
                    System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
                    System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat(StringFormatFlags.DirectionVertical);//文本
                    g.DrawString(emp.Name, font, drawBrush, 3, 3);
                    img.Save(pathMe);
                    img.Dispose();
                    g.Dispose();

                    File.Copy(pathMe,
                    BP.Sys.SystemConfig.PathOfDataUser + "\\Siganture\\" + emp.Name + ".JPG", true);
                }
                return "执行成功...";
            }
            catch(Exception ex)
            {
                return "执行失败,请确认对 " + BP.Sys.SystemConfig.PathOfDataUser + "\\Siganture\\ 目录有访问权限?异常信息:"+ex.Message;
            }
        }

19 Source : WaterImage.cs
with GNU Lesser General Public License v3.0
from ccbpm

public string DrawWords(string sourcePictureName,
                         string waterWords,
                         float alpha,
                         ImagePosition position,
                         string targetImage)
        {
            //
            // 判断参数是否有效
            //
            if (sourcePictureName == string.Empty || waterWords == string.Empty || alpha == 0.0 || sourcePictureName == string.Empty)
                throw new Exception("@参数错误");

            //
            // 源图片全路径
            //
            string fileExtension = System.IO.Path.GetExtension(sourcePictureName).ToLower();

            //
            // 判断文件是否存在,以及文件名是否正确
            //
            if (System.IO.File.Exists(sourcePictureName) == false || (
              fileExtension != ".gif" &&
              fileExtension != ".jpg" &&
              fileExtension != ".png"))
            {
                throw new Exception("@源文件格式错误" + sourcePictureName);
            }
             

            //创建一个图片对象用来装载要被添加水印的图片
            Image imgPhoto = Image.FromFile(sourcePictureName);

            //获取图片的宽和高
            int phWidth = imgPhoto.Width;
            int phHeight = imgPhoto.Height;

            //
            //建立一个bitmap,和我们需要加水印的图片一样大小
            Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

            //SetResolution:设置此 Bitmap 的分辨率
            //这里直接将我们需要添加水印的图片的分辨率赋给了bitmap
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            //Graphics:封装一个 GDI+ 绘图图面。
            Graphics grPhoto = Graphics.FromImage(bmPhoto);

            //设置图形的品质
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

            //将我们要添加水印的图片按照原始大小描绘(复制)到图形中
            grPhoto.DrawImage(
             imgPhoto,                      //  要添加水印的图片
             new Rectangle(0, 0, phWidth, phHeight), // 根据要添加的水印图片的宽和高
             0,                           // X方向从0点开始描绘
             0,                           // Y方向

             phWidth,                      // X方向描绘长度
             phHeight,                      // Y方向描绘长度
             GraphicsUnit.Pixel);               // 描绘的单位,这里用的是像素

            //根据图片的大小我们来确定添加上去的文字的大小
            //在这里我们定义一个数组来确定
            int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };

            //字体
            Font crFont = null;
            //矩形的宽度和高度,SizeF有三个属性,分别为Height高,width宽,IsEmpty是否为空
            SizeF crSize = new SizeF();

            //利用一个循环语句来选择我们要添加文字的型号
            //直到它的长度比图片的宽度小
            for (int i = 0; i < 7; i++)
            {
                crFont = new Font("arial", sizes[i], FontStyle.Italic);


                //测量用指定的 Font 对象绘制并用指定的 StringFormat 对象格式化的指定字符串。
                crSize = grPhoto.MeasureString(waterWords, crFont);

                // ushort 关键字表示一种整数数据类型
                if ((ushort)crSize.Width < (ushort)phWidth)
                    break;
            }

            //截边5%的距离,定义文字显示(由于不同的图片显示的高和宽不同,所以按百分比截取)
            int yPixlesFromBottom = (int)(phHeight * .05);

            //定义在图片上文字的位置
            float wmHeight = crSize.Height;
            float wmWidth = crSize.Width;
            float xPosOfWm;
            float yPosOfWm;

            switch (position)
            {
                case ImagePosition.BottomMiddle:
                    xPosOfWm = phWidth / 2;
                    yPosOfWm = phHeight - wmHeight - 10;
                    break;
                case ImagePosition.Center:
                    xPosOfWm = phWidth / 2;
                    yPosOfWm = phHeight / 2;
                    break;
                case ImagePosition.LeftBottom:
                    xPosOfWm = wmWidth;
                    yPosOfWm = phHeight - wmHeight - 10;
                    break;
                case ImagePosition.LeftTop:
                    xPosOfWm = wmWidth / 2;
                    yPosOfWm = wmHeight / 2;
                    break;
                case ImagePosition.RightTop:
                    xPosOfWm = phWidth - wmWidth - 10;
                    yPosOfWm = wmHeight;
                    break;
                case ImagePosition.RigthBottom:
                    xPosOfWm = phWidth - wmWidth - 10;
                    yPosOfWm = phHeight - wmHeight - 10;
                    break;
                case ImagePosition.TopMiddle:
                    xPosOfWm = phWidth / 2;
                    yPosOfWm = wmWidth;

                    break;
                default:
                    xPosOfWm = wmWidth;
                    yPosOfWm = phHeight - wmHeight - 10;
                    break;
            }

            //封装文本布局信息(如对齐、文字方向和 Tab 停靠位),显示操作(如省略号插入和国家标准 (National) 数字替换)和 OpenType 功能。
            StringFormat StrFormat = new StringFormat();

             
            //定义需要印的文字居中对齐
            StrFormat.Alignment = StringAlignment.Center;

            //SolidBrush:定义单色画笔。画笔用于填充图形形状,如矩形、椭圆、扇形、多边形和封闭路径。
            //这个画笔为描绘阴影的画笔,呈灰色            
            int m_alpha = Convert.ToInt32(256 * alpha);
            SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(m_alpha, 0, 0, 0));

            //描绘文字信息,这个图层向右和向下偏移一个像素,表示阴影效果
            //DrawString 在指定矩形并且用指定的 Brush 和 Font 对象绘制指定的文本字符串。
            grPhoto.DrawString(waterWords,                  //string of text
                          crFont,                     //font
                          semiTransBrush2,              //Brush
                          new PointF(xPosOfWm + 1, yPosOfWm + 1), //Position
                          StrFormat);

            //从四个 ARGB 分量(alpha、红色、绿色和蓝色)值创建 Color 结构,这里设置透明度为153
            //这个画笔为描绘正式文字的笔刷,呈白色
            SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));

            //第二次绘制这个图形,建立在第一次描绘的基础上
            grPhoto.DrawString(waterWords,         //string of text
                          crFont,                  //font
                          semiTransBrush,              //Brush
                          new PointF(xPosOfWm, yPosOfWm), //Position
                          StrFormat);

            //imgPhoto是我们建立的用来装载最终图形的Image对象
            //bmPhoto是我们用来制作图形的容器,为Bitmap对象
            imgPhoto = bmPhoto;
            //释放资源,将定义的Graphics实例grPhoto释放,grPhoto功德圆满
            grPhoto.Dispose();

            //将grPhoto保存
            imgPhoto.Save(targetImage, ImageFormat.Jpeg);
            imgPhoto.Dispose();

            return targetImage;

            //return targetImage.Replace(PicturePath, "");
        }

19 Source : WaterImage.cs
with GNU Lesser General Public License v3.0
from ccbpm

public string DrawImage(string sourcePicture,
                         string waterImage,
                         float alpha,

                         ImagePosition position,
                         string PicturePath)
        {
            //
            // 判断参数是否有效
            //
            if (sourcePicture == string.Empty || waterImage == string.Empty || alpha == 0.0 || PicturePath == string.Empty)
            {
                return sourcePicture;
            }

            //
            // 源图片,水印图片全路径
            //
            string sourcePictureName = PicturePath + sourcePicture;
            string waterPictureName = PicturePath + waterImage;
            string fileSourceExtension = System.IO.Path.GetExtension(sourcePictureName).ToLower();
            string fileWaterExtension = System.IO.Path.GetExtension(waterPictureName).ToLower();
            //
            // 判断文件是否存在,以及类型是否正确
            //
            if (System.IO.File.Exists(sourcePictureName) == false ||
              System.IO.File.Exists(waterPictureName) == false || (
              fileSourceExtension != ".gif" &&
              fileSourceExtension != ".jpg" &&
              fileSourceExtension != ".png") || (
              fileWaterExtension != ".gif" &&
              fileWaterExtension != ".jpg" &&
              fileWaterExtension != ".png")
              )
            {
                return sourcePicture;
            }

            //
            // 目标图片名称及全路径
            //
            string targetImage = sourcePictureName.Replace(System.IO.Path.GetExtension(sourcePictureName), "") + "_1101.jpg";

            //
            // 将需要加上水印的图片装载到Image对象中
            //
            Image imgPhoto = Image.FromFile(sourcePictureName);
            //
            // 确定其长宽
            //
            int phWidth = imgPhoto.Width;
            int phHeight = imgPhoto.Height;

            //
            // 封装 GDI+ 位图,此位图由图形图像及其属性的像素数据组成。
            //
            Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

            //
            // 设定分辨率
            // 
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            //
            // 定义一个绘图画面用来装载位图
            //
            Graphics grPhoto = Graphics.FromImage(bmPhoto);

            //
            //同样,由于水印是图片,我们也需要定义一个Image来装载它
            //
            Image imgWatermark = new Bitmap(waterPictureName);

            //
            // 获取水印图片的高度和宽度
            //
            int wmWidth = imgWatermark.Width;
            int wmHeight = imgWatermark.Height;

            //SmoothingMode:指定是否将平滑处理(消除锯齿)应用于直线、曲线和已填充区域的边缘。
            // 成员名称  说明 
            // AntiAlias   指定消除锯齿的呈现。 
            // Default    指定不消除锯齿。

            // HighQuality 指定高质量、低速度呈现。 
            // HighSpeed  指定高速度、低质量呈现。 
            // Invalid    指定一个无效模式。 
            // None     指定不消除锯齿。 
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

            //
            // 第一次描绘,将我们的底图描绘在绘图画面上
            //
            grPhoto.DrawImage(imgPhoto,
                          new Rectangle(0, 0, phWidth, phHeight),
                          0,
                          0,
                          phWidth,
                          phHeight,
                          GraphicsUnit.Pixel);

            //
            // 与底图一样,我们需要一个位图来装载水印图片。并设定其分辨率
            //
            Bitmap bmWatermark = new Bitmap(bmPhoto);
            bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            //
            // 继续,将水印图片装载到一个绘图画面grWatermark
            //
            Graphics grWatermark = Graphics.FromImage(bmWatermark);

            //
            //ImageAttributes 对象包含有关在呈现时如何操作位图和图元文件颜色的信息。
            //   

            ImageAttributes imageAttributes = new ImageAttributes();

            //
            //Colormap: 定义转换颜色的映射
            //
            ColorMap colorMap = new ColorMap();

            //
            //我的水印图被定义成拥有绿色背景色的图片被替换成透明
            //
            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float[][] colorMatrixElements = { 
      new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // red红色
      new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, //green绿色
      new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, //blue蓝色    
      new float[] {0.0f, 0.0f, 0.0f, alpha, 0.0f}, //透明度   
      new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}};//

            // ColorMatrix:定义包含 RGBA 空间坐标的 5 x 5 矩阵。
            // ImageAttributes 类的若干方法通过使用颜色矩阵调整图像颜色。
            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);


            imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
             ColorAdjustType.Bitmap);

            //
            //上面设置完颜色,下面开始设置位置
            //
            int xPosOfWm;
            int yPosOfWm;

            switch (position)
            {
                case ImagePosition.BottomMiddle:
                    xPosOfWm = (phWidth - wmWidth) / 2;
                    yPosOfWm = phHeight - wmHeight - 10;
                    break;

                case ImagePosition.Center:
                    xPosOfWm = (phWidth - wmWidth) / 2;
                    yPosOfWm = (phHeight - wmHeight) / 2;
                    break;
                case ImagePosition.LeftBottom:
                    xPosOfWm = 10;
                    yPosOfWm = phHeight - wmHeight - 10;
                    break;
                case ImagePosition.LeftTop:
                    xPosOfWm = 10;
                    yPosOfWm = 10;
                    break;
                case ImagePosition.RightTop:
                    xPosOfWm = phWidth - wmWidth - 10;
                    yPosOfWm = 10;
                    break;
                case ImagePosition.RigthBottom:
                    xPosOfWm = phWidth - wmWidth - 10;
                    yPosOfWm = phHeight - wmHeight - 10;
                    break;
                case ImagePosition.TopMiddle:
                    xPosOfWm = (phWidth - wmWidth) / 2;
                    yPosOfWm = 10;
                    break;
                default:
                    xPosOfWm = 10;
                    yPosOfWm = phHeight - wmHeight - 10;
                    break;
            }

            // 第二次绘图,把水印印上去
            //
            grWatermark.DrawImage(imgWatermark,
             new Rectangle(xPosOfWm,
                       yPosOfWm,
                       wmWidth,
                       wmHeight),
                       0,
                       0,
                       wmWidth,
                       wmHeight,
                       GraphicsUnit.Pixel,
                       imageAttributes);

            imgPhoto = bmWatermark;
            grPhoto.Dispose();
            grWatermark.Dispose();

            //
            // 保存文件到服务器的文件夹里面
            //
            imgPhoto.Save(targetImage, ImageFormat.Jpeg);
            imgPhoto.Dispose();
            imgWatermark.Dispose();
            return targetImage.Replace(PicturePath, "");
        }

19 Source : FrmInfo.cs
with MIT License
from ChDC

private void drawMemoryUsage(float value)
        {
            
            Control control = lblMemory;
            Bitmap b = new Bitmap(control.Width, control.Height);
            Graphics g = Graphics.FromImage(b);

            //draw background
            g.FillRectangle(new SolidBrush(Color.FromArgb(28, 28, 29)), 0, 0, control.Width, control.Height);

            // draw usage rect
            int width = (int)(control.Width * value);
            Rectangle rect = new Rectangle(0, 0, width, control.Height);

            //LinearGradientBrush brush = new LinearGradientBrush(control.ClientRectangle, Color.FromArgb(17, 160, 255), Color.FromArgb(23,174,254), LinearGradientMode.Vertical);
            //brush.SetSigmaBellShape(0.5f);
            //g.FillRectangle(brush, rect);
            g.FillRectangle(new SolidBrush(Color.FromArgb(0, 186, 255)), rect);

            // border
            g.DrawRectangle(new Pen(Color.FromArgb(28, 28, 29), 3), 0, 0, control.Width-2, control.Height-2);

            g.Dispose();
            control.BackgroundImage = b;
        }

19 Source : components.cs
with BSD 2-Clause "Simplified" License
from chengse66

private Image resize_icon(Image image)
	{
		Bitmap bitmap = new Bitmap(40, 40);
		Graphics graphics = Graphics.FromImage(bitmap);
		int left = (40 < image.Width) ? (image.Width - 40) / 2 : 0;
		int top = (40 < image.Height) ? (image.Height - 40) / 2 : 0;
		int width = (40 < image.Width) ? 40 : image.Width;
		int height = (40 < image.Height) ? 40 : image.Height;

		graphics.DrawImage(image, new Rectangle((40 - width) / 2, (40 - height) / 2, width, height), new Rectangle(left, top, width, height), GraphicsUnit.Pixel);

		graphics.Dispose();
		image.Dispose();

		return bitmap;
	}

See More Examples