FromImage() public static method

public static FromImage ( Image image ) : Graphics
image Image
return Graphics
Example #1
3
        /// <summary>
        /// Set the size of the back buffer to the size of the control
        /// </summary>
        private void InitBuffer()
        {
            Graphics = this.CreateGraphics();

            Rectangle disp = RealRectangle;
            BackBuffer = new Bitmap(disp.Width > 0 ? disp.Width : 1, disp.Height > 0 ? disp.Height : 1);
            BufferGraphics = Graphics.FromImage(BackBuffer);
            BufferGraphics.TextRenderingHint = Graphics.TextRenderingHint;
        }
Example #2
0
        private void Initialize(int width, int height)
        {
            if (width == _BI.biHeader.bihWidth && height == -_BI.biHeader.bihHeight)
                return;
            
            lock (LockObj)
            {
                if (_GFX != null) _GFX.Dispose();
                if (_DIB != null) _DIB.Dispose();

                _DIB = new BitmapSurface(width, height);
                _GFX = GDIGraphics.FromImage(_DIB.BmpSource);
                _GFX.CompositingQuality = _gfxcompq;
                _GFX.CompositingMode = _gfxcompm;
                _GFX.SmoothingMode = _gfxsmoth;
                _DIB.DrawQuality = _dibdmode;

                _BI  = new BITMAPINFO {
				    biHeader = {
					    bihBitCount = 32,
					    bihPlanes   = 1,
					    bihSize     = 40,
					    bihWidth    = +width,
					    bihHeight   = -height,
                        bihSizeImage = (width * height) << 2
				    }
			    };
            }
        }
Example #3
0
        private void ResizeWithSystemDrawing(string filePath, string resizedFilePath, int size)
        {
            var image = DrawingImage.FromFile(filePath);

            var destRect  = new DrawingRectangle(0, 0, size, size);
            var destImage = new DrawingBitmap(size, size);

            destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            using (var graphics = DrawingGraphics.FromImage(destImage))
            {
                graphics.CompositingMode    = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode      = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;

                using (var wrapMode = new ImageAttributes())
                {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                    graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }

            destImage.Save(resizedFilePath);
        }
Example #4
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Forms.Control.SizeChanged" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> that contains the event data.</param>
        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);

            try
            {
                if (_bitmap == null)
                {
                    return;
                }

                _formGraphics.Dispose();
                _graphics.Dispose();
                _bitmap.Dispose();
                _bitmap   = null;
                _graphics = null;

                _formGraphics = panelGraphics.CreateGraphics();
                _bitmap       = new Bitmap(panelGraphics.ClientSize.Width, panelGraphics.ClientSize.Height, _formGraphics);
                _graphics     = DrawingGraphics.FromImage(_bitmap);
                _graphics.Clear(Color.Black);
            }
            catch (Exception ex)
            {
                ex.Catch(_ => GorgonDialogs.ErrorBox(this, _), GorgonApplication.Log);
            }
        }
Example #5
0
 public Bitmap GetTilset()
 {
     if (_tileset == null)
     {
         return(null);
     }
     using (var gr = Graphics.FromImage(_tileset))
     {
         for (int i = 0; i <= _tileset.Width; i += H)
         {
             if (i == _tileset.Width)
             {
                 i--;
             }
             gr.DrawLine(new Pen(GDIColor.Silver), i, 0, i, _tileset.Height);
         }
         for (int i = 0; i <= _tileset.Height; i += H)
         {
             if (i == _tileset.Height)
             {
                 i--;
             }
             gr.DrawLine(new Pen(GDIColor.Silver), 0, i, _tileset.Width, i);
         }
         int x   = _activeTile1.X * H;
         int y   = _activeTile1.Y * H;
         int w   = (_activeTile2.X - _activeTile1.X + 1) * H;
         int h   = (_activeTile2.Y - _activeTile1.Y + 1) * H;
         var pen = new Pen(GDIColor.Red);
         gr.DrawRectangle(pen, x, y, w, h);
     }
     return(_tileset);
 }
Example #6
0
        /// <summary>
        /// Create new buffer. Sizes are in pixels
        /// </summary>
        /// <param name="gc"></param>
        /// <param name="sizeX"></param>
        /// <param name="sizeY"></param>
        public bool CreateBuffer(int width, int height)
        {
            if ((width != this.width) || (height != this.height))
            {
                // if size of buffer is changed

                this.height = height;
                this.width  = width;

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

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

                if (width == 0 || height == 0)
                {
                    return(false);
                }

                buffer   = new Bitmap(width, height);
                graphics = Graphics.FromImage(buffer);
            }
            return(true);
        }
