System.Drawing.Graphics.FromImage(System.Drawing.Image)

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

1819 Examples 7

19 Source : BatchImageProcessor.cs
with MIT License
from Azure-Samples

private Bitmap ToGrayScale(Image source)
        {
            Bitmap grayscaleBitmap = new Bitmap(source.Width, source.Height);

            using Graphics graphics = Graphics.FromImage(grayscaleBitmap);

            //create the grayscale ColorMatrix
            ColorMatrix colorMatrix = new ColorMatrix(
                new float[][]
                {
                        new float[] {.3f, .3f, .3f, 0, 0},
                        new float[] {.59f, .59f, .59f, 0, 0},
                        new float[] {.11f, .11f, .11f, 0, 0},
                        new float[] {0, 0, 0, 1, 0},
                        new float[] {0, 0, 0, 0, 1}
                });

            ImageAttributes attributes = new ImageAttributes();

            //set the color matrix attribute
            attributes.SetColorMatrix(colorMatrix);

            //draw the original image on the new image
            //using the grayscale color matrix
            graphics.DrawImage(source, new System.Drawing.Rectangle(0, 0, source.Width, source.Height),
                0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes);

            return grayscaleBitmap;
        }

19 Source : Theme.cs
with MIT License
from b9q

protected override void OnPaint(PaintEventArgs e)
    {
        Bitmap b = new Bitmap(Width, Height);
        using (Graphics g = Graphics.FromImage(b))
        {
            g.SmoothingMode = SmoothingMode.HighQuality;
            Rectangle rect = new Rectangle(0, 0, Width, Height);

            switch (State)
            {
                case MouseState.Hover:
                    {
                        g.DrawString("r", Font, new SolidBrush(Color.FromArgb(27, 136, 209)), new Rectangle(0, 0, Width, Height), new StringFormat
                        {
                            Alignment = StringAlignment.Center,
                            LineAlignment = StringAlignment.Center
                        });
                        break;
                    }
                case MouseState.None:
                    {
                        g.DrawString("r", Font, new SolidBrush(Color.FromArgb(170, 186, 198)), new Rectangle(0, 0, Width, Height), new StringFormat
                        {
                            Alignment = StringAlignment.Center,
                            LineAlignment = StringAlignment.Center
                        });
                        break;
                    }
                default:
                    g.DrawString("r", Font, new SolidBrush(Color.FromArgb(170, 186, 198)), new Rectangle(0, 0, Width, Height), new StringFormat
                    {
                        Alignment = StringAlignment.Center,
                        LineAlignment = StringAlignment.Center
                    });
                    break;
            }

            e.Graphics.DrawImage(b, 0, 0);
        }

        b.Dispose();

        base.OnPaint(e);
    }

19 Source : Theme.cs
with MIT License
from b9q

protected override void OnPaint(PaintEventArgs e)
    {
        Bitmap b = new Bitmap(Width, Height);
        using (Graphics g = Graphics.FromImage(b))
        {
            g.SmoothingMode = SmoothingMode.HighQuality;
            Rectangle rect = new Rectangle(0, 0, Width, Height);

            switch (State)
            {
                case MouseState.Hover:
                    {
                        g.DrawString("0", Font, new SolidBrush(Color.FromArgb(27, 136, 209)), new Rectangle(0, 0, Width, Height), new StringFormat
                        {
                            Alignment = StringAlignment.Center,
                            LineAlignment = StringAlignment.Center
                        });
                        break;
                    }
                case MouseState.None:
                    {
                        g.DrawString("0", Font, new SolidBrush(Color.FromArgb(170, 186, 198)), new Rectangle(0, 0, Width, Height), new StringFormat
                        {
                            Alignment = StringAlignment.Center,
                            LineAlignment = StringAlignment.Center
                        });
                        break;
                    }
                default:
                    g.DrawString("0", Font, new SolidBrush(Color.FromArgb(170, 186, 198)), new Rectangle(0, 0, Width, Height), new StringFormat
                    {
                        Alignment = StringAlignment.Center,
                        LineAlignment = StringAlignment.Center
                    });
                    break;
            }

            e.Graphics.DrawImage(b, 0, 0);
        }

        b.Dispose();

        base.OnPaint(e);
    }

19 Source : Theme.cs
with MIT License
from b9q

protected override void OnPaint(PaintEventArgs e)
    {
        Bitmap b = new Bitmap(Width, Height);
        Brush _inner = new SolidBrush(Color.FromArgb(254, 255, 255));

        base.OnPaint(e);

        using (Graphics g = Graphics.FromImage(b))
        {
            switch (_MouseState)
            {
                case MouseState.Hover:
                    {
                        _inner = new SolidBrush(Color.FromArgb(140, 20, 60));
                        break;
                    };

                default:
                    _inner = new SolidBrush(Color.FromArgb(254, 255, 255));
                    break;
            }


            Drawing.DrawWithOutline(g, _inner, new SolidBrush(Color.FromArgb(220, 60, 60)), new Rectangle(0, 0, Width - 1, Height - 1));

            //button related text
            if (_MouseState == MouseState.Hover)
            {
                g.DrawString(Text, _font, new SolidBrush(Color.FromArgb(220, 20, 60)), new Rectangle(0, 1, Width, Height), new StringFormat
                {
                    Alignment = StringAlignment.Center,
                    LineAlignment = StringAlignment.Center
                });

            }
            else
            {
                g.DrawString(Text, _font, new SolidBrush(Color.FromArgb(220, 20, 60)), new Rectangle(0, 1, Width, Height), new StringFormat
                {
                    Alignment = StringAlignment.Center,
                    LineAlignment = StringAlignment.Center
                });
            }

            e.Graphics.DrawImage(b, 0, 0);
        }

        b.Dispose();
    }

19 Source : Theme.cs
with MIT License
from b9q

protected override void OnPaint(PaintEventArgs e)
    {
        Bitmap b = new Bitmap(Width, Height);
        using (Graphics g = Graphics.FromImage(b))
        {
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

            if (_checked)
            {
                Drawing.DrawWithOutline(g, new SolidBrush(Color.FromArgb(254, 255, 255)), new SolidBrush(Color.FromArgb(208, 230, 246)), new Rectangle(0, 0, 14, 14));
                g.DrawString("a", _checkFont, Drawing.tehColor, -3, -1);
            }
            else
            {
                Drawing.DrawWithOutline(g, new SolidBrush(Color.FromArgb(254, 255, 255)), new SolidBrush(Color.FromArgb(208, 230, 246)), new Rectangle(0, 0, 14, 14));
            }

            g.DrawString(Text, _font, new SolidBrush(ForeColor), new Point(18, 0), new StringFormat
            {
                Alignment = StringAlignment.Near,
                LineAlignment = StringAlignment.Near
            });

            e.Graphics.DrawImage(b, 0, 0);
        }

        b.Dispose();
    }

19 Source : Theme.cs
with MIT License
from b9q

protected override void OnPaint(PaintEventArgs e)
    {
        Bitmap b = new Bitmap(Width, Height);
        using (Graphics g = Graphics.FromImage(b))
        {
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.Clear(Color.FromArgb(246, 251, 254));

            Drawing.DrawWithOutline(g, new SolidBrush(Color.FromArgb(254, 255, 255)), new SolidBrush(Color.FromArgb(208, 230, 246)), new Rectangle(0, 0, Width - 1, Height - 1));
            e.Graphics.DrawImage(b, 0, 0);
        }

        b.Dispose();
    }

19 Source : Theme.cs
with MIT License
from b9q