Example #7
0
        public BitmapTextureSource Write(string s, float size, Color fg)
        {
            Bitmap       tmp = new Bitmap(1, 1);
            StringFormat fmt = new StringFormat()
            {
                Alignment     = StringAlignment.Center,
                LineAlignment = StringAlignment.Center
            };

            GDIGraphics tmpG = GDIGraphics.FromImage(tmp);
            Font        fnt  = new Font(familyName, size);
            SizeF       si   = tmpG.MeasureString(s, fnt);

            tmpG.Dispose();
            tmp.Dispose();

            Bitmap bmp = new Bitmap((int)si.Width, (int)si.Height);

            bmp.MakeTransparent();

            tmpG = GDIGraphics.FromImage(bmp);
            tmpG.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
            tmpG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            tmpG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

            tmpG.DrawString(s, fnt, new SolidBrush(fg), 0, 0);
            tmpG.Flush();
            tmpG.Dispose();

            var t = new BitmapTextureSource(bmp, 0);

            bmp.Dispose();
            return(t);
        }
Example #8
0
        /// <summary>
        /// Takes a screenshot associated with the given handle (be it a window or control) and return it
        /// as a System.Drawing.Bitmap.
        /// This function uses the BitBlt Windows API to take the screenshot.
        /// </summary>
        /// <param name="handle"></param>
        public static Bitmap GetScreenshotByHandle(IntPtr handle)
        {
            var g              = default(GraphicsFx);
            var hdcDest        = IntPtr.Zero;
            var windowHandleDC = IntPtr.Zero;

            var windowRect = default(RECT);
            var bmp        = default(Bitmap);

            if (GetWindowRect(handle, out windowRect))
            {
                bmp = new Bitmap(windowRect.Right - windowRect.Left, windowRect.Bottom - windowRect.Top);
            }
            else
            {
                return(null);
            }

            g = GraphicsFx.FromImage(bmp);
            windowHandleDC = (IntPtr)GetWindowDC(handle);
            hdcDest        = g.GetHdc();
            BitBlt(hdcDest, 0, 0, bmp.Width, bmp.Height, windowHandleDC, 0, 0, SRCCOPY);

            g.ReleaseHdc(hdcDest);
            ReleaseDC(handle, windowHandleDC);

            g.Dispose();
            g = null;

            return(bmp);
        }
Example #9
0
        /// <summary>
        /// Takes a screenshot of the specified location and returns it as a System.Drawing.Bitmap.
        /// This function uses the BitBlt Windows API to take the screenshot.
        /// </summary>
        /// <param name="rectLoc"></param>
        public static Bitmap GetScreenshotByLocation(Rectangle rectLoc)
        {
            var g              = default(GraphicsFx);
            var hdcDest        = IntPtr.Zero;
            var windowHandleDC = IntPtr.Zero;

            var windowRect = default(RECT);

            windowRect.Left   = rectLoc.Left;
            windowRect.Right  = rectLoc.Right;
            windowRect.Top    = rectLoc.Top;
            windowRect.Bottom = rectLoc.Bottom;

            var bmp = new Bitmap(windowRect.Right - windowRect.Left, windowRect.Bottom - windowRect.Top);

            g = GraphicsFx.FromImage(bmp);
            windowHandleDC = GetDesktopWindow();
            hdcDest        = g.GetHdc();
            BitBlt(hdcDest, 0, 0, bmp.Width, bmp.Height, windowHandleDC, windowRect.Left, windowRect.Top, SRCCOPY);

            g.ReleaseHdc(hdcDest);
            ReleaseDC(GetDesktopWindow(), windowHandleDC);

            g.Dispose();
            g = null;

            return(bmp);
        }
        /// <summary>
        /// Downscales <param name="original"/> to <see cref="kImageSize"/>
        /// </summary>
        protected static Stream DownscaleImage(Stream original)
        {
            try
            {
                Image originalImage = Image.FromStream(original);

                if (originalImage.Width <= kImageSize && originalImage.Height <= kImageSize)
                {
                    return(original);
                }

                var resizedRect  = new Rectangle(0, 0, kImageSize, kImageSize);
                var resizedImage = new Bitmap(kImageSize, kImageSize);

                resizedImage.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);

                using (var graphics = Graphics.FromImage(resizedImage))
                {
                    using var wrapMode = new ImageAttributes();
                    wrapMode.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY);
                    graphics.DrawImage(originalImage, resizedRect, 0, 0, originalImage.Width, originalImage.Height, GraphicsUnit.Pixel, wrapMode);
                }

                MemoryStream ms = new MemoryStream();
                resizedImage.Save(ms, ImageFormat.Png);
                return(ms);
            }
            catch (Exception)
            {
                return(original);
            }
        }
Example #11
0
        /// <summary>
        /// Handles the Resize event of the surfaceControl control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        private void surfaceControl_Resize(object sender, EventArgs e)
        {
            System.Windows.Forms.Form parentForm = _control.FindForm();

            if ((parentForm == null) || (parentForm.WindowState == FormWindowState.Minimized))
            {
                return;
            }

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

            // Copy the old image into the new buffer.
            Image tempImage = new Bitmap(_control.ClientSize.Width, _control.ClientSize.Height, _drawing.PixelFormat);

            _imageGraphics = DrawingGraphics.FromImage(tempImage);
            if (_drawing != null)
            {
                _imageGraphics.DrawImage(_drawing, Point.Empty);

                _drawing.Dispose();
            }
            _drawing = tempImage;

            GetResources(false);
        }
Example #12
0
    public static Bitmap ResizeImage(Image image, int width, int height)
    {
        var destRect  = new Rectangle(0, 0, width, height);
        var destImage = new Bitmap(width, height);

        destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

        using (var graphics = Graphics.FromImage(destImage))
        {
            graphics.CompositingMode    = CompositingMode.SourceCopy;
            graphics.CompositingQuality = CompositingQuality.HighQuality;
            graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode      = SmoothingMode.HighQuality;
            graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;

            using (var wrapMode = new ImageAttributes())
            {
                wrapMode.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY);
                graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
            }
        }

        image.Dispose();

        return(destImage);
    }
Example #13
0
        public static Bitmap Resize(this Bitmap input, int width, int height, bool autoDispose = false)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
            if (width <= 0)
            {
                throw new ArgumentException("must be greater than 0", "width");
            }
            if (height <= 0)
            {
                throw new ArgumentException("must be greater than 0", "height");
            }

            Bitmap resizedBitmap = new Bitmap(width, height);

            using (GDIGraphics g = GDIGraphics.FromImage(resizedBitmap))
            {
                g.SmoothingMode      = SmoothingMode.HighQuality;
                g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.DrawImage(input, 0, 0, width, height);
            }

            if (autoDispose)
            {
                input.Dispose();
            }

            return(resizedBitmap);
        }
        public static Graphics CreateGraphics(Bitmap bitmap)
        {
            Graphics g = Graphics.FromImage(bitmap);

            g.InterpolationMode = InterpolationMode.NearestNeighbor;
            return(g);
        }