protected override void OnPaint(PaintEventArgs e)
    {
        Bitmap b = new Bitmap(Width, Height);
        using (Graphics g = Graphics.FromImage(b))
        {
            g.Clear(Color.FromArgb(254, 255, 255));

            for (int i = 0; i <= TabCount - 1; i++)
            {
                Rectangle TabRectangle = GetTabRect(i);

                //fix tab position
                TabRectangle.X += 2;
                //TabRectangle.Height = 34;
                TabRectangle.Y += 1;

                Rectangle stringRect = TabRectangle;
                stringRect.X += 3;

                if (i == SelectedIndex)
                {
                    g.FillRectangle(Drawing.tehColor, TabRectangle);
                    g.DrawString(TabPages[i].Text, _font, Brushes.White, stringRect, new StringFormat
                    {
                        LineAlignment = StringAlignment.Center,
                        Alignment = StringAlignment.Near
                    });
                }
                else
                {
                    g.DrawRectangle(new Pen(Color.FromArgb(208, 230, 246)), TabRectangle);
                    g.DrawString(TabPages[i].Text, _font, Drawing.tehColor, stringRect, new StringFormat
                    {
                        LineAlignment = StringAlignment.Center,
                        Alignment = StringAlignment.Near
                    });
                }

                g.DrawLine(new Pen(Drawing.tehColor), new Point(TabRectangle.X, TabRectangle.Y + TabRectangle.Height),
                    new Point(this.Width - 5, TabRectangle.Y + TabRectangle.Height));
            }

            e.Graphics.DrawImage(b, 0, 0);
        }

        b.Dispose();
        base.OnPaint(e);
    }

19 Source : Main.cs
with MIT License
from bandaranayake

private void btnDraw_Click(object sender, EventArgs e)
        {
            if (_original == null)
            {
                MessageBox.Show("No image selected. Click 'Browse' to select an image.", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                Hide();
                Thread.Sleep(500);

                Bitmap image = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);

                using (Graphics g = Graphics.FromImage(image))
                {
                    g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, image.Size, CopyPixelOperation.SourceCopy);
                    g.DrawRectangle(Pens.Red, 1, 1, image.Width - 3, image.Height - 3);
                }

                ScreenOverlay overlay = new ScreenOverlay(image);
                Show();

                if (overlay.ShowDialog() == DialogResult.OK)
                {
                    WindowState = FormWindowState.Minimized;
                    image.Dispose();

                    CvInvoke.Resize(_img, _img, new Size(_img.Cols, _img.Rows));
                    CvInvoke.BitwiseNot(_img, _img);

                    Thread.Sleep(2000);

                    _lastPoint = new Point(-1, -1);
                    _pid = GetActiveProcess();

                    Draw(_img, overlay.Pos.X, overlay.Pos.Y);
                    WindowState = FormWindowState.Normal;
                }
            }
        }

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 : Win32Interop.cs
with GNU General Public License v3.0
from belowaverage-org