Example #15
0
    public Texture2D LoadUnitySprite(AssetsManager manager, AssetTypeValueField baseField, AssetsFileInstance spriteFileInst)
    {
        AssetTypeValueField m_RD        = baseField.Get("m_RD");
        AssetTypeValueField texture     = m_RD.Get("texture");
        AssetTypeValueField textureRect = m_RD.Get("textureRect");
        int  texFileId = texture.Get("m_FileID").GetValue().AsInt();
        long texPathId = texture.Get("m_PathID").GetValue().AsInt64();
        AssetTypeValueField textureBaseField = manager.GetExtAsset(spriteFileInst, texture).instance.GetBaseField();
        int x      = (int)Mathf.Floor(textureRect.Get("x").GetValue().AsFloat());
        int y      = (int)Mathf.Floor(textureRect.Get("y").GetValue().AsFloat());
        int width  = (int)Mathf.Ceil(textureRect.Get("width").GetValue().AsFloat());
        int height = (int)Mathf.Ceil(textureRect.Get("height").GetValue().AsFloat());

        Bitmap bitmap = GetBitmap(manager, textureBaseField, texFileId, texPathId, spriteFileInst);

        List <Point> points = GetUnityPoints(baseField, bitmap.Height);

        //because the section we are selecting has to be at 0,
        //we move the sprite from the bottom to the top
        for (int i = 0; i < points.Count; i++)
        {
            points[i] = new Point(points[i].X, points[i].Y - (bitmap.Height - height));
        }
        AssetTypeValueField m_IndexBuffer = m_RD.Get("m_IndexBuffer").Get("Array");

        GraphicsPath gp = new GraphicsPath();

        for (uint i = 0; i < m_IndexBuffer.GetValue().AsArray().size; i += 6)
        {
            int     pointA   = (int)(m_IndexBuffer[i + 0].GetValue().AsUInt() | (m_IndexBuffer[i + 1].GetValue().AsUInt() << 8));
            int     pointB   = (int)(m_IndexBuffer[i + 2].GetValue().AsUInt() | (m_IndexBuffer[i + 3].GetValue().AsUInt() << 8));
            int     pointC   = (int)(m_IndexBuffer[i + 4].GetValue().AsUInt() | (m_IndexBuffer[i + 5].GetValue().AsUInt() << 8));
            Point[] triangle = new Point[] { points[pointA], points[pointB], points[pointC] };
            gp.AddPolygon(triangle);
        }

        //todo, handle all this in unity (needs algo for clipping in poly)
        Bitmap croppedBitmap = new Bitmap(width, height);

        using (Graphics graphics = Graphics.FromImage(croppedBitmap))
        {
            graphics.Clip = new Region(gp);
            graphics.DrawImage(bitmap, -x, -(bitmap.Height - (y + height)));
        }
        //o nose
        croppedBitmap = ResizeImage(croppedBitmap, (int)(croppedBitmap.Width * 1.5625f), (int)(croppedBitmap.Height * 1.5625f));
        //bitmap.Dispose();
        //this is terribly inefficent please o please fix
        Texture2D image = new Texture2D(width, height);

        using (MemoryStream stream = new MemoryStream())
        {
            croppedBitmap.Save(stream, croppedBitmap.RawFormat);
            image.LoadImage(stream.ToArray());
        }
        return(image);
    }
Example #16
0
 private void UpdateScreenBitmap()
 {
     using (Graphics g = Graphics.FromImage(screenBitmap))
     {
         g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
         g.DrawImage(internalBitmap, 0, 0, screenBitmap.Width, screenBitmap.Height);
     }
     picScreen.Image = screenBitmap;
 }
Example #17
0
        /// <summary>
        /// Function to create the double buffer surface resources.
        /// </summary>
        /// <param name="displayControl">The control that will be used as the display.</param>
        private void CreateDoubleBufferSurface(Control displayControl)
        {
            _graphics = DrawingGraphics.FromHwnd(displayControl.Handle);

            _mouseImage    = new Bitmap(displayControl.ClientSize.Width, displayControl.ClientSize.Height, PixelFormat.Format32bppArgb);
            _imageGraphics = DrawingGraphics.FromImage(_mouseImage);

            _graphicsContext = BufferedGraphicsManager.Current;
            _buffer          = _graphicsContext.Allocate(_imageGraphics, new Rectangle(0, 0, _mouseImage.Width, _mouseImage.Height));
        }
Example #18
0
        public DrawHandler(int canvasWidth, int canvasHeight, int fontSize)
        {
            this.canvasWidth  = canvasWidth;
            this.canvasHeight = canvasHeight;
            this.fontSize     = fontSize;

            timerFont    = new System.Drawing.Font(System.Drawing.FontFamily.GenericSansSerif, this.fontSize, System.Drawing.FontStyle.Bold);
            timerBrush   = new SolidBrush(System.Drawing.Color.White);
            offScreenBmp = new Bitmap(this.canvasWidth, this.canvasHeight);
            offScreenDC  = SystemGraphics.FromImage(this.offScreenBmp);
            backBrush    = new SolidBrush(System.Drawing.Color.Black);
        }
Example #19
0
        public static Bitmap GetBitmap(Font font, string text)
        {
            Graphic graphic = Graphic.FromImage(new Bitmap(1, 1));
            SizeF   size    = graphic.MeasureString(text, font);
            Bitmap  bitmap  = new Bitmap((int)size.Width + 1, (int)size.Height + 1);
            Brush   brush   = new SolidBrush(ColorS.White);

            graphic = Graphic.FromImage(bitmap);
            graphic.DrawString(text, font, brush, 0, 0);
            graphic.Dispose();
            return(bitmap);
        }
Example #20
0
        public static Bitmap Copy([NotNull] this Image image)
        {
            int width = image.Width, height = image.Height;
            var output = new Bitmap(width, height, image.PixelFormat);

            using (var g = G.FromImage(output))
            {
                g.InterpolationMode = InterpolationMode.NearestNeighbor;
                g.DrawImage(image, 0, 0, width, height);
            }
            return(output);
        }
Example #21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Spray" /> class.
        /// </summary>
        /// <param name="size">Size of the drawing surface.</param>
        public Spray(Size size)
        {
            Surface   = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppArgb);
            _graphics = DrawingGraphics.FromImage(Surface);

            _brushes = new SolidBrush[64];

            for (int i = 0; i < _brushes.Length; ++i)
            {
                _brushes[i] = new SolidBrush(Color.FromArgb(GorgonRandom.RandomInt32(0, 255), GorgonRandom.RandomInt32(0, 255), GorgonRandom.RandomInt32(0, 255)));
            }
        }
Example #22
0
        public static Bitmap TakeScreenshot(Rectangle rectangle, PixelFormat format, [CanBeNull] Bitmap reusable = null)
        {
            var bounds = rectangle;

            if (reusable == null || reusable.PixelFormat != format || reusable.Size != bounds.Size)
            {
                reusable = new Bitmap(bounds.Width, bounds.Height, format);
            }
            using (var g = G.FromImage(reusable))
                g.CopyFromScreen(bounds.X, bounds.Y, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy);
            return(reusable);
        }
Example #23
0
        private void InitialiseBitmap()
        {
            internalBitmap = new Bitmap(64, 32);
            using (Graphics g = Graphics.FromImage(internalBitmap))
            {
                g.Clear(Color.Black);
            }

            screenBitmap = new Bitmap(picScreen.ClientSize.Width, picScreen.ClientSize.Height);
            UpdateScreenBitmap();
            picScreen.Image = screenBitmap;
        }
Example #24
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="SelectTemplateDialog" /> class.
        /// </summary>
        // ReSharper disable once NotNullMemberIsNotInitialized
        public SelectTemplateDialog()
        {
            InitializeComponent();

            int index = 0;

            foreach (Tuple <Template, IImage> tuple in TemplateManager.Templates)
            {
                Image image;
                using (Stream stream = tuple.Item2.GetStream())
                {
                    image = Image.FromStream(stream);
                    if (image.Size != _thumbnailList.ImageSize)
                    {
                        Vector2 scale    = _thumbnailList.ImageSize.ToVector2() / image.Size.ToVector2();
                        float   minScale = Math.Min(scale.X, scale.Y);
                        Vector2 size     = minScale * image.Size.ToVector2();
                        Vector2 pos      = (_thumbnailList.ImageSize.ToVector2() - size) / 2;

                        Bitmap bit = new Bitmap(
                            _thumbnailList.ImageSize.Width,
                            _thumbnailList.ImageSize.Height,
                            PixelFormat.Format32bppArgb);

                        using (GdiPGraphics g = GdiPGraphics.FromImage(bit))
                        {
                            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            g.SmoothingMode     = SmoothingMode.AntiAlias;
                            g.PixelOffsetMode   = PixelOffsetMode.HighQuality;

                            g.DrawImage(image, pos.X, pos.Y, size.X, size.Y);
                        }
                        image.Dispose();
                        image = bit;
                    }
                }

                _thumbnailList.Images.Add(image);

                // TODO Just temporary. need to add a name to Template
                ShapeTemplate shapeTemplate = tuple.Item1.ShapeTemplates.First().Value;
                string        name          = shapeTemplate.Name;
                int           sideCount     = shapeTemplate.VertexNames.Count;

                ListViewItem item = new ListViewItem(name, index++, GetGroup(sideCount))
                {
                    Tag = tuple.Item1
                };

                _templateList.Items.Add(item);
            }
        }