public static void DrawMenuItemBitmaps(this Menu Menu)
        {
            int miIndexOffset = 0;
            foreach(MenuItem mi in Menu.MenuItems)
            {
                if (!MenuItemIcons.ContainsKey(mi)) continue;
                if (!mi.Visible)
                {
                    miIndexOffset--;
                    continue;
                }
                Image image = MenuItemIcons[mi];
                Bitmap bitmap = new Bitmap(image.Width, image.Height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
                Graphics g = Graphics.FromImage(bitmap);
                g.DrawImage(image, 0, 0, image.Width, image.Height);
                MENUITEMINFO mii = new MENUITEMINFO
                {
                    cbSize = (uint)Marshal.SizeOf(typeof(MENUITEMINFO)),
                    fMask = 0x80u,
                    hbmpItem = bitmap.GetHbitmap(Color.FromArgb(0, 0, 0, 0))
                };
                SetMenuItemInfo(mi.Parent.Handle, (uint)(mi.Index + miIndexOffset), true, ref mii);
            }
        }

19 Source : Win32Interop.cs
with GNU General Public License v3.0
from belowaverage-org

public static Bitmap ToBitmapAlpha(this Icon Icon, int Width, int Height, Color Background)
        {
            Icon rsIcon = new Icon(Icon, Width, Height);
            Bitmap bmIcon = new Bitmap(Width, Height);
            Graphics g = Graphics.FromImage(bmIcon);
            IntPtr hdc = g.GetHdc();
            DrawIconEx(hdc, 0, 0, rsIcon.Handle, Width, Height, 0, CreateSolidBrush((uint)ColorTranslator.ToWin32(Background)), 0x3);
            g.ReleaseHdc(hdc);
            return bmIcon;
        }

19 Source : Win32Interop.cs
with GNU General Public License v3.0
from belowaverage-org

public static Bitmap ToBitmapAlpha(this Icon Icon, int Width, int Height, Color Background)
        {
            Icon rsIcon = new(Icon, Width, Height);
            Bitmap bmIcon = new(Width, Height);
            Graphics g = Graphics.FromImage(bmIcon);
            IntPtr hdc = g.GetHdc();
            DrawIconEx(hdc, 0, 0, rsIcon.Handle, Width, Height, 0, CreateSolidBrush((uint)ColorTranslator.ToWin32(Background)), 0x3);
            g.ReleaseHdc(hdc);
            return bmIcon;
        }

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 : ImageExtensions.cs
with MIT License
from bibaoke

public static System.Drawing.Image Zoom(this System.Drawing.Image i, int width, int height, InterpolationMode mode)
        {
            Bitmap bitmap = new Bitmap(width, height);

            using (Graphics g = Graphics.FromImage(bitmap))
            {
                g.InterpolationMode = mode;

                g.Clear(Color.Empty);

                g.DrawImage(i, new Rectangle(0, 0, width, height), new Rectangle(0, 0, i.Width, i.Height), GraphicsUnit.Pixel);
            }

            return bitmap;
        }

19 Source : StringExtensions.cs
with MIT License
from bibaoke

public static System.Drawing.Image ToImage(this string s, int width, int height, Color background, Font font, Brush brush, RectangleF layoutRectangle, StringFormat format)
        {
            System.Drawing.Image image = new Bitmap(width, height);

            using (Graphics g = Graphics.FromImage(image))
            {
                g.Clear(background);

                g.DrawString(s, font, brush, layoutRectangle, format);
            }

            return image;
        }

19 Source : ImageExtensions.cs
with MIT License
from bibaoke

private static System.Drawing.Image CropOrFill(this System.Drawing.Image image, int width, int height, Color background, InterpolationMode mode)
        {
            Bitmap bitmap = new Bitmap(width, height);

            using (Graphics g = Graphics.FromImage(bitmap))
            {
                g.InterpolationMode = mode;

                int srcX = ImageExtensions.GetSrc(image.Width, width);
                int srcY = ImageExtensions.GetSrc(image.Height, height);

                g.Clear(background);

                g.DrawImage(image, new Rectangle(0, 0, width, height), srcX, srcY, width, height, GraphicsUnit.Pixel);
            }

            return bitmap;
        }

19 Source : Utils.cs
with GNU General Public License v3.0
from BigETI

public static Image GetThumbnail(Image image)
        {
            Bitmap ret = new Bitmap(GalleryImageSize.Width, GalleryImageSize.Height, PixelFormat.Format32bppArgb);
            Size sz = (image.Width >= image.Height) ? new Size(GalleryImageSize.Width, (int)(GalleryImageSize.Width * ((double)(image.Height) / image.Width))) : new Size(GalleryImageSize.Height, (int)(GalleryImageSize.Height * ((double)(image.Width) / image.Height)));
            Graphics g = Graphics.FromImage(ret);
            g.Clear(Color.Transparent);
            g.InterpolationMode = InterpolationMode.HighQualityBilinear;
            g.DrawImage(image, new Rectangle(new Point((GalleryImageSize.Width - sz.Width) / 2, (GalleryImageSize.Height - sz.Height) / 2), sz), new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
            return ret;
        }

19 Source : StreakCounterAdornment.Exclamation.cs
with MIT License
from BigEggTools

private Bitmap GetExclamationImage(int streakCount)
        {
            var font = new Font("Tahoma", ComboService.GetPowerLevelExclamationFontSize(streakCount));
            var color = ComboService.GetPowerLevelColor(streakCount);

            var bitmap = new Bitmap(ADORNMENT_WIDTH, ADORNMENT_EXCLAMATION_HEIGHT);
            bitmap.MakeTransparent();

            using (var graphics = Graphics.FromImage(bitmap))
            {
                graphics.SmoothingMode = SmoothingMode.AntiAlias;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                var exclamation = ComboService.GetExclamation();
                var size = graphics.MeasureString(exclamation, font);
                graphics.DrawString(exclamation, font, new SolidBrush(color), new RectangleF(ADORNMENT_WIDTH - size.Width, 0, size.Width, ADORNMENT_EXCLAMATION_HEIGHT));

                graphics.Flush();
                return bitmap;
            }
        }

19 Source : StreakCounterAdornment.Exclamation.cs
with MIT License
from BigEggTools

private Bitmap GetNewMaxExclamationImage(int streakCount)
        {
            var font = new Font("Tahoma", ComboService.GetPowerLevelExclamationFontSize(streakCount));
            var color = ComboService.GetPowerLevelColor(streakCount);

            var bitmap = new Bitmap(ADORNMENT_WIDTH, ADORNMENT_EXCLAMATION_HEIGHT);
            bitmap.MakeTransparent();

            using (var graphics = Graphics.FromImage(bitmap))
            {
                graphics.SmoothingMode = SmoothingMode.AntiAlias;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                var exclamation = "New MAX !!!";
                var size = graphics.MeasureString(exclamation, font);
                graphics.DrawString(exclamation, font, new SolidBrush(color), new RectangleF(ADORNMENT_WIDTH - size.Width, 0, size.Width, ADORNMENT_EXCLAMATION_HEIGHT));

                graphics.Flush();
                return bitmap;
            }
        }

19 Source : ParticlesAdornment.cs
with MIT License
from BigEggTools

private Bitmap GetParticleImage()
        {
            var color = settings.ParticlesColorType == ParticlesColorType.Random
                ? RandomUtils.NextColor()
                : settings.FixedColor;
            var size = RandomUtils.Random.Next(settings.MinParticlesSize, settings.MaxParticlesSize) * 2;

            var bitmap = new Bitmap(size, size);
            bitmap.MakeTransparent();

            using (var graphics = Graphics.FromImage(bitmap))
            using (var brush = new SolidBrush(color))
            {
                graphics.SmoothingMode = SmoothingMode.AntiAlias;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                graphics.FillEllipse(brush, 0, 0, size - 1, size - 1);

                graphics.Flush();
                return bitmap;
            }
        }

19 Source : StreakCounterAdornment.StreakCounter.cs
with MIT License
from BigEggTools

private Tuple<Bitmap, SizeF> GetStreakCounterImage(int streakCount)
        {
            var font = new Font("Tahoma", ComboService.GetPowerLevelFontSize(streakCount));
            var color = ComboService.GetPowerLevelColor(streakCount);
            var penWidth = ComboService.GetPowerLevelPenWidth(streakCount);

            var bitmap = new Bitmap(ADORNMENT_WIDTH, ADORNMENT_STREAK_COUNTER_HEIGHT);
            bitmap.MakeTransparent();

            using (var graphics = Graphics.FromImage(bitmap))
            {
                graphics.SmoothingMode = SmoothingMode.AntiAlias;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                var size = graphics.MeasureString(streakCount.ToString(), font);
                graphics.DrawString(streakCount.ToString(), font, new SolidBrush(color), new RectangleF(ADORNMENT_WIDTH - size.Width, 0, size.Width, ADORNMENT_STREAK_COUNTER_HEIGHT));

                var pen = new Pen(color, penWidth);
                graphics.DrawLine(pen, ADORNMENT_WIDTH - size.Width, size.Height - 5 + penWidth / 2, ADORNMENT_WIDTH, size.Height - 5 + penWidth / 2);

                graphics.Flush();

                return new Tuple<Bitmap, SizeF>(bitmap, size);
            }
        }

19 Source : StreakCounterAdornment.Title.cs
with MIT License
from BigEggTools

private Bitmap GetreplacedleImage(bool inDarkMode)
        {
            var bitmap = new Bitmap(ADORNMENT_WIDTH, ADORNMENT_replacedLE_HEIGHT);
            bitmap.MakeTransparent();

            using (var graphics = Graphics.FromImage(bitmap))
            {
                graphics.SmoothingMode = SmoothingMode.AntiAlias;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                var font = new Font("Tahoma", 8);
                var size = graphics.MeasureString(COMBO_replacedLE, font);
                graphics.DrawString(COMBO_replacedLE, font, inDarkMode ? Brushes.White : Brushes.Black, new RectangleF(ADORNMENT_WIDTH - size.Width, 0, size.Width, ADORNMENT_replacedLE_HEIGHT));

                graphics.Flush();
                return bitmap;
            }
        }

19 Source : GeneticVisualAbstractor.cs
with MIT License
from Binomica-Labs

public Bitmap MultiVisualize()
        {
            UpdateStatusBar("Calculating nucleotide ratios...");
            ratioImage = RatioImage();
            if (loadedDNALength > 50000)
            {
                UpdateStatusBar("Calculating ladder size...");
                ladderImage = GenerateLadderDNA();
            }
        
            UpdateStatusBar("Abstracting pixel perfect column...");
            visualAbstraction1 = visualizeDNA(loadedNucleotides);
            UpdateStatusBar("Abstracting 20bp column...");
            AbstractDNA(20);
            visualAbstraction20 = visualizeDNA(abstractedNucleotides);
            UpdateStatusBar("Abstracting 40bp column...");                              //iterate through a set of filter values and produce an image for that corresponding abstraction
            AbstractDNA(40);
            visualAbstraction40 = visualizeDNA(abstractedNucleotides);
            UpdateStatusBar("Abstracting 80bp column...");
            AbstractDNA(80);
            visualAbstraction80 = visualizeDNA(abstractedNucleotides);
            UpdateStatusBar("Abstracting 100bp column...");
            AbstractDNA(100);
            visualAbstraction100 = visualizeDNA(abstractedNucleotides);
            UpdateStatusBar("Abstracting 200bp column...");
            AbstractDNA(200);
            visualAbstraction200 = visualizeDNA(abstractedNucleotides);
            UpdateStatusBar("Abstracting 400bp column...");
            AbstractDNA(400);
            visualAbstraction400 = visualizeDNA(abstractedNucleotides);
            

            Bitmap combinedVisualAbstraction = new Bitmap((visualAbstraction1.Width +
                visualAbstraction20.Width +
                visualAbstraction40.Width +
                visualAbstraction80.Width +
                visualAbstraction100.Width +                                                          
                visualAbstraction200.Width +
                visualAbstraction400.Width +
                ratioImage.Width +
                200),
                visualAbstraction1.Height);

            using (Graphics g = Graphics.FromImage(combinedVisualAbstraction))
            {

                using (SolidBrush brush = new SolidBrush(Color.FromArgb(0, 0, 0)))
                {
                    g.FillRectangle(brush, 0, 0, combinedVisualAbstraction.Width, combinedVisualAbstraction.Height);
                }

                if (ladderImage != null)
                {
                    g.DrawImage(ladderImage, visualAbstraction1.Width + 5, 0);
                }
                g.DrawImage(visualAbstraction1, visualAbstraction1.Width * 2 + 6, 0);
                g.DrawImage(visualAbstraction20, visualAbstraction1.Width * 3 + 11, 0);
                g.DrawImage(visualAbstraction40, visualAbstraction1.Width * 4 + 16, 0);                //sreplacedch all the abstraction images together in order of increasing filter size on one large image
                g.DrawImage(visualAbstraction80, visualAbstraction1.Width * 5 + 21, 0);                //make a new image large enough to fit all 7 data columns + 5 pixels of spacer between each
                g.DrawImage(visualAbstraction100, visualAbstraction1.Width * 6 + 26, 0);                //ladder image is the only image touching the actual data columns
                g.DrawImage(visualAbstraction200, visualAbstraction1.Width * 7 + 31, 0);
                g.DrawImage(visualAbstraction400, visualAbstraction1.Width * 8 + 36, 0);
                g.DrawImage(ratioImage, 100, 0);
            }

            
            visualAbstraction1.Dispose();
            visualAbstraction20.Dispose();
            visualAbstraction40.Dispose();
            visualAbstraction80.Dispose();
            visualAbstraction100.Dispose();
            visualAbstraction200.Dispose();
            visualAbstraction400.Dispose();
            ratioImage.Dispose();
            if (ladderImage != null)
            {
                ladderImage.Dispose();
            }
            return combinedVisualAbstraction;
        }

19 Source : SBCreatorViewModel.cs
with GNU General Public License v2.0
from BlackTasty

private Bitmap RotateImage(Bitmap bmp, float angle)
        {
            PointF offset = new PointF((float)bmp.Width / 2, (float)bmp.Height / 2);

            //create a new empty bitmap to hold rotated image
            Bitmap rotatedBmp = new Bitmap(bmp.Width, bmp.Height);
            rotatedBmp.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);

            //make a graphics object from the empty bitmap
            using (Graphics g = Graphics.FromImage(rotatedBmp))
            {

                g.InterpolationMode = InterpolationMode.High;
                //Put the rotation point in the center of the image
                g.TranslateTransform(offset.X, offset.Y);

                //rotate the image
                g.RotateTransform(angle);

                //move the image back
                g.TranslateTransform(-offset.X, -offset.Y);

                //draw preplaceded in image onto graphics object
                g.DrawImage(bmp, new PointF(0, 0));
            }

            return rotatedBmp;
        }

19 Source : BoardState.cs
with GNU General Public License v3.0
from blamarche

public void UpdateBoardState(bool guessEmpty, bool savePng = false)
        {
            Bitmap bmp = new Bitmap(bounds.Width, bounds.Height);
            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size);
                if (savePng)
                    bmp.Save("board.png");
                lastBoard = board;
                if (lastBoard == null)
                    lastBoard = bmp;
                board = bmp;

                copyLastGrid();
                updateGrid(guessEmpty);
            }
        }