Example #25
0
            public void ClipByCanvas(int width, int height, bool clipSubLayers)
            {
                var canvasRectangle  = new Rectangle(0, 0, width, height);
                var clippedRectangle = Rectangle.Intersect(canvasRectangle, Rectangle);

                if (Rectangle != clippedRectangle)
                {
                    if (clippedRectangle.Width > 0 && clippedRectangle.Height > 0)
                    {
                        if (Bitmap != null)
                        {
                            var sourceRectangle = new Rectangle(clippedRectangle.X - Rectangle.X,
                                                                clippedRectangle.Y - Rectangle.Y,
                                                                clippedRectangle.Width,
                                                                clippedRectangle.Height);

                            var trimmedRectangle = this.Bitmap.GetTrimmedRect(sourceRectangle);

                            clippedRectangle.X     += trimmedRectangle.X - sourceRectangle.X;
                            clippedRectangle.Y     += trimmedRectangle.Y - sourceRectangle.Y;
                            clippedRectangle.Width  = trimmedRectangle.Width;
                            clippedRectangle.Height = trimmedRectangle.Height;

                            var newBitmap = new Bitmap(clippedRectangle.Width, clippedRectangle.Height);
                            using (var g = GDIGraphics.FromImage(newBitmap))
                            {
                                g.DrawImage(Bitmap,
                                            new Rectangle(0, 0, newBitmap.Width, newBitmap.Height),
                                            trimmedRectangle,
                                            GraphicsUnit.Pixel);
                            }

                            this.Bitmap.Dispose();
                            this.Bitmap = newBitmap;
                        }
                    }
                    else
                    {
                        Bitmap = null;
                    }

                    Rectangle = clippedRectangle;
                }

                if (clipSubLayers)
                {
                    foreach (var item in SubLayers)
                    {
                        item.ClipByCanvas(width, height, true);
                    }
                }
            }
Example #26
0
 public static void ResizeIcon(string imageFile, string outputFile, int width, int height)
 {
     using (var srcImage = Image.FromFile(imageFile)) {
         using (var newImage = new Bitmap(width, height))
             using (var graphics = Graphics.FromImage(newImage)) {
                 graphics.SmoothingMode     = SmoothingMode.HighQuality;
                 graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
                 graphics.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                 graphics.DrawImage(srcImage, new Rectangle(0, 0, width, height));
                 newImage.Save(outputFile);
             }
     }
 }