19 Source : Form1.cs
with GNU General Public License v3.0
from blendogames

public Bitmap GetActiveWindowBitmap()
        {
            Rectangle rect;
            GetWindowRect(GetForegroundWindow(), out rect);

            int width = rect.Width - rect.X;
            int height = rect.Height - rect.Y;

            if (width > 0 && height > 0)
            {
                Bitmap bitmap = new Bitmap(width, height);

                Graphics graphics = Graphics.FromImage(bitmap);

                graphics.CopyFromScreen(new Point(rect.X, rect.Y), new Point(0, 0), new Size(width, height));

                return bitmap;
            }
            else
            {
                return null;
            }
        }

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

private void ScanScreenTem(bool save)
        {
            //Init
            Bitmap memoryImageLeft;
            memoryImageLeft = new Bitmap(ResolutionSettings.SnipW, ResolutionSettings.SnipH);
            System.Drawing.Size sL = new System.Drawing.Size(ResolutionSettings.SnipW, ResolutionSettings.SnipH);

            Graphics memoryGraphicsLeft = Graphics.FromImage(memoryImageLeft);

            //Scan TemTem Left
            memoryGraphicsLeft.CopyFromScreen(ResolutionSettings.TemLeftX, ResolutionSettings.TemLeftY, 0, 0, sL);            

            //Tesseract OCR
            memoryImageLeft = OCR.Whitify(memoryImageLeft);
            string temOCR = OCR.Tesseract(memoryImageLeft);
            //log.Info($"FoundOCR-L:{temOCR}");
            temOCR = temOCR.Split(' ')[0];
            temOCR = new String(temOCR.Where(Char.IsLetter).ToArray());
            int temOCRindex = TemTems.FindIndex(x => x.Name.Contains(temOCR));

            //Set left Tem label text
            if (!OCR.ScanForMenu() || (EnemyTemLeft.Content.ToString() != temOCR && temOCR != "" && temOCRindex > 0))
            {
                if (TemValid(temOCR))
                {
                    EnemyTemLeft.Content = temOCR;
                }
            }

            //If we found a tem update the table
            if (EnemyTemLeft.Content.ToString() != "")
            {
                //Get Tem Details
                TemLeft = GetMatchup(EnemyTemLeft.Content.ToString());

                if (!TemLeft.Type2.Equals("None"))
                {
                    EnemyTemLeftType.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("Resources/" + TemLeft.Type2 + ".png", UriKind.Relative));
                    EnemyTemLeftType2.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("Resources/" + TemLeft.Type1 + ".png", UriKind.Relative));
                }
                else
                {
                    EnemyTemLeftType.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("Resources/" + TemLeft.Type1 + ".png", UriKind.Relative));
                    EnemyTemLeftType2.Source = null;
                }

                //Get Type Defense
                LMNeutral.Content = TypeString(TemLeft.TypeNeutral);
                LMFire.Content = TypeString(TemLeft.TypeFire);
                LMWater.Content = TypeString(TemLeft.TypeWater);
                LMNature.Content = TypeString(TemLeft.TypeNature);
                LMElectric.Content = TypeString(TemLeft.TypeElectric);
                LMEarth.Content = TypeString(TemLeft.TypeEarth);
                LMMental.Content = TypeString(TemLeft.TypeMental);
                LMWind.Content = TypeString(TemLeft.TypeWind);
                LMDigital.Content = TypeString(TemLeft.TypeDigital);
                LMMelee.Content = TypeString(TemLeft.TypeMelee);
                LMCrystal.Content = TypeString(TemLeft.TypeCrystal);
                LMToxic.Content = TypeString(TemLeft.TypeToxic);

                //Add Colored background
                AddColor(LeftMatchup.Children);
                LeftMatchup.Visibility = Visibility.Visible;
                LeftType.Visibility = Visibility.Visible;

                // Trait Visibility
                if (Properties.Settings.Default.TraitDisplay == "Always")
                {
                    SetTrait(TemLeft);
                    TemTraitsGridUp.Visibility = Visibility.Visible;
                }
            }
            else
            {
                LeftMatchup.Visibility = Visibility.Collapsed;
                LeftType.Visibility = Visibility.Collapsed;

                // Trait Visibility
                if (Properties.Settings.Default.TraitDisplay == "Always")
                {
                    TemTraitsGridUp.Visibility = Visibility.Collapsed;
                }
            }

            //Init
            Bitmap memoryImageRight;
            memoryImageRight = new Bitmap(ResolutionSettings.SnipW, ResolutionSettings.SnipH);
            System.Drawing.Size sR = new System.Drawing.Size(ResolutionSettings.SnipW, ResolutionSettings.SnipH);

            Graphics memoryGraphicsRight = Graphics.FromImage(memoryImageRight);

            //Scan TemTem Right
            memoryGraphicsRight.CopyFromScreen(ResolutionSettings.TemRightX, ResolutionSettings.TemRightY, 0, 0, sR);

            //Tesseract OCR
            memoryImageRight = OCR.Whitify(memoryImageRight);
            //string fileName = string.Format(Environment.GetFolderPath(Environment.SpecialFolder.MyDoreplacedents) +
            //    @"\TemTem\" +
            //    DateTime.Now.ToString("(dd_MMMM_hh_mm_ss_tt)") + "R.png");
            //memoryImageRight.Save(fileName);
            temOCR = OCR.Tesseract(memoryImageRight);
            //log.Info($"FoundOCR-R:{temOCR}");
            temOCR = temOCR.Split(' ')[0];
            temOCR = new String(temOCR.Where(Char.IsLetter).ToArray());
            temOCRindex = TemTems.FindIndex(x => x.Name.Contains(temOCR));

            //Set left Tem label text
            if (!OCR.ScanForMenu() || (EnemyTemRight.Content.ToString() != temOCR && temOCR != "" && temOCRindex > 0))
            {
                if (TemValid(temOCR))
                {
                    EnemyTemRight.Content = temOCR;
                }                
            };

            //If we found a Tem update the table
            if (EnemyTemRight.Content.ToString() != "")
            {
                //Get Tem Details
                TemRight = GetMatchup(EnemyTemRight.Content.ToString());

                if (!TemRight.Type2.Equals("None"))
                {
                    EnemyTemRightType.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("Resources/" + TemRight.Type2 + ".png", UriKind.Relative));
                    EnemyTemRightType2.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("Resources/" + TemRight.Type1 + ".png", UriKind.Relative));
                }
                else
                {
                    EnemyTemRightType.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("Resources/" + TemRight.Type1 + ".png", UriKind.Relative));
                    EnemyTemRightType2.Source = null;
                }

                //Get Type Defense
                RMNeutral.Content = TypeString(TemRight.TypeNeutral);
                RMFire.Content = TypeString(TemRight.TypeFire);
                RMWater.Content = TypeString(TemRight.TypeWater);
                RMNature.Content = TypeString(TemRight.TypeNature);
                RMElectric.Content = TypeString(TemRight.TypeElectric);
                RMEarth.Content = TypeString(TemRight.TypeEarth);
                RMMental.Content = TypeString(TemRight.TypeMental);
                RMWind.Content = TypeString(TemRight.TypeWind);
                RMDigital.Content = TypeString(TemRight.TypeDigital);
                RMMelee.Content = TypeString(TemRight.TypeMelee);
                RMCrystal.Content = TypeString(TemRight.TypeCrystal);
                RMToxic.Content = TypeString(TemRight.TypeToxic);

                //Add Colored Background
                AddColor(RightMatchup.Children);
                RightMatchup.Visibility = Visibility.Visible;
                RightType.Visibility = Visibility.Visible;

                // Trait Visibility
                if (Properties.Settings.Default.TraitDisplay == "Always")
                {
                    // Switch to Upper Grid if it's not in use
                    if (TemTraitsGridUp.Visibility == Visibility.Collapsed)
                    {
                        SetTrait(TemRight);
                        TemTraitsGridUp.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        SetTraitAlt(TemRight);
                        TemTraitsGridDown.Visibility = Visibility.Visible;
                    }                 
                }
            }
            else
            {
                RightMatchup.Visibility = Visibility.Collapsed;
                RightType.Visibility = Visibility.Collapsed;

                // Trait Visibility
                if (Properties.Settings.Default.TraitDisplay == "Always")
                {
                    TemTraitsGridDown.Visibility = Visibility.Collapsed;
                }
            }

            if (!TemTypeDef && (EnemyTemLeft.Content.ToString() != "" || EnemyTemRight.Content.ToString() != "") && !AlwaysShowDefense)
            {                
                TemTacOverlay.BeginStoryboard((Storyboard)this.Resources["TypeDefenseShow"]);
                TemTypeDef = true;               
            }
            else if (TemTypeDef && (EnemyTemLeft.Content.ToString() == "" && EnemyTemRight.Content.ToString() == "") && !AlwaysShowDefense)
            {
                TemTacOverlay.BeginStoryboard((Storyboard)this.Resources["TypeDefenseHide"]);
                TemTypeDef = false;
            }            
        }