Example #27
0
        static byte[] Resize(byte[] bytes, int size)
        {
            Image    img      = (Bitmap)(new ImageConverter().ConvertFrom(bytes));
            Bitmap   cutPiece = new Bitmap(size, size);
            Graphics graphic  = Graphics.FromImage(cutPiece);

            graphic.DrawImage(img, new Rectangle(0, 0, size, size), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
            graphic.Dispose();
            MemoryStream ms = new MemoryStream();

            cutPiece.Save(ms, ImageFormat.Jpeg);
            return(ms.ToArray());
        }
Example #28
0
        public void createBuffer()
        {
            if (this.bufer != null)
            {
                this.bufer.Dispose();
            }
            if (this.buferGraphics != null)
            {
                this.buferGraphics.Dispose();
            }

            this.bufer         = new Bitmap(this.settings.buferSize, this.settings.buferSize);
            this.buferGraphics = Graphics.FromImage(this.bufer);
        }
Example #29
0
 public static void Overlay(string imageFile, string overlayImgFile, string saveFile)
 {
     using (var overlayImage = Image.FromFile(overlayImgFile))
         using (var srcImage = Image.FromFile(imageFile)) {
             using (var newImage = new Bitmap(srcImage.Width, srcImage.Height))
                 using (var graphics = Graphics.FromImage(newImage)) {
                     graphics.SmoothingMode     = SmoothingMode.HighQuality;
                     graphics.InterpolationMode = InterpolationMode.HighQualityBilinear;
                     graphics.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                     var rect = new Rectangle(0, 0, srcImage.Width, srcImage.Height);
                     graphics.DrawImage(srcImage, rect);
                     graphics.DrawImage(overlayImage, rect);
                     newImage.Save(saveFile);
                 }
         }
 }
Example #30
0
        /// <summary>
        /// Scales a given image
        /// </summary>
        private static Image ScaleImage(Image image, int maxWidth, int maxHeight)
        {
            var ratioX = (double)maxWidth / image.Width;
            var ratioY = (double)maxHeight / image.Height;
            var ratio  = Math.Min(ratioX, ratioY);

            var newWidth  = (int)(image.Width * ratio);
            var newHeight = (int)(image.Height * ratio);

            var newImage = new Bitmap(newWidth, newHeight);

            using (var graphics = Graphics.FromImage(newImage))
                graphics.DrawImage(image, 0, 0, newWidth, newHeight);

            return(newImage);
        }
Example #31
0
        //private Size MeasureString(string text)
        //{
        //    if (text == string.Empty)
        //        return Size.Empty;

        //    Size size = new Size();
        //    float top = 0, bottom = 0;

        //    for (int i = 0; i < text.Length; i++)
        //    {
        //        char c = text[i];

        //        uint index = face.GetCharIndex(c);

        //        face.LoadGlyph(index, LoadFlags.Default, LoadTarget.Normal);

        //        size.Width += (float)face.Glyph.Advance.X;

        //        if (face.HasKerning && i < text.Length - 1)
        //        {
        //            char cc = text[i + 1];
        //            size.Width += (float)face.GetKerning(index, face.GetCharIndex(cc), KerningMode.Default).X;
        //        }

        //        float top_ = (float)face.Glyph.Metrics.HorizontalBearingY;
        //        float bottom_ = (float)(face.Glyph.Metrics.Height - face.Glyph.Metrics.HorizontalBearingY);

        //        if (top_ > top)
        //            top = top_;

        //        if (bottom_ > bottom)
        //            bottom = bottom_;
        //    }

        //    size.Height = top + bottom;

        //    return size;
        //}

        //private void AddCharacter(uint c)
        //{
        //    if (c == (uint)'\t')
        //    {
        //        GlyphInfo space = GetGlyph((uint)' ');
        //        glyphs.Add(c, new GlyphInfo(space.AdvanceX * 5, space.AdvanceY, space.CharIndex));
        //        return;
        //    }

        //    uint index = face.GetCharIndex(c);
        //    if (index == 0)
        //        throw new Exception("undefined char code");

        //    face.LoadGlyph(index, LoadFlags.Default, LoadTarget.Normal);
        //    face.Glyph.RenderGlyph(RenderMode.Normal);

        //    if (face.Glyph.Bitmap.Width == 0 && face.Glyph.Bitmap.Rows == 0)
        //    {
        //        glyphs.Add(c, new GlyphInfo(
        //            (int)Math.Ceiling(face.Glyph.Advance.X.ToDecimal()),
        //            (int)Math.Ceiling(face.Glyph.Advance.Y.ToDecimal()),
        //            index));
        //        return;
        //    }

        //    RGBA[] pixels = new RGBA[face.Glyph.Bitmap.Width * face.Glyph.Bitmap.Rows];

        //    byte[] data = face.Glyph.Bitmap.BufferData;
        //    for (int i = 0; i < face.Glyph.Bitmap.Width * face.Glyph.Bitmap.Rows; i++)
        //    {
        //        pixels[i] = new RGBA(255, 255, 255, data[i]);
        //    }

        //    Rectangle r = new Rectangle(0, 0, face.Glyph.Bitmap.Width, face.Glyph.Bitmap.Rows);
        //    Texture2D tex = new Texture2D(TextureConfiguration.Linear, r.Width, r.Height);
        //    tex.SetData(pixels, r);

        //    GlyphInfo info = new GlyphInfo(tex, r,
        //        face.Glyph.Advance.X.Ceiling(),
        //        face.Glyph.Advance.Y.Ceiling(),
        //        face.Glyph.BitmapLeft, face.Glyph.BitmapTop);

        //    glyphs.Add(c, info);
        //}

        private void AddCharacter(char c)
        {
            if (c == '\t')
            {
                GlyphInfo space = GetGlyph(' ');
                glyphs.Add(c, new GlyphInfo(space.AdvanceX + 5, space.AdvanceY));

                return;
            }

            Gfx g = Gfx.FromImage(buffer);

            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.High;
            g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            g.DrawString(c.ToString(), font, brush, 0, 0);

            SizeF size = g.MeasureString(c.ToString(), font);

            Rectangle r = new Rectangle(0, 0, (int)Math.Ceiling(size.Width), (int)Math.Ceiling(size.Height));

            RGBA[] pixels = new RGBA[r.Width * r.Height];

            int q = 0;

            for (int x = 0; x < r.Width; x++)
            {
                for (int y = 0; y < r.Height; y++)
                {
                    var color = buffer.GetPixel(x, y);
                    pixels[q++] = new RGBA(255, 255, 255, color.A);
                }
            }


            Texture2D tex = new Texture2D(TextureConfiguration.Linear, r.Width, r.Height);

            tex.SetData(pixels, null);

            GlyphInfo info = new GlyphInfo(tex, r, r.Width, 0, 0, 0);

            glyphs.Add(c, info);

            g.Clear(Color.Transparent);

            g.Dispose();
        }