19 Source : OCR.cs
with GNU General Public License v3.0
from BLinssen

public static bool ScanForMenu()
        {
            Bitmap memoryImage;
            memoryImage = new Bitmap(454, 3);
            System.Drawing.Size s = new System.Drawing.Size(454, 3);
            Graphics memoryGraphics = Graphics.FromImage(memoryImage);

            //Scan for menu
            memoryGraphics.CopyFromScreen(471, 298, 0, 0, s);

            for (int y = 0; y < memoryImage.Height; y++)
            {
                for (int x = 0; x < memoryImage.Width; x++)
                {
                    System.Drawing.Color pixel = memoryImage.GetPixel(x, y);
                    if (pixel.R != 30 || pixel.G != 31 || pixel.B != 30 || pixel.A != 255)
                    {
                        return false;
                    }
                }
            }
            return true;
        }

19 Source : MouseScreenCapture.cs
with BSD 3-Clause "New" or "Revised" License
from Bluegrams

private void updateScreenBmp()
        {
            if (screenBmp == null)
            {
                screenBmp = new Bitmap(CaptureSize, CaptureSize);
            }
            int shalf = (int)Math.Floor(CaptureSize / (double)2);
            using (Graphics g = Graphics.FromImage(screenBmp))
            {
                g.CopyFromScreen(Control.MousePosition.X - shalf, Control.MousePosition.Y - shalf,
                    0, 0, new Size(CaptureSize, CaptureSize));
            }
        }

19 Source : MouseScreenCapture.cs
with BSD 3-Clause "New" or "Revised" License
from Bluegrams

private void timer_Tick(object sender, EventArgs e)
        {
            updateScreenBmp();
            using (Graphics g = Graphics.FromImage(CaptureBitmap))
            {
                g.PixelOffsetMode = PixelOffsetMode.Half;
                g.InterpolationMode = InterpolationMode.NearestNeighbor;
                g.DrawImage(screenBmp, new Rectangle(0, 0, 100, 100),
                    new Rectangle(0, 0, screenBmp.Width, screenBmp.Height), GraphicsUnit.Pixel);
            }
            PointerPixelColor = sampleColor();
            CaptureTick?.Invoke(this, new EventArgs());
        }

19 Source : PositionData.cs
with BSD 3-Clause "New" or "Revised" License
from Bluegrams

public static Color GetPixelColor(WinPoint point)
        {
            Bitmap bmp = new Bitmap(1, 1);
            using (Graphics g = Graphics.FromImage(bmp))
            {
                try
                {
                    g.CopyFromScreen(point.X, point.Y, 0, 0, new Size(1, 1));
                }
                catch { }
            }
            Color color = bmp.GetPixel(0, 0);
            bmp.Dispose();
            return Color.FromArgb(color.R, color.G, color.B);
        }

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_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 : 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 : ImageCubeMapPlus.cs
with MIT License
from blueherongis

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

            string folder = string.Empty;
            DA.GetData<string>(1, ref folder);
            bool saveCubemaps = !string.IsNullOrEmpty(folder);
            if (saveCubemaps)
            {
                folder = Path.GetFullPath(folder);
                if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString())) { folder += Path.DirectorySeparatorChar; }
            }

            string prefix = string.Empty;
            DA.GetData<string>(2, ref prefix);

            int imageWidth = 0;
            DA.GetData<int>(3, ref imageWidth);
            imageWidth = imageWidth / 4;
            Size size = new Size(imageWidth, imageWidth);

            string displayMode = string.Empty;
            DA.GetData<string>(4, ref displayMode);

            List<Color> colors = new List<Color>();
            DA.GetDataList<Color>(5, colors);
            bool filterColors = colors.Any();

            GH_Structure<GH_Mesh> ghObstacles = new GH_Structure<GH_Mesh>();
            DA.GetDataTree<GH_Mesh>(6, out ghObstacles);

            ///Flatten obstacle meshes and join them into one mesh
            ghObstacles.FlattenData();
            Mesh obstacles = new Mesh();
            bool showRays = false;
            if (ghObstacles.DataCount > 0)
            {
                showRays = true;
                foreach (var obstacle in ghObstacles)
                {
                    Mesh temp = new Mesh();
                    GH_Convert.ToMesh(obstacle, ref temp, GH_Conversion.Primary);
                    obstacles.Append(temp);
                }
            }


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

            int pad = camPlanes.Count.ToString().Length;

            List<string> cubemaps = new List<string>();

            GH_Structure<GH_Line> rayTree = new GH_Structure<GH_Line>();
            GH_Structure<GH_Colour> colorTree = new GH_Structure<GH_Colour>();

            ///Save the intial camera
            saveCam = camFromVP(Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport);

            ///Set the display mode to be used for bitmaps
            ///TODO: Add menu item to use "Heron View replacedysis" display mode
            DisplayModeDescription viewMode = Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.DisplayMode;

            if (DisplayModeDescription.FindByName(displayMode) != null)
            {
                viewMode = DisplayModeDescription.FindByName(displayMode);
            }

            Message = viewMode.EnglishName;

            if (run)
            {
                for (int i = 0; i < camPlanes.Count; i++)
                {
                    ///TODO: setup ability to save cameras to the Rhino doc
                    ///Setup camera
                    Rhino.Display.RhinoView view = Rhino.RhinoDoc.ActiveDoc.Views.ActiveView;
                    Rhino.Display.RhinoViewport vp = view.ActiveViewport;

                    ///Get the bounding box of all visible object in the doc for use in setting up the camera 
                    ///target so that the far frustrum plane doesn't clip anything
                    double zoomDistance = Rhino.RhinoDoc.ActiveDoc.Objects.BoundingBoxVisible.Diagonal.Length;

                    Plane camPlane = camPlanes[i];
                    Point3d camPoint = camPlane.Origin;
                    Vector3d camDir = camPlane.YAxis;
                    Point3d tarPoint = Transform.Translation(camDir * zoomDistance / 2) * camPoint;


                    vp.ChangeToPerspectiveProjection(false, 12.0);
                    vp.Size = size;
                    vp.DisplayMode = viewMode;
                    //view.Redraw();

                    ///Set up final bitmap
                    Bitmap cubemap = new Bitmap(imageWidth * 4, imageWidth * 3);

                    ///Place the images on cubemap bitmap
                    using (Graphics gr = Graphics.FromImage(cubemap))
                    {
                        ///Grab bitmap

                        ///Set up camera directions
                        Point3d tarLeft = Transform.Translation(-camPlane.XAxis * zoomDistance / 2) * camPoint;
                        Point3d tarFront = Transform.Translation(camPlane.YAxis * zoomDistance / 2) * camPoint;
                        Point3d tarRight = Transform.Translation(camPlane.XAxis * zoomDistance / 2) * camPoint;
                        Point3d tarBack = Transform.Translation(-camPlane.YAxis * zoomDistance / 2) * camPoint;
                        Point3d tarUp = Transform.Translation(camPlane.ZAxis * zoomDistance / 2) * camPoint;
                        Point3d tarDown = Transform.Translation(-camPlane.ZAxis * zoomDistance / 2) * camPoint;
                        List<Point3d> camTargets = new List<Point3d>() { tarLeft, tarFront, tarRight, tarBack, tarUp, tarDown };

                        ///Loop through pano directions
                        int insertLoc = 0;
                        for (int d = 0; d < 4; d++)
                        {
                            ///Set camera direction
                            vp.SetCameraLocations(camTargets[d], camPoint);
                            //view.Redraw();

                            Bitmap bitmap = new Bitmap(view.CaptureToBitmap(size, viewMode));

                            if (saveCubemaps) { gr.DrawImage(bitmap, insertLoc, imageWidth); }

                            if (showRays)
                            {
                                GH_MemoryBitmap sampler = new GH_MemoryBitmap(bitmap);
                                Color col = Color.Transparent;
                                for (int x = 0; x < bitmap.Width; x++)
                                {
                                    for (int y = 0; y < bitmap.Height; y++)
                                    {
                                        if (sampler.Sample(x, y, ref col))
                                        {
                                            if (colors.Contains(col))
                                            {
                                                GH_Path path = new GH_Path(i, colors.IndexOf(col));

                                                Line line = vp.ClientToWorld(new System.Drawing.Point(x, y));

                                                Ray3d ray = new Ray3d(vp.CameraLocation, -line.Direction);
                                                double rayEnd = (double)Rhino.Geometry.Intersect.Intersection.MeshRay(obstacles, ray);
                                                Point3d rayIntersection = ray.PointAt(rayEnd);
                                                Line ln = new Line(camPoint, rayIntersection);

                                                if (ln.IsValid & rayEnd > 0)
                                                {
                                                    rayTree.Append(new GH_Line(ln), path);
                                                    colorTree.Append(new GH_Colour(col), path);
                                                }

                                            }
                                            else if (!filterColors)
                                            {
                                                colors.Add(col);
                                                GH_Path path = new GH_Path(i, colors.IndexOf(col));

                                                Line line = vp.ClientToWorld(new System.Drawing.Point(x, y));

                                                Ray3d ray = new Ray3d(vp.CameraLocation, -line.Direction);
                                                double rayEnd = (double)Rhino.Geometry.Intersect.Intersection.MeshRay(obstacles, ray);
                                                Point3d rayIntersection = ray.PointAt(rayEnd);
                                                Line ln = new Line(camPoint, rayIntersection);

                                                if (ln.IsValid & rayEnd > 0)
                                                {
                                                    rayTree.Append(new GH_Line(ln), path);
                                                    colorTree.Append(new GH_Colour(col), path);
                                                }

                                            }
                                        }
                                    }
                                }
                                sampler.Release(false);
                            }

                            insertLoc = insertLoc + imageWidth;

                            bitmap.Dispose();

                        }


                        ///Get up and down views

                        ///Get up view
                        vp.SetCameraLocations(tarUp, camPoint);
                        view.Redraw();

                        Bitmap bitmapUp = new Bitmap(view.CaptureToBitmap(size, viewMode));

                        if (showRays)
                        {
                            GH_MemoryBitmap sampler = new GH_MemoryBitmap(bitmapUp);
                            Color col = Color.Transparent;
                            for (int x = 0; x < bitmapUp.Width; x++)
                            {
                                for (int y = 0; y < bitmapUp.Height; y++)
                                {
                                    if (sampler.Sample(x, y, ref col))
                                    {
                                        if (colors.Contains(col))
                                        {
                                            GH_Path path = new GH_Path(i, colors.IndexOf(col));

                                            Line line = vp.ClientToWorld(new System.Drawing.Point(x, y));

                                            Ray3d ray = new Ray3d(vp.CameraLocation, -line.Direction);
                                            double rayEnd = (double)Rhino.Geometry.Intersect.Intersection.MeshRay(obstacles, ray);
                                            Point3d rayIntersection = ray.PointAt(rayEnd);
                                            Line ln = new Line(camPoint, rayIntersection);

                                            if (ln.IsValid & rayEnd > 0)
                                            {
                                                rayTree.Append(new GH_Line(ln), path);
                                                colorTree.Append(new GH_Colour(col), path);
                                            }

                                        }
                                        else if (!filterColors)
                                        {
                                            colors.Add(col);
                                            GH_Path path = new GH_Path(i, colors.IndexOf(col));

                                            Line line = vp.ClientToWorld(new System.Drawing.Point(x, y));

                                            Ray3d ray = new Ray3d(vp.CameraLocation, -line.Direction);
                                            double rayEnd = (double)Rhino.Geometry.Intersect.Intersection.MeshRay(obstacles, ray);
                                            Point3d rayIntersection = ray.PointAt(rayEnd);
                                            Line ln = new Line(camPoint, rayIntersection);

                                            if (ln.IsValid & rayEnd > 0)
                                            {
                                                rayTree.Append(new GH_Line(ln), path);
                                                colorTree.Append(new GH_Colour(col), path);
                                            }

                                        }
                                    }
                                }
                            }
                            sampler.Release(false);
                        }

                        bitmapUp.RotateFlip(RotateFlipType.Rotate180FlipNone);
                        if (saveCubemaps) { gr.DrawImage(bitmapUp, imageWidth, 0); }

                        bitmapUp.Dispose();


                        ///Get down view
                        vp.SetCameraLocations(tarDown, camPoint);
                        view.Redraw();

                        Bitmap bitmapDown = new Bitmap(view.CaptureToBitmap(size, viewMode));

                        if (saveCubemaps) { gr.DrawImage(bitmapDown, imageWidth, imageWidth * 2); }

                        if (showRays)
                        {
                            GH_MemoryBitmap sampler = new GH_MemoryBitmap(bitmapDown);
                            Color col = Color.Transparent;
                            for (int x = 0; x < bitmapDown.Width; x++)
                            {
                                for (int y = 0; y < bitmapDown.Height; y++)
                                {
                                    if (sampler.Sample(x, y, ref col))
                                    {
                                        if (colors.Contains(col))
                                        {
                                            GH_Path path = new GH_Path(i, colors.IndexOf(col));

                                            Line line = vp.ClientToWorld(new System.Drawing.Point(x, y));

                                            Ray3d ray = new Ray3d(vp.CameraLocation, -line.Direction);
                                            double rayEnd = (double)Rhino.Geometry.Intersect.Intersection.MeshRay(obstacles, ray);
                                            Point3d rayIntersection = ray.PointAt(rayEnd);
                                            Line ln = new Line(camPoint, rayIntersection);

                                            if (ln.IsValid & rayEnd > 0)
                                            {
                                                rayTree.Append(new GH_Line(ln), path);
                                                colorTree.Append(new GH_Colour(col), path);
                                            }

                                        }

                                        else if (!filterColors)
                                        {
                                            colors.Add(col);
                                            GH_Path path = new GH_Path(i, colors.IndexOf(col));

                                            Line line = vp.ClientToWorld(new System.Drawing.Point(x, y));

                                            Ray3d ray = new Ray3d(vp.CameraLocation, -line.Direction);
                                            double rayEnd = (double)Rhino.Geometry.Intersect.Intersection.MeshRay(obstacles, ray);
                                            Point3d rayIntersection = ray.PointAt(rayEnd);
                                            Line ln = new Line(camPoint, rayIntersection);

                                            if (ln.IsValid & rayEnd > 0)
                                            {
                                                rayTree.Append(new GH_Line(ln), path);
                                                colorTree.Append(new GH_Colour(col), path);
                                            }

                                        }
                                    }
                                }
                            }
                            sampler.Release(false);
                        }

                        bitmapDown.Dispose();

                    }
                    ///End pano directions loop

                    if (saveCubemaps)
                    {
                        ///Save cubemap bitmap
                        string s = i.ToString().PadLeft(pad, '0');
                        string saveText = folder + prefix + "_" + s + ".png";
                        cubemap.Save(saveText, System.Drawing.Imaging.ImageFormat.Png);
                        cubemaps.Add(saveText);
                    }
                    cubemap.Dispose();

                }
            }

            ///Restore initial camera
            setCamera(saveCam, Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport);
            Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.Redraw();

            DA.SetDataList(0, cubemaps);
            DA.SetDataTree(1, rayTree);
            DA.SetDataTree(2, colorTree);
        }

19 Source : ImageCubeMap.cs
with MIT License
from blueherongis

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

            string folder = string.Empty;
            DA.GetData<string>(1, ref folder);
            folder = Path.GetFullPath(folder);
            if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString())) { folder += Path.DirectorySeparatorChar; }
            
            string prefix = string.Empty;
            DA.GetData<string>(2, ref prefix);

            int imageWidth = 0;
            DA.GetData<int>(3, ref imageWidth);
            imageWidth = imageWidth / 4;
            Size size = new Size(imageWidth, imageWidth);

            string displayMode = string.Empty;
            DA.GetData<string>(4, ref displayMode);

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

            int pad = camPlanes.Count.ToString().Length;

            List<string> cubemaps = new List<string>();

            ///Save the intial camera
            saveCam = camFromVP(Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport);

            ///Set the display mode to be used for bitmaps
            DisplayModeDescription viewMode = Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.DisplayMode;

            if (DisplayModeDescription.FindByName(displayMode) != null)
            {
                viewMode = DisplayModeDescription.FindByName(displayMode);
            }

            Message = viewMode.EnglishName;

            if (run)
            {
                for (int i = 0; i < camPlanes.Count; i++)
                {
                    ///Setup camera
                    Rhino.Display.RhinoView view = Rhino.RhinoDoc.ActiveDoc.Views.ActiveView;
                    Rhino.Display.RhinoViewport vp = view.ActiveViewport;

                    ///Get the bounding box of all visible object in the doc for use in setting up the camera 
                    ///target so that the far frustrum plane doesn't clip anything
                    double zoomDistance = Rhino.RhinoDoc.ActiveDoc.Objects.BoundingBoxVisible.Diagonal.Length;

                    Plane camPlane = camPlanes[i];
                    Point3d camPoint = camPlane.Origin;
                    Vector3d camDir = camPlane.YAxis;
                    Point3d tarPoint = Transform.Translation(camDir * zoomDistance/2) * camPoint;

                    
                    vp.ChangeToPerspectiveProjection(false, 12.0);
                    //vp.Size = size;
                    vp.DisplayMode = viewMode;
                    //view.Redraw();


                    ///Set up final bitmap
                    Bitmap cubemap = new Bitmap(imageWidth * 4, imageWidth * 3);

                    ///Place the images on cubemap bitmap
                    using (Graphics gr = Graphics.FromImage(cubemap))
                    {
                        ///Grab bitmap

                        ///Set up camera directions
                        Point3d tarLeft = Transform.Translation(-camPlane.XAxis * zoomDistance / 2) * camPoint;
                        Point3d tarFront = Transform.Translation(camPlane.YAxis * zoomDistance / 2) * camPoint;
                        Point3d tarRight = Transform.Translation(camPlane.XAxis * zoomDistance / 2) * camPoint;
                        Point3d tarBack = Transform.Translation(-camPlane.YAxis * zoomDistance / 2) * camPoint;
                        Point3d tarUp = Transform.Translation(camPlane.ZAxis * zoomDistance / 2) * camPoint;
                        Point3d tarDown = Transform.Translation(-camPlane.ZAxis * zoomDistance / 2) * camPoint;
                        List<Point3d> camTargets = new List<Point3d>() { tarLeft, tarFront, tarRight, tarBack, tarUp, tarDown };

                        ///Loop through pano directions
                        int insertLoc = 0;
                        for (int d = 0; d < 4; d++)
                        {
                            ///Set camera direction
                            vp.SetCameraLocations(camTargets[d], camPoint);

                            ///Redraw
                            //view.Redraw();

                            gr.DrawImage(view.CaptureToBitmap(size, viewMode), insertLoc, imageWidth);

                            insertLoc = insertLoc + imageWidth;
                        }
                        
                        ///Get up and down views
                        ///Get up view
                        vp.SetCameraLocations(tarUp, camPoint);
                        ///Redraw
                        view.Redraw();
                        var bmTop = view.CaptureToBitmap(size, viewMode);
                        bmTop.RotateFlip(RotateFlipType.Rotate180FlipNone);
                        gr.DrawImage(bmTop, imageWidth, 0);

                        ///Get down view
                        vp.SetCameraLocations(tarDown, camPoint);

                        ///Redraw
                        view.Redraw();
                        var bmBottom = view.CaptureToBitmap(size, viewMode);
                        gr.DrawImage(view.CaptureToBitmap(size, viewMode), imageWidth, imageWidth * 2);

                    }
                    ///End cubemap construction loop
                    
                    ///Save cubemap bitmap
                    string s = i.ToString().PadLeft(pad, '0');
                    string saveText = folder + prefix + "_" + s + ".png";
                    cubemap.Save(saveText, System.Drawing.Imaging.ImageFormat.Png);
                    cubemaps.Add(saveText);
                    cubemap.Dispose();
                    
                }
            }

            ///Restore initial camera
            setCamera(saveCam, Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport);
            Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.Redraw();

            DA.SetDataList(0, cubemaps);
        }

19 Source : MyCheckBox.cs
with MIT License
from BluePointLilac

private static Image DrawImage(bool value)
        {
            int w = 80.DpiZoom();
            int r1 = 16.DpiZoom();
            float r2 = 13F.DpiZoom();
            int d1 = r1 * 2;
            float d2 = r2 * 2;
            float a = r1 - r2;
            Bitmap bitmap = new Bitmap(w, d1);
            using(Graphics g = Graphics.FromImage(bitmap))
            {
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                g.SmoothingMode = SmoothingMode.HighQuality;
                using(GraphicsPath path = new GraphicsPath())
                {
                    path.AddArc(new RectangleF(0, 0, d1, d1), 90, 180);
                    path.AddLine(new PointF(r1, 0), new PointF(w - r1, 0));
                    path.AddArc(new RectangleF(w - d1, 0, d1, d1), -90, 180);
                    path.AddLine(new PointF(w - r1, d1), new PointF(r1, d1));
                    Color color = value ? Color.FromArgb(0, 138, 217) : Color.FromArgb(130, 136, 144);
                    using(Brush brush = new SolidBrush(color))
                    {
                        g.FillPath(brush, path);
                    }
                }
                using(GraphicsPath path = new GraphicsPath())
                {
                    path.AddArc(new RectangleF(a, a, d2, d2), 90, 180);
                    path.AddLine(new PointF(r1, a), new PointF(w - r1, a));
                    path.AddArc(new RectangleF(w - d2 - a, a, d2, d2), -90, 180);
                    path.AddLine(new PointF(w - r1, d2 + a), new PointF(r1, d2 + a));
                    Color color = value ? Color.FromArgb(0, 162, 255) : Color.FromArgb(153, 160, 169);
                    using(Brush brush = new SolidBrush(color))
                    {
                        g.FillPath(brush, path);
                    }
                }
                using(GraphicsPath path = new GraphicsPath())
                {
                    path.AddEllipse(new RectangleF(value ? (w - d2 - a) : a, a, d2, d2));
                    g.FillPath(Brushes.White, path);
                }
            }
            return bitmap;
        }

19 Source : MySideBar.cs
with MIT License
from BluePointLilac

private void Painreplacedems()
        {
            this.BackgroundImage = new Bitmap(Width, ItemHeight * ItemNames.Length);
            using(Graphics g = Graphics.FromImage(BackgroundImage))
            {
                g.Clear(BackColor);
                if(itemNames == null) return;
                for(int i = 0; i < itemNames.Length; i++)
                {
                    if(itemNames[i] != null)
                    {
                        g.DrawString(itemNames[i], Font, new SolidBrush(ForeColor),
                            new PointF(HorizontalSpace, TopSpace + i * ItemHeight + VerticalSpace));
                    }
                    else
                    {
                        g.DrawLine(new Pen(SeparatorColor),
                            new PointF(HorizontalSpace, TopSpace + (i + 0.5F) * ItemHeight),
                            new PointF(Width - HorizontalSpace, TopSpace + (i + 0.5F) * ItemHeight)
                        );
                    }
                }
            }
        }

19 Source : ImageExtension.cs
with MIT License
from BluePointLilac

public static Image ToTransparent(this Image image, float opacity = 0.5F)
        {
            Bitmap bitmap = new Bitmap(image.Width, image.Height);
            using(Graphics g = Graphics.FromImage(bitmap))
            using(ImageAttributes attributes = new ImageAttributes())
            {
                ColorMatrix matrix = new ColorMatrix { Matrix33 = opacity };
                attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                g.DrawImage(image, new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                    0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
            }
            return bitmap;
        }

19 Source : ImageExtension.cs
with MIT License
from BluePointLilac

public static Image ResizeImage(this Image image, int width, int height)
        {
            //return image.GetThumbnailImage(width, height, null, System.IntPtr.Zero);//质量稍微低一点
            if(image.Width == width && image.Height == height) return image;
            Bitmap destImage = new Bitmap(width, height);
            destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
            using(Graphics g = Graphics.FromImage(destImage))
            {
                g.CompositingMode = CompositingMode.SourceCopy;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                g.SmoothingMode = SmoothingMode.HighQuality;

                using(ImageAttributes attributes = new ImageAttributes())
                {
                    attributes.SetWrapMode(WrapMode.TileFlipXY);
                    g.DrawImage(image, new Rectangle(0, 0, width, height),
                        0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
                }
            }
            return destImage;
        }

19 Source : DonateBox.cs
with MIT License
from BluePointLilac

private static Image GetSingleQR(int index)
        {
            Bitmap bitmap = new Bitmap(200, 200);
            using(Graphics g = Graphics.FromImage(bitmap))
            {
                Rectangle destRect = new Rectangle(0, 0, 200, 200);
                Rectangle srcRect = new Rectangle(index * 200, 0, 200, 200);
                g.DrawImage(AllQR, destRect, srcRect, GraphicsUnit.Pixel);
            }
            return bitmap;
        }

19 Source : FormPickColor.cs
with MIT License
from BluePointLilac

private Bitmap SnipScreen() {
            Bitmap bitmap = null;
            try {
                int sLeft = SystemInformation.VirtualScreen.Left;
                int sTop = SystemInformation.VirtualScreen.Top;
                int sWidth = (int)(SystemInformation.VirtualScreen.Width * PrimaryScreen.ScaleX);
                int sHeight = (int)(SystemInformation.VirtualScreen.Height * PrimaryScreen.ScaleY);

                bitmap = new Bitmap(sWidth, sHeight);
                Graphics g = Graphics.FromImage(bitmap);
                g.CopyFromScreen(sLeft, sTop, 0, 0, bitmap.Size);
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
                this.Dispose();
            }
            return bitmap;
        }

19 Source : PartImage.cs
with MIT License
from BluePointLilac

public static Bitmap GetPart(Image image, int pX, int pY, int pW, int pH) {
			Bitmap bitmap = new Bitmap(pW, pH);
			Graphics g = Graphics.FromImage(bitmap);
			Rectangle rectangle = new Rectangle(0, 0, pW, pH);
			Rectangle srcRect = new Rectangle(pX, pY, pW, pH);
			g.DrawImage(image, rectangle, srcRect, GraphicsUnit.Pixel);
			return bitmap;
		}

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 : DrawingArea.cs
with GNU General Public License v3.0
from boonkerz

public void Draw(Image image, Rectangle region)
        {
            if (Screen.Width * Screen.Height < region.Width * region.Height)
            {
                Screen = new Bitmap(region.Width, region.Height);
            }

            var gfx = Graphics.FromImage(Screen);
            gfx.DrawImageUnscaled(image, region);

            this.Invalidate();
        }

See More Examples