// PaintPrivate is used in three places that need to duplicate the paint code:
        // 1. DataGridViewCell::Paint method
        // 2. DataGridViewCell::GetContentBounds
        // 3. DataGridViewCell::GetErrorIconBounds
        //
        // if computeContentBounds is true then PaintPrivate returns the contentBounds
        // else if computeErrorIconBounds is true then PaintPrivate returns the errorIconBounds
        // else it returns Rectangle.Empty;
        private Rectangle PaintPrivate(Graphics g,
                                       Rectangle clipBounds,
                                       Rectangle cellBounds,
                                       int rowIndex,
                                       DataGridViewElementStates elementState,
                                       object formattedValue,
                                       string errorText,
                                       DataGridViewCellStyle cellStyle,
                                       DataGridViewAdvancedBorderStyle advancedBorderStyle,
                                       DataGridViewPaintParts paintParts,
                                       bool computeContentBounds,
                                       bool computeErrorIconBounds,
                                       bool paint)
        {
            // Parameter checking.
            // One bit and one bit only should be turned on
            Debug.Assert(paint || computeContentBounds || computeErrorIconBounds);
            Debug.Assert(!paint || !computeContentBounds || !computeErrorIconBounds);
            Debug.Assert(!computeContentBounds || !computeErrorIconBounds || !paint);
            Debug.Assert(!computeErrorIconBounds || !paint || !computeContentBounds);
            Debug.Assert(cellStyle != null);

            if (paint && DataGridViewCell.PaintBorder(paintParts))
            {
                PaintBorder(g, clipBounds, cellBounds, cellStyle, advancedBorderStyle);
            }

            Rectangle resultBounds;
            Rectangle valBounds    = cellBounds;
            Rectangle borderWidths = BorderWidths(advancedBorderStyle);

            valBounds.Offset(borderWidths.X, borderWidths.Y);
            valBounds.Width  -= borderWidths.Right;
            valBounds.Height -= borderWidths.Bottom;

            if (valBounds.Width > 0 && valBounds.Height > 0 && (paint || computeContentBounds))
            {
                Rectangle imgBounds = valBounds;
                if (cellStyle.Padding != Padding.Empty)
                {
                    if (this.DataGridView.RightToLeftInternal)
                    {
                        imgBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top);
                    }
                    else
                    {
                        imgBounds.Offset(cellStyle.Padding.Left, cellStyle.Padding.Top);
                    }
                    imgBounds.Width  -= cellStyle.Padding.Horizontal;
                    imgBounds.Height -= cellStyle.Padding.Vertical;
                }

                bool       cellSelected = (elementState & DataGridViewElementStates.Selected) != 0;
                SolidBrush br           = this.DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor);

                if (imgBounds.Width > 0 && imgBounds.Height > 0)
                {
                    Image img = formattedValue as Image;
                    Icon  ico = null;
                    if (img == null)
                    {
                        ico = formattedValue as Icon;
                    }
                    if (ico != null || img != null)
                    {
                        DataGridViewImageCellLayout imageLayout = this.ImageLayout;
                        if (imageLayout == DataGridViewImageCellLayout.NotSet)
                        {
                            if (this.OwningColumn is DataGridViewImageColumn)
                            {
                                imageLayout = ((DataGridViewImageColumn)this.OwningColumn).ImageLayout;
                                Debug.Assert(imageLayout != DataGridViewImageCellLayout.NotSet);
                            }
                            else
                            {
                                imageLayout = DataGridViewImageCellLayout.Normal;
                            }
                        }

                        if (imageLayout == DataGridViewImageCellLayout.Stretch)
                        {
                            if (paint)
                            {
                                if (DataGridViewCell.PaintBackground(paintParts))
                                {
                                    DataGridViewCell.PaintPadding(g, valBounds, cellStyle, br, this.DataGridView.RightToLeftInternal);
                                }
                                if (DataGridViewCell.PaintContentForeground(paintParts))
                                {
                                    if (img != null)
                                    {
                                        // bug 21949: Graphics.DrawImage does not treat well scaled images
                                        // we have to pass an ImageAttribute
                                        ImageAttributes attr = new ImageAttributes();

                                        attr.SetWrapMode(WrapMode.TileFlipXY);
                                        g.DrawImage(img, imgBounds, 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, attr);
                                        attr.Dispose();
                                    }
                                    else
                                    {
                                        g.DrawIcon(ico, imgBounds);
                                    }
                                }
                            }

                            resultBounds = imgBounds;
                        }
                        else
                        {
                            Rectangle imgBounds2 = ImgBounds(imgBounds, (img == null) ? ico.Width : img.Width, (img == null) ? ico.Height : img.Height, imageLayout, cellStyle);
                            resultBounds = imgBounds2;

                            if (paint)
                            {
                                if (DataGridViewCell.PaintBackground(paintParts) && br.Color.A == 255)
                                {
                                    g.FillRectangle(br, valBounds);
                                }
                                if (DataGridViewCell.PaintContentForeground(paintParts))
                                {
                                    //paint the image
                                    Region reg = g.Clip;
                                    g.SetClip(Rectangle.Intersect(Rectangle.Intersect(imgBounds2, imgBounds), Rectangle.Truncate(g.VisibleClipBounds)));
                                    if (img != null)
                                    {
                                        g.DrawImage(img, imgBounds2);
                                    }
                                    else
                                    {
                                        g.DrawIconUnstretched(ico, imgBounds2);
                                    }
                                    g.Clip = reg;
                                }
                            }
                        }
                    }
                    else
                    {
                        if (paint && DataGridViewCell.PaintBackground(paintParts) && br.Color.A == 255)
                        {
                            g.FillRectangle(br, valBounds);
                        }
                        resultBounds = Rectangle.Empty;
                    }
                }
                else
                {
                    if (paint && DataGridViewCell.PaintBackground(paintParts) && br.Color.A == 255)
                    {
                        g.FillRectangle(br, valBounds);
                    }
                    resultBounds = Rectangle.Empty;
                }

                Point ptCurrentCell = this.DataGridView.CurrentCellAddress;
                if (paint &&
                    DataGridViewCell.PaintFocus(paintParts) &&
                    ptCurrentCell.X == this.ColumnIndex &&
                    ptCurrentCell.Y == rowIndex &&
                    this.DataGridView.ShowFocusCues &&
                    this.DataGridView.Focused)
                {
                    // Draw focus rectangle
                    ControlPaint.DrawFocusRectangle(g, valBounds, Color.Empty, br.Color);
                }

                if (this.DataGridView.ShowCellErrors && paint && DataGridViewCell.PaintErrorIcon(paintParts))
                {
                    PaintErrorIcon(g, cellStyle, rowIndex, cellBounds, valBounds, errorText);
                }
            }
            else if (computeErrorIconBounds)
            {
                if (!String.IsNullOrEmpty(errorText))
                {
                    resultBounds = ComputeErrorIconBounds(valBounds);
                }
                else
                {
                    resultBounds = Rectangle.Empty;
                }
            }
            else
            {
                Debug.Assert(valBounds.Height <= 0 || valBounds.Width <= 0);
                resultBounds = Rectangle.Empty;
            }

            return(resultBounds);
        }
        public static void DrawBackgroundImage(
            Graphics G,
            Image BackgroundImage,
            Color BackColor,
            ImageLayout BackgroundImageLayout,
            Rectangle BoundsRect,
            Rectangle ClipRect,
            Point ScrollPoint,
            RightToLeft rightToLeft)
        {
            if (G == null)
            {
                throw new ArgumentNullException("g");
            }
            if (BackgroundImageLayout == ImageLayout.Tile)
            {
                using (TextureBrush brush = new TextureBrush(BackgroundImage, WrapMode.Tile))
                {
                    if (ScrollPoint != Point.Empty)
                    {
                        Matrix transform = brush.Transform;
                        transform.Translate((float)ScrollPoint.X, (float)ScrollPoint.Y);
                        brush.Transform = transform;
                    }
                    G.FillRectangle(brush, ClipRect);
                    return;
                }
            }
            Rectangle rect = CalculateBackgroundImageRectangle(
                BoundsRect,
                BackgroundImage,
                BackgroundImageLayout);

            if ((rightToLeft == RightToLeft.Yes) && (BackgroundImageLayout == ImageLayout.None))
            {
                rect.X += ClipRect.Width - rect.Width;
            }
            using (SolidBrush brush2 = new SolidBrush(BackColor))
            {
                G.FillRectangle(brush2, ClipRect);
            }
            if (!ClipRect.Contains(rect))
            {
                if ((BackgroundImageLayout == ImageLayout.Stretch) || (BackgroundImageLayout == ImageLayout.Zoom))
                {
                    rect.Intersect(ClipRect);

                    G.DrawImage(BackgroundImage, rect);
                }
                else if (BackgroundImageLayout == ImageLayout.None)
                {
                    rect.Offset(ClipRect.Location);
                    Rectangle destRect = rect;
                    destRect.Intersect(ClipRect);
                    Rectangle rectangle3 = new Rectangle(Point.Empty, destRect.Size);
                    G.DrawImage(
                        BackgroundImage,
                        destRect,
                        rectangle3.X,
                        rectangle3.Y,
                        rectangle3.Width,
                        rectangle3.Height,
                        GraphicsUnit.Pixel);
                }
                else
                {
                    Rectangle rectangle4 = rect;
                    rectangle4.Intersect(ClipRect);
                    Rectangle rectangle5 = new Rectangle(
                        new Point(rectangle4.X - rect.X, rectangle4.Y - rect.Y),
                        rectangle4.Size);
                    G.DrawImage(
                        BackgroundImage,
                        rectangle4,
                        rectangle5.X,
                        rectangle5.Y,
                        rectangle5.Width,
                        rectangle5.Height,
                        GraphicsUnit.Pixel);
                }
            }
            else
            {
                ImageAttributes imageAttr = new ImageAttributes();
                imageAttr.SetWrapMode(WrapMode.TileFlipXY);
                G.DrawImage(
                    BackgroundImage,
                    rect,
                    0,
                    0,
                    BackgroundImage.Width,
                    BackgroundImage.Height,
                    GraphicsUnit.Pixel,
                    imageAttr);
                imageAttr.Dispose();
            }
        }
Example #3
0
        protected override void OnPaint(PaintEventArgs e)
        {
            //  RefreshScreen();

            if (mBufferImage == null)
            {
                mBufferImage = new Bitmap(Width, Height);
            }
            Graphics bufferGrf = Graphics.FromImage(mBufferImage);

            Graphics g;


            if (mConfiguration.DoubleBuffered)
            {
                g = bufferGrf;
            }
            else
            {
                g = e.Graphics;
            }

            g.CompositingMode    = CompositingMode.SourceCopy;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
            g.SmoothingMode      = SmoothingMode.HighQuality;
            g.PixelOffsetMode    = PixelOffsetMode.HighQuality;

            // g.SmoothingMode = SmoothingMode.AntiAlias;

            //default
            ColorMatrix colorMatrix = new ColorMatrix(new float[][] {
                new float[] { 1, 0, 0, 0, 0 },                                   // red scaling factor of -1
                new float[] { 0, 1, 0, 0, 0 },                                   // green scaling factor of -1
                new float[] { 0, 0, 1, 0, 0 },                                   // blue scaling factor of -1
                new float[] { 0, 0, 0, 1, 0 },                                   // alpha scaling factor of 1
                new float[] { 0, 0, 0, 0, 1 }
            });                                                                  // three translations of 1;

            if (mScreenImage != null && mConfiguration.normal)
            {
                //Normal
                colorMatrix = new ColorMatrix(new float[][] {
                    new float[] { 1, 0, 0, 0, 0 },                               // red scaling factor of -1
                    new float[] { 0, 1, 0, 0, 0 },                               // green scaling factor of -1
                    new float[] { 0, 0, 1, 0, 0 },                               // blue scaling factor of -1
                    new float[] { 0, 0, 0, 1, 0 },                               // alpha scaling factor of 1
                    new float[] { 0, 0, 0, 0, 1 }
                });                                                              // three translations of 1
            }

            if (mScreenImage != null && mConfiguration.invertColors)
            {
                colorMatrix = new ColorMatrix(new float[][] {
                    new float[] { -1, 0, 0, 0, 0 },
                    new float[] { 0, -1, 0, 0, 0 },
                    new float[] { 0, 0, -1, 0, 0 },
                    new float[] { 0, 0, 0, 1, 0 },
                    new float[] { 1, 1, 1, 0, 1 }
                });
            }

            if (mScreenImage != null && mConfiguration.protanopia)
            {
                //Protanopia
                colorMatrix = new ColorMatrix(new float[][] {
                    new float[] { 0.567f, 0.433f, 0, 0, 0 },
                    new float[] { 0.558f, 0.442f, 0, 0, 0 },
                    new float[] { 0, 0.242f, 0.758f, 0, 0 },
                    new float[] { 0, 0, 0, 1, 0 },
                    new float[] { 0, 0, 0, 0, 1 }
                });
            }
            if (mScreenImage != null && mConfiguration.protanomaly)
            {
                //Protanomaly
                colorMatrix = new ColorMatrix(new float[][] {
                    new float[] { 0.817f, 0.183f, 0, 0, 0 },
                    new float[] { 0.333f, 0.667f, 0, 0, 0 },
                    new float[] { 0, 0.125f, 0.875f, 0, 0 },
                    new float[] { 0, 0, 0, 1, 0 },
                    new float[] { 0, 0, 0, 0, 1 }
                });
            }
            if (mScreenImage != null && mConfiguration.deuteranopia)
            {
                //Deuteranopia
                colorMatrix = new ColorMatrix(new float[][] {
                    new float[] { 0.625f, 0.375f, 0, 0, 0 },
                    new float[] { 0.7f, 0.3f, 0, 0, 0 },
                    new float[] { 0, 0.3f, 0.7f, 0, 0 },
                    new float[] { 0, 0, 0, 1, 0 },
                    new float[] { 0, 0, 0, 0, 1 }
                });
            }
            if (mScreenImage != null && mConfiguration.deuteranomaly)
            {
                //Deuteranomaly
                colorMatrix = new ColorMatrix(new float[][] {
                    new float[] { 0.8f, 0.2f, 0, 0, 0 },
                    new float[] { 0.258f, 0.742f, 0, 0, 0 },
                    new float[] { 0, 0.142f, 0.858f, 0, 0 },
                    new float[] { 0, 0, 0, 1, 0 },
                    new float[] { 0, 0, 0, 0, 1 }
                });
            }
            if (mScreenImage != null && mConfiguration.tritanopia)
            {
                //Tritanopia
                colorMatrix = new ColorMatrix(new float[][] {
                    new float[] { 0.95f, 0.05f, 0, 0, 0 },
                    new float[] { 0, 0.433f, 0.567f, 0, 0 },
                    new float[] { 0, 0.475f, 0.525f, 0, 0 },
                    new float[] { 0, 0, 0, 1, 0 },
                    new float[] { 0, 0, 0, 0, 1 }
                });
            }
            if (mScreenImage != null && mConfiguration.tritanomaly)
            {
                //Tritanomaly
                colorMatrix = new ColorMatrix(new float[][] {
                    new float[] { 0.967f, 0.033f, 0, 0, 0 },
                    new float[] { 0, 0.733f, 0.267f, 0, 0 },
                    new float[] { 0, 0.183f, 0.817f, 0, 0 },
                    new float[] { 0, 0, 0, 1, 0 },
                    new float[] { 0, 0, 0, 0, 1 }
                });
            }
            if (mScreenImage != null && mConfiguration.achromatopsia)
            {
                //Achromatopsia
                colorMatrix = new ColorMatrix(new float[][] {
                    new float[] { 0.299f, 0.587f, 0.114f, 0, 0 },
                    new float[] { 0.299f, 0.587f, 0.114f, 0, 0 },
                    new float[] { 0.299f, 0.587f, 0.114f, 0, 0 },
                    new float[] { 0, 0, 0, 1, 0 },
                    new float[] { 0, 0, 0, 0, 1 }
                });
            }
            if (mScreenImage != null && mConfiguration.achromatomaly)
            {
                //Achromatomaly
                colorMatrix = new ColorMatrix(new float[][] {
                    new float[] { 0.618f, 0.320f, 0.062f, 0, 0 },
                    new float[] { 0.163f, 0.775f, 0.062f, 0, 0 },
                    new float[] { 0.163f, 0.320f, 0.516f, 0, 0 },
                    new float[] { 0, 0, 0, 1, 0 },
                    new float[] { 0, 0, 0, 0, 1 }
                });
            }



            ImageAttributes imageAttributes = new ImageAttributes();

            //???????????????
            imageAttributes.SetWrapMode(WrapMode.TileFlipXY);

            imageAttributes.SetColorMatrix(colorMatrix);
            System.Drawing.Rectangle dest = new System.Drawing.Rectangle(0, 0, Width, Height);
            int w = (int)(Width / mConfiguration.ZoomFactor);
            int h = (int)(Height / mConfiguration.ZoomFactor);
            int x = Left - w / 2 + Width / 2;
            int y = Top - h / 2 + Height / 2;

            g.CompositingMode    = CompositingMode.SourceCopy;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
            g.SmoothingMode      = SmoothingMode.HighQuality;
            g.SmoothingMode      = SmoothingMode.AntiAlias;
            g.PixelOffsetMode    = PixelOffsetMode.HighQuality;

            g.DrawImage(
                mScreenImage,
                dest,
                x, y,
                w, h,
                GraphicsUnit.Pixel,
                imageAttributes);

            Pen pen = new Pen(Color.White, 3);

            pen.Alignment = PenAlignment.Inset;
            e.Graphics.DrawRectangle(pen, dest);


            if (mConfiguration.DoubleBuffered)
            {
                e.Graphics.DrawImage(mBufferImage, 0, 0, Width, Height);
                Pen pen2 = new Pen(Color.DarkKhaki, 3);
                pen2.Alignment = PenAlignment.Inset;
                e.Graphics.DrawRectangle(pen2, dest);
            }
        }
Example #4
0
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="factory">
        /// The the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class containing
        /// the image to process.
        /// </param>
        /// <returns>
        /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public Image ProcessImage(ImageFactory factory)
        {
            Bitmap newImage = null;
            Image  image    = factory.Image;

            try
            {
                Rectangle rectangle = this.DynamicParameter;

                int sourceWidth  = image.Width;
                int sourceHeight = image.Height;

                if (rectangle.X < sourceWidth && rectangle.Y < sourceHeight)
                {
                    if (rectangle.Width > (sourceWidth - rectangle.X))
                    {
                        rectangle.Width = sourceWidth - rectangle.X;
                    }

                    if (rectangle.Height > (sourceHeight - rectangle.Y))
                    {
                        rectangle.Height = sourceHeight - rectangle.Y;
                    }

                    // Dont use an object initializer here.
                    newImage     = new Bitmap(rectangle.Width, rectangle.Height, PixelFormat.Format32bppPArgb);
                    newImage.Tag = image.Tag;

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

                        // An unwanted border appears when using InterpolationMode.HighQualityBicubic to resize the image
                        // as the algorithm appears to be pulling averaging detail from surrounding pixels beyond the edge
                        // of the image. Using the ImageAttributes class to specify that the pixels beyond are simply mirror
                        // images of the pixels within solves this problem.
                        using (ImageAttributes wrapMode = new ImageAttributes())
                        {
                            wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                            graphics.DrawImage(
                                image,
                                new Rectangle(0, 0, rectangle.Width, rectangle.Height),
                                rectangle.X,
                                rectangle.Y,
                                rectangle.Width,
                                rectangle.Height,
                                GraphicsUnit.Pixel,
                                wrapMode);
                        }

                        // Reassign the image.
                        image.Dispose();
                        image = newImage;
                    }
                }
            }
            catch
            {
                if (newImage != null)
                {
                    newImage.Dispose();
                }
            }

            return(image);
        }
        /// <summary>
        /// 创建缩略图
        /// </summary>
        public void CutAvatar(string imgSrc, int x, int y, int width, int height, long quality, string savePath, int t)
        {
            var original = Image.FromFile(imgSrc);
            var img      = new Bitmap(t, t, PixelFormat.Format24bppRgb);

            try
            {
                img.MakeTransparent(img.GetPixel(0, 0));
                img.SetResolution(t, t);
                using (var gr = Graphics.FromImage(img))
                {
                    if (original.RawFormat.Equals(ImageFormat.Jpeg) || original.RawFormat.Equals(ImageFormat.Png) ||
                        original.RawFormat.Equals(ImageFormat.Bmp))
                    {
                        gr.Clear(Color.Transparent);
                    }
                    if (original.RawFormat.Equals(ImageFormat.Gif))
                    {
                        gr.Clear(Color.White);
                    }

                    gr.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                    gr.SmoothingMode      = SmoothingMode.AntiAlias;
                    gr.CompositingQuality = CompositingQuality.HighQuality;
                    gr.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                    gr.TextRenderingHint  = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;

                    using (var attribute = new ImageAttributes())
                    {
                        attribute.SetWrapMode(WrapMode.TileFlipXY);
                        gr.DrawImage(original, new Rectangle(0, 0, t, t), x, y, width, height, GraphicsUnit.Pixel,
                                     attribute);
                    }
                }
                var myImageCodecInfo = GetEncoderInfo("image/jpeg");
                if (original.RawFormat.Equals(ImageFormat.Jpeg))
                {
                    myImageCodecInfo = GetEncoderInfo("image/jpeg");
                }
                else if (original.RawFormat.Equals(ImageFormat.Png))
                {
                    myImageCodecInfo = GetEncoderInfo("image/png");
                }
                else if (original.RawFormat.Equals(ImageFormat.Gif))
                {
                    myImageCodecInfo = GetEncoderInfo("image/gif");
                }
                else if (original.RawFormat.Equals(ImageFormat.Bmp))
                {
                    myImageCodecInfo = GetEncoderInfo("image/bmp");
                }

                var myEncoder           = Encoder.Quality;
                var myEncoderParameters = new EncoderParameters(1);
                var myEncoderParameter  = new EncoderParameter(myEncoder, quality);
                myEncoderParameters.Param[0] = myEncoderParameter;
                img.Save(savePath, myImageCodecInfo, myEncoderParameters);
                original.Dispose();
                img.Dispose();
            }
            catch (Exception ex)
            {
                NBCMSLoggerManager.Error("MediaController:cutAvatar,KeyWord:" + savePath);
                NBCMSLoggerManager.Error(ex.Message);
                NBCMSLoggerManager.Error(ex.Source);
                original.Dispose();
                img.Dispose();
            }
            finally
            {
                original.Dispose();
                img.Dispose();
            }
        }
        /// <summary>
        ///     The resize.
        /// </summary>
        /// <param name="source">
        ///     The source.
        /// </param>
        /// <param name="width">
        ///     The width.
        /// </param>
        /// <param name="height">
        ///     The height.
        /// </param>
        /// <param name="preservePerspective">
        ///     The preserve perspective.
        /// </param>
        /// <param name="keepSquare"></param>
        /// <returns>
        /// </returns>
        public virtual Bitmap Resize(Bitmap source, int?width, int?height, bool preservePerspective, bool keepSquare, Color bgColor)
        {
            int destX      = 0;
            int destY      = 0;
            int destWidth  = width ?? 1;
            int destHeight = height ?? 1;

            int newBitmapWidth  = destWidth;
            int newBitmapHeight = destHeight;

            if (preservePerspective)
            {
                double maxWidth  = width.HasValue ? Convert.ToDouble(width.Value) : 0;
                double maxHeight = height.HasValue ? Convert.ToDouble(height.Value) : 0;

                if (maxWidth > 0 && maxHeight <= 0)
                {
                    maxHeight = (maxWidth / source.Width) * source.Height;
                }
                else if (maxHeight > 0 && maxWidth <= 0)
                {
                    maxWidth = (maxHeight / source.Height) * source.Width;
                }

                double aspectRatio = (double)source.Width / (double)source.Height;
                double boxRatio    = (double)maxWidth / (double)maxHeight;
                double scaleFactor;

                if (boxRatio > aspectRatio)
                {
                    // Use height, since that is the most restrictive dimension of box.
                    scaleFactor = (double)maxHeight / (double)source.Height;
                }
                else
                {
                    scaleFactor = (double)maxWidth / (double)source.Width;
                }

                double doubleDestWidth  = (double)source.Width * scaleFactor;
                double doubleDestHeight = (double)source.Height * scaleFactor;

                if (keepSquare && doubleDestWidth < maxWidth)
                {
                    destX = Convert.ToInt32(Math.Floor(((maxWidth - doubleDestWidth) * .5)));
                }

                if (keepSquare && doubleDestHeight < maxHeight)
                {
                    destY = Convert.ToInt32(Math.Floor(((maxHeight - doubleDestHeight) * .5)));
                }

                newBitmapWidth  = destWidth = Math.Max(Convert.ToInt32(Math.Floor(doubleDestWidth)), 1);
                newBitmapHeight = destHeight = Math.Max(Convert.ToInt32(Math.Floor(doubleDestHeight)), 1);

                if (keepSquare)
                {
                    newBitmapWidth  = Math.Max(Convert.ToInt32(Math.Floor(maxWidth)), 1);
                    newBitmapHeight = Math.Max(Convert.ToInt32(Math.Floor(maxHeight)), 1);
                }
            }
            else
            {
                newBitmapWidth  = Math.Max(destWidth, 1);
                newBitmapHeight = Math.Max(destHeight, 1);
            }

            var bitmap = new Bitmap(newBitmapWidth, newBitmapHeight, PixelFormat.Format24bppRgb);

            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                using (var backgroundBrush = new SolidBrush(bgColor))
                {
                    graphics.FillRectangle(backgroundBrush, new Rectangle(0, 0, newBitmapWidth, newBitmapHeight));
                }

                graphics.CompositingMode    = CompositingMode.SourceOver;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.SmoothingMode      = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;

                using (var imageAttr = new ImageAttributes())
                {
                    imageAttr.SetWrapMode(WrapMode.TileFlipXY);

                    graphics.DrawImage(
                        source,
                        new Rectangle(destX, destY, destWidth, destHeight),
                        0,
                        0,
                        source.Width,
                        source.Height,
                        GraphicsUnit.Pixel,
                        imageAttr);

                    return(bitmap);
                }
            }
        }
Example #7
0
        static void Main(string[] args)
        {
            int    resX       = 512;
            int    resY       = 512;
            string inCatalog  = Directory.GetCurrentDirectory();
            string outCatalog = Directory.GetCurrentDirectory() + "//output";

            foreach (string param in args)
            {
                if (param.StartsWith("-res=") == true)
                {
                    string res = param.Split('=')[1];
                    try
                    {
                        resX = Convert.ToInt32(res.Split('x')[0]);
                        resY = Convert.ToInt32(res.Split('x')[1]);
                    } catch (Exception e)
                    {
                        Console.WriteLine("You typed -res=reXxresY wrong, check if there are something more than numbers and separator x after =");
                        break;
                    }
                }
                else if (param.StartsWith("-inputdir=") == true)
                {
                    inCatalog = param.Split('=')[1];
                    if (!Directory.Exists(inCatalog))
                    {
                        throw new Exception();
                    }
                }
                else if (param.StartsWith("-outputdir=") == true)
                {
                    outCatalog = param.Split('=')[1];
                }
                else
                {
                    Console.WriteLine("parametr : " + param + " is wrong");
                }
            }

            if (!Directory.Exists(outCatalog))
            {
                Directory.CreateDirectory(outCatalog);
            }

            List <string> files = new List <string>(Directory.GetFiles(inCatalog));

            foreach (string file in files)
            {
                bool   freeSpace  = false;
                string tmp        = Path.GetFileName(file);
                int    fileNumber = 1;

                while (freeSpace == false)
                {
                    if (File.Exists(outCatalog + "//" + tmp))
                    {
                        tmp = Path.GetFileNameWithoutExtension(file) + "_" + fileNumber + Path.GetExtension(file);
                        fileNumber++;
                    }
                    else
                    {
                        freeSpace = true;
                    }
                }

                try
                {
                    Image imgPhoto  = Image.FromFile(file);
                    var   destRect  = new Rectangle(0, 0, resX, resY);
                    var   destImage = new Bitmap(resX, resY);

                    destImage.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.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(WrapMode.TileFlipXY);
                            graphics.DrawImage(imgPhoto, destRect, 0, 0, imgPhoto.Width, imgPhoto.Height, GraphicsUnit.Pixel, wrapMode);
                        }
                    }
                    destImage.Save(outCatalog + "//" + tmp);
                }
                catch (Exception e)
                {
                    Console.WriteLine(file + " may not be a graphical file");
                }
            }

            Console.WriteLine("operaction ended, press Enter to continue");
            Console.ReadLine();
        }
Example #8
0
        private Stream GetImageResizedVersion(string filePath, ImageFormat format)
        {
            Bitmap bImageFile = new Bitmap(filePath);
            //using (var myImage = Image.FromFile(filePath))
            //{
            var result = new MemoryStream();

            if (bImageFile.Width < maxImageWidth)
            {
                bImageFile.Save(result, format);
                return(result);
            }

            // calculate dimensions
            var newImageSize = ResizeFit(bImageFile);


            var destRect  = new Rectangle(0, 0, newImageSize.Width, newImageSize.Height);
            var destImage = new Bitmap(newImageSize.Width, newImageSize.Height);

            destImage.SetResolution(bImageFile.HorizontalResolution, bImageFile.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(WrapMode.TileFlipXY);
                    graphics.DrawImage(bImageFile, destRect, 0, 0, bImageFile.Width, bImageFile.Height,
                                       GraphicsUnit.Pixel,
                                       wrapMode);
                }
            }

            using (destImage)
            {
                destImage.Save(result, format);
            }

            bImageFile.Dispose();

            return(result);
            //  }



            //using (var myImage = Image.FromFile(filePath))
            //{

            //    var result = new MemoryStream();
            //    var qualityParamId = Encoder.ColorDepth;
            //    var encoderParameters = new EncoderParameters(1);
            //    encoderParameters.Param[0] = new EncoderParameter(qualityParamId, maxResolution);

            //    var codec = ImageCodecInfo.GetImageDecoders()
            //        .FirstOrDefault(dec => dec.FormatID == format.Guid);

            //    if (myImage.Width < maxImageWidth)
            //    {
            //        myImage.Save(result, codec, encoderParameters);
            //        return result;
            //    }


            //    //calculate dimensions
            //    var newImageSize = ResizeFit(myImage);

            //    using (var thumbnail = myImage.GetThumbnailImage(newImageSize.Width, newImageSize.Height, new Image.GetThumbnailImageAbort(() => false), IntPtr.Zero))
            //    {

            //        thumbnail.Save(result, codec, encoderParameters);

            //        return result;
            //    }
            //}
        }
Example #9
0
        // todo not used, remove?
        //private static Rectangle letterRect(Bitmap source, int hStart, int hEnd)
        //{
        //    int startWhite = -1, endWhite = -1;
        //    for (int j = 0; j < source.Height; j++)
        //    {
        //        for (int i = hStart; i < hEnd; i++)
        //        {
        //            if (startWhite == -1 && source.GetPixel(i, j).R == 255)
        //            {
        //                startWhite = j;
        //            }

        //            if (endWhite == -1 && source.GetPixel(i, (source.Height - j) - 1).R == 255)
        //            {
        //                endWhite = (source.Height - j);
        //            }
        //            if (startWhite != -1 && endWhite != -1)
        //                return new Rectangle(hStart, startWhite, hEnd - hStart, endWhite - startWhite);
        //        }
        //    }


        //    return Rectangle.Empty;
        //}

        public double[] doOCR(out string OCRText, out string dinoName, out string species, out string ownerName, out string tribeName, out Sex sex, string useImageFilePath = "", bool changeForegroundWindow = true)
        {
            string finishedText = "";

            dinoName  = "";
            species   = "";
            ownerName = "";
            tribeName = "";
            sex       = Sex.Unknown;
            double[] finalValues = new double[1] {
                0
            };

            Bitmap screenshotbmp;

            ocrControl.debugPanel.Controls.Clear();
            ocrControl.ClearLists();

            if (System.IO.File.Exists(useImageFilePath))
            {
                screenshotbmp = (Bitmap)Image.FromFile(useImageFilePath);
            }
            else
            {
                // grab screenshot from ark
                screenshotbmp = Win32Stuff.GetSreenshotOfProcess(screenCaptureApplicationName, waitBeforeScreenCapture, true);
            }
            if (screenshotbmp == null)
            {
                OCRText = "Error: no image for OCR. Is ARK running?";
                return(finalValues);
            }

            if (!setResolution(screenshotbmp))
            {
                OCRText = "Error while calibrating: probably game-resolution is not supported by this OCR-configuration.\nThe tested image has a resolution of " + screenshotbmp.Width.ToString() + "×" + screenshotbmp.Height.ToString() + " px.";
                return(finalValues);
            }

            // TODO resize image according to resize-factor. used for large screenshots
            if (ocrConfig.resize != 1 && ocrConfig.resize > 0)
            {
                Bitmap resized = new Bitmap((int)(ocrConfig.resize * ocrConfig.resolutionWidth), (int)(ocrConfig.resize * ocrConfig.resolutionHeight));
                using (var graphics = Graphics.FromImage(resized))
                {
                    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(screenshotbmp, new Rectangle(0, 0, 1920, 1080), 0, 0, screenshotbmp.Width, screenshotbmp.Height, GraphicsUnit.Pixel, wrapMode);
                    }

                    screenshotbmp?.Dispose();
                    screenshotbmp = resized;
                }
            }

            if (enableOutput)
            {
                AddBitmapToDebug(screenshotbmp);
                ocrControl.setScreenshot(screenshotbmp);
            }

            finalValues    = new double[ocrConfig.labelRectangles.Count];
            finalValues[8] = -1; // set imprinting to -1 to mark it as unknown and to set a difference to a creature with 0% imprinting.

            if (changeForegroundWindow)
            {
                Win32Stuff.SetForegroundWindow(Application.OpenForms[0].Handle);
            }


            bool wild = false; // todo: set to true and find out if the creature is wild in the first loop
            int  stI  = -1;

            for (int lbI = 0; lbI < ocrConfig.labelNames.Count; lbI++)
            {
                stI++;
                if (lbI == 8)
                {
                    stI = 8;
                }
                string statName = ocrConfig.labelNames[stI];

                Rectangle rec = ocrConfig.labelRectangles[lbI];

                // wild creatures don't have the xp-bar, all stats are moved one row up
                if (wild && stI < 9)
                {
                    rec.Offset(0, ocrConfig.labelRectangles[0].Top - ocrConfig.labelRectangles[1].Top);
                }

                Bitmap testbmp = SubImage(screenshotbmp, rec.X, rec.Y, rec.Width, rec.Height);
                //AddBitmapToDebug(testbmp);

                string statOCR = "";

                if (statName == "NameSpecies")
                {
                    statOCR = readImage(testbmp, true, false);
                }
                else if (statName == "Level")
                {
                    statOCR = readImage(testbmp, true, true);
                }
                else if (statName == "Tribe" || statName == "Owner")
                {
                    statOCR = readImage(testbmp, true, false);
                }
                else
                {
                    statOCR = readImage(testbmp, true, true); // statvalues are only numbers
                }
                if (statOCR == "" &&
                    (statName == "Health" || statName == "Imprinting" || statName == "Tribe" || statName == "Owner"))
                {
                    if (wild && statName == "Health")
                    {
                        stI--;
                        wild = false;
                    }
                    continue; // these can be missing, it's fine
                }


                lastLetterPositions[statName] = new Point(rec.X + lastLetterPosition(removePixelsUnderThreshold(GetGreyScale(testbmp), whiteThreshold)), rec.Y);

                finishedText += (finishedText.Length == 0 ? "" : "\r\n") + statName + ":\t" + statOCR;

                // parse the OCR String

                Regex r;
                r       = new Regex(@"^[_\/\\]*(.*?)[_\/\\]*$"); // trim. often the background is misinterpreted as underscores or slash/backslash
                statOCR = r.Replace(statOCR, "$1");

                if (statName == "NameSpecies")
                {
                    r = new Regex(@".*?([♂♀])?[_.,-\/\\]*([^♂♀]+?)(?:[\(\[]([^\[\(\]\)]+)[\)\]]$|$)");
                }
                else if (statName == "Owner" || statName == "Tribe")
                {
                    r = new Regex(@"(.*)");
                }
                else if (statName == "Level")
                {
                    r = new Regex(@".*\D(\d+)");
                }
                else
                {
                    r = new Regex(@"(?:[\d.,%\/]*\/)?(\d+[\.,']?\d?)(%)?"); // only the second numbers is interesting after the current weight is not shown anymore

                    //if (onlyNumbers)
                    //r = new Regex(@"((\d*[\.,']?\d?\d?)\/)?(\d*[\.,']?\d?\d?)");
                    //else
                    // r = new Regex(@"([a-zA-Z]*)[:;]((\d*[\.,']?\d?\d?)\/)?(\d*[\.,']?\d?\d?)");
                }

                MatchCollection mc = r.Matches(statOCR);

                if (mc.Count == 0)
                {
                    if (statName == "NameSpecies" || statName == "Owner" || statName == "Tribe")
                    {
                        continue;
                    }
                    if (statName == "Torpor" && false)
                    {
                        // probably it's a wild creature
                        // todo
                    }
                    else
                    {
                        finishedText    += "error reading stat " + statName;
                        finalValues[stI] = 0;
                        continue;
                    }
                }

                if (statName == "NameSpecies" || statName == "Owner" || statName == "Tribe")
                {
                    if (statName == "NameSpecies" && mc[0].Groups.Count > 0)
                    {
                        if (mc[0].Groups[1].Value == "♀")
                        {
                            sex = Sex.Female;
                        }
                        else if (mc[0].Groups[1].Value == "♂")
                        {
                            sex = Sex.Male;
                        }
                        dinoName = mc[0].Groups[2].Value;
                        species  = mc[0].Groups[3].Value;
                        if (species.Length == 0)
                        {
                            species = dinoName;
                        }

                        // remove non-letter chars
                        r       = new Regex("[^a-zA-Z]");
                        species = r.Replace(species, "");
                        // replace capital I with lower l (common misrecognition)
                        r       = new Regex("(?<=[a-z])I(?=[a-z])");
                        species = r.Replace(species, "l");
                        // readd spaces before capital letters
                        r       = new Regex("(?<=[a-z])(?=[A-Z])");
                        species = r.Replace(species, " ");

                        finishedText += "\t→ " + sex.ToString() + ", " + species;
                    }
                    else if (statName == "Owner" && mc[0].Groups.Count > 0)
                    {
                        ownerName     = mc[0].Groups[0].Value;
                        finishedText += "\t→ " + ownerName;
                    }
                    else if (statName == "Tribe" && mc[0].Groups.Count > 0)
                    {
                        tribeName     = mc[0].Groups[0].Value.Replace("Tobe", "Tribe").Replace("Tdbe", "Tribe").Replace("Tribeof", "Tribe of ");
                        finishedText += "\t→ " + tribeName;
                    }
                    continue;
                }

                if (mc[0].Groups.Count > 2 && mc[0].Groups[2].Value == "%" && statName == "Weight")
                {
                    // first stat with a '%' is damage, if oxygen is missing, shift all stats by one
                    finalValues[4] = finalValues[3]; // shift food to weight
                    finalValues[3] = finalValues[2]; // shift oxygen to food
                    finalValues[2] = 0;              // set oxygen (which wasn't there) to 0
                    stI++;
                }

                double.TryParse(mc[0].Groups[1].Value.Replace('\'', '.').Replace(',', '.').Replace('O', '0'), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.GetCultureInfo("en-US"), out double v); // common substitutions: comma and apostrophe to dot,

                finishedText += $"\t→ {v}";

                // TODO: test here that the read stat name corresponds to the stat supposed to be read
                finalValues[stI] = v;
            }

            OCRText = finishedText;

            // TODO reorder stats to match 12-stats-order

            return(finalValues);

            /*
             * Bitmap grab = Win32Stuff.GetSreenshotOfProcess(screenCaptureApplicationName);
             * AddBitmapToDebug(grab);
             *
             * //grab.Save("E:\\Temp\\Calibration8.png", ImageFormat.Png);
             * if (changeForegroundWindow)
             *  Win32Stuff.SetForegroundWindow(Application.OpenForms[0].Handle);
             */
        }
Example #10
0
        /// <summary>
        /// For electronic books, we want to limit the dimensions of images since they'll be displayed
        /// on small screens.  More importantly, we want to limit the size of the image file since it
        /// will often be transmitted over slow network connections.  So rather than merely zipping up
        /// an image file, we set its dimensions to within our desired limit (currently 600x600px) and
        /// generate the bytes in the desired format.  If the original image is already small enough, we
        /// retain its dimensions.  We also make png images have transparent backgrounds if requested so
        /// that they will work for cover pages.  If transparency is not needed, the original image file
        /// bytes are returned if that results in a smaller final image file.
        /// </summary>
        /// <remarks>
        /// Note that we have to write png files with 32-bit color even if the orginal file used 1-bit
        /// 4-bit, or 8-bit grayscale.  So .png files may come out bigger even when the dimensions
        /// shrink, and likely will be bigger when the dimensions stay the same.  This might be a
        /// limitation of the underlying .Net/Windows and Mono/Linux code, or might be needed for
        /// transparent backgrounds.
        /// </remarks>
        /// <returns>The bytes of the (possibly) adjusted image.</returns>
        internal static byte[] GetImageBytesForElectronicPub(string filePath, bool needsTransparentBackground)
        {
            var originalBytes = RobustFile.ReadAllBytes(filePath);

            using (var originalImage = PalasoImage.FromFileRobustly(filePath))
            {
                var image           = originalImage.Image;
                int originalWidth   = image.Width;
                int originalHeight  = image.Height;
                var appearsToBeJpeg = ImageUtils.AppearsToBeJpeg(originalImage);
                if (originalWidth > kMaxWidth || originalHeight > kMaxHeight || !appearsToBeJpeg)
                {
                    // Preserve the aspect ratio
                    float scaleX = (float)kMaxWidth / (float)originalWidth;
                    float scaleY = (float)kMaxHeight / (float)originalHeight;
                    // no point in ever expanding, even if we're making a new image just for transparency.
                    float scale = Math.Min(1.0f, Math.Min(scaleX, scaleY));

                    // New width and height maintaining the aspect ratio
                    int newWidth         = (int)(originalWidth * scale);
                    int newHeight        = (int)(originalHeight * scale);
                    var imagePixelFormat = image.PixelFormat;
                    switch (imagePixelFormat)
                    {
                    // These three formats are not supported for bitmaps to be drawn on using Graphics.FromImage.
                    // So use the default bitmap format.
                    // Enhance: if these are common it may be worth research to find out whether there are better options.
                    // - possibly the 'reduced' image might not be reduced...even though smaller, the indexed format
                    // might be so much more efficient that it is smaller. However, even if that is true, it doesn't
                    // necessarily follow that it takes less memory to render on the device. So it's not obvious that
                    // we should keep the original just because it's a smaller file.
                    // - possibly we don't need a 32-bit bitmap? Unfortunately the 1bpp/4bpp/8bpp only tells us
                    // that the image uses two, 16, or 256 distinct colors, not what they are or what precision they have.
                    case PixelFormat.Format1bppIndexed:
                    case PixelFormat.Format4bppIndexed:
                    case PixelFormat.Format8bppIndexed:
                        imagePixelFormat = PixelFormat.Format32bppArgb;
                        break;
                    }
                    // OTOH, always using 32-bit format for .png files keeps us from having problems in BloomReader
                    // like BL-5740 (where 24bit format files came out in BR with black backgrounds).
                    if (!appearsToBeJpeg)
                    {
                        imagePixelFormat = PixelFormat.Format32bppArgb;
                    }
                    // Image files may have unknown formats which can be read, but not written.
                    // See https://issues.bloomlibrary.org/youtrack/issue/BH-5812.
                    imagePixelFormat = EnsureValidPixelFormat(imagePixelFormat);

                    var needTransparencyConversion =
                        !appearsToBeJpeg && needsTransparentBackground && !ImageUtils.HasTransparency(image);

                    using (var newImage = new Bitmap(newWidth, newHeight, imagePixelFormat))
                    {
                        // Draws the image in the specified size with quality mode set to HighQuality
                        using (Graphics graphics = Graphics.FromImage(newImage))
                        {
                            graphics.CompositingQuality = CompositingQuality.HighQuality;
                            graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                            graphics.SmoothingMode      = SmoothingMode.HighQuality;
                            using (var imageAttributes = new ImageAttributes())
                            {
                                // See https://stackoverflow.com/a/11850971/7442826
                                // Fixes the 50% gray border issue on bright white or dark images
                                imageAttributes.SetWrapMode(WrapMode.TileFlipXY);

                                // In addition to possibly scaling, we want PNG images to have transparent backgrounds.
                                if (needTransparencyConversion)
                                {
                                    // This specifies that all white or very-near-white pixels (all color components at least 253/255)
                                    // will be made transparent.
                                    imageAttributes.SetColorKey(Color.FromArgb(253, 253, 253), Color.White);
                                }
                                var destRect = new Rectangle(0, 0, newWidth, newHeight);
                                graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height,
                                                   GraphicsUnit.Pixel, imageAttributes);
                            }
                        }
                        // Save the file in the same format as the original, and return its bytes.
                        using (var tempFile = TempFile.WithExtension(Path.GetExtension(filePath)))
                        {
                            // This uses default quality settings for jpgs...one site says this is
                            // 75 quality on a scale that runs from 0-100. For most images, this
                            // should give a quality barely distinguishable from uncompressed and still save
                            // about 7/8 of the file size. Lower quality settings rapidly lose quality
                            // while only saving a little space; higher ones rapidly use more space
                            // with only marginal quality improvement.
                            // See  https://photo.stackexchange.com/questions/30243/what-quality-to-choose-when-converting-to-jpg
                            // for more on quality and  https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-set-jpeg-compression-level
                            // for how to control the quality setting if we decide to (RobustImageIO has
                            // suitable overloads).
                            RobustImageIO.SaveImage(newImage, tempFile.Path, image.RawFormat);
                            // Copy the metadata from the original file to the new file.
                            var metadata = SIL.Windows.Forms.ClearShare.Metadata.FromFile(filePath);
                            if (!metadata.IsEmpty)
                            {
                                metadata.Write(tempFile.Path);
                            }
                            var newBytes = RobustFile.ReadAllBytes(tempFile.Path);
                            if (newBytes.Length < originalBytes.Length || needTransparencyConversion)
                            {
                                return(newBytes);
                            }
                        }
                    }
                }
            }
            return(originalBytes);
        }
        private Bitmap GenerateTemplate()
        {
            // Benchmarks suggest this is fastest regardless of the renderer pixel format
            var template = new Bitmap(Width, Height, PixelFormat.Format32bppPArgb);

            // Draw it
            using (var g = Graphics.FromImage(template))
            {
                g.SmoothingMode     = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;

                if (BackgroundImage != null)
                {
                    // Fill with the background image
                    using (var attribute = new ImageAttributes())
                    {
                        attribute.SetWrapMode(WrapMode.TileFlipXY);
                        g.DrawImage(
                            BackgroundImage,
                            new Rectangle(0, 0, Width, Height),
                            0,
                            0,
                            BackgroundImage.Width,
                            BackgroundImage.Height,
                            GraphicsUnit.Pixel,
                            attribute);
                    }
                }
                else
                {
                    // Fill background
                    using (var brush = new SolidBrush(BackgroundColor))
                    {
                        g.FillRectangle(brush, -1, -1, Width + 1, Height + 1);
                    }
                }

                foreach (var channel in _channels)
                {
                    if (channel.BackgroundColor != Color.Transparent)
                    {
                        using (var b = new SolidBrush(channel.BackgroundColor))
                        {
                            g.FillRectangle(b, channel.Bounds);
                        }
                    }

                    if (channel.ZeroLineColor != Color.Transparent && channel.ZeroLineWidth > 0)
                    {
                        using (var pen = new Pen(channel.ZeroLineColor, channel.ZeroLineWidth))
                        {
                            // Draw the zero line
                            g.DrawLine(
                                pen,
                                channel.Bounds.Left,
                                channel.Bounds.Top + channel.Bounds.Height / 2,
                                channel.Bounds.Right,
                                channel.Bounds.Top + channel.Bounds.Height / 2);
                        }
                    }

                    if (channel.BorderWidth > 0 && channel.BorderColor != Color.Transparent)
                    {
                        using (var pen = new Pen(channel.BorderColor, channel.BorderWidth))
                        {
                            if (channel.BorderEdges)
                            {
                                // We want all edges to show equally.
                                // To achieve this, we need to artificially pull the edges in 1px on the right and bottom.
                                g.DrawRectangle(
                                    pen,
                                    channel.Bounds.Left,
                                    channel.Bounds.Top,
                                    channel.Bounds.Width - (channel.Bounds.Right == RenderingBounds.Right ? 1 : 0),
                                    channel.Bounds.Height - (channel.Bounds.Bottom == RenderingBounds.Bottom ? 1 : 0));
                            }
                            else
                            {
                                // We want to draw all lines which are not on the rendering bounds
                                if (channel.Bounds.Left != RenderingBounds.Left)
                                {
                                    g.DrawLine(pen, channel.Bounds.Left, channel.Bounds.Top, channel.Bounds.Left, channel.Bounds.Bottom);
                                }
                                if (channel.Bounds.Top != RenderingBounds.Top)
                                {
                                    g.DrawLine(pen, channel.Bounds.Left, channel.Bounds.Top, channel.Bounds.Right, channel.Bounds.Top);
                                }
                                if (channel.Bounds.Right != RenderingBounds.Right)
                                {
                                    g.DrawLine(pen, channel.Bounds.Right, channel.Bounds.Top, channel.Bounds.Right, channel.Bounds.Bottom);
                                }
                                if (channel.Bounds.Bottom != RenderingBounds.Bottom)
                                {
                                    g.DrawLine(pen, channel.Bounds.Left, channel.Bounds.Bottom, channel.Bounds.Right, channel.Bounds.Bottom);
                                }
                            }
                        }
                    }

                    if (channel.LabelFont != null && channel.LabelColor != Color.Transparent)
                    {
                        g.TextRenderingHint = TextRenderingHint.AntiAlias;
                        using (var brush = new SolidBrush(channel.LabelColor))
                        {
                            var stringFormat    = new StringFormat();
                            var layoutRectangle = new RectangleF(
                                channel.Bounds.Left + channel.LabelMargins.Left,
                                channel.Bounds.Top + channel.LabelMargins.Top,
                                channel.Bounds.Width - channel.LabelMargins.Left - channel.LabelMargins.Right,
                                channel.Bounds.Height - channel.LabelMargins.Top - channel.LabelMargins.Bottom);
                            switch (channel.LabelAlignment)
                            {
                            case ContentAlignment.TopLeft:
                                stringFormat.Alignment     = StringAlignment.Near;
                                stringFormat.LineAlignment = StringAlignment.Near;
                                break;

                            case ContentAlignment.TopCenter:
                                stringFormat.Alignment     = StringAlignment.Center;
                                stringFormat.LineAlignment = StringAlignment.Near;
                                break;

                            case ContentAlignment.TopRight:
                                stringFormat.Alignment     = StringAlignment.Far;
                                stringFormat.LineAlignment = StringAlignment.Near;
                                break;

                            case ContentAlignment.MiddleLeft:
                                stringFormat.Alignment     = StringAlignment.Near;
                                stringFormat.LineAlignment = StringAlignment.Center;
                                break;

                            case ContentAlignment.MiddleCenter:
                                stringFormat.Alignment     = StringAlignment.Center;
                                stringFormat.LineAlignment = StringAlignment.Center;
                                break;

                            case ContentAlignment.MiddleRight:
                                stringFormat.Alignment     = StringAlignment.Far;
                                stringFormat.LineAlignment = StringAlignment.Center;
                                break;

                            case ContentAlignment.BottomLeft:
                                stringFormat.Alignment     = StringAlignment.Near;
                                stringFormat.LineAlignment = StringAlignment.Far;
                                break;

                            case ContentAlignment.BottomCenter:
                                stringFormat.Alignment     = StringAlignment.Center;
                                stringFormat.LineAlignment = StringAlignment.Far;
                                break;

                            case ContentAlignment.BottomRight:
                                stringFormat.Alignment     = StringAlignment.Far;
                                stringFormat.LineAlignment = StringAlignment.Far;
                                break;

                            default:
                                throw new ArgumentOutOfRangeException();
                            }

                            g.DrawString(channel.Label, channel.LabelFont, brush, layoutRectangle, stringFormat);
                        }
                    }
                }
            }

            return(template);
        }
Example #12
0
        public static Bitmap FitBitmap(Bitmap source, int maxSize, out string comment)
        {
            bool makeTilable = true;

            comment = "Texture is fine.";
            if (source.Width * source.Height <= maxSize)
            {
                return(source);
            }

            int newWidth  = source.Width;
            int newHeight = source.Height;

            while (newWidth * newHeight > maxSize)
            {
                if (!makeTilable)
                {
                    if (newWidth > newHeight)
                    {
                        newWidth--;
                        newHeight = (int)(source.Height * (float)newWidth / source.Width + 0.5f);
                    }
                    else
                    {
                        newHeight--;
                        newWidth = (int)(source.Width * (float)newHeight / source.Height + 0.5f);
                    }
                }
                else
                {
                    newWidth  = 1 << ((int)Math.Log(newWidth - 1, 2));
                    newHeight = 1 << ((int)Math.Log(newHeight - 1, 2));
                }
            }
            comment = "Image is too large (" + source.Width.ToString() + " x " + source.Height.ToString() + ") and has to be resized to " + newWidth.ToString() + " x " + newHeight.ToString();
            if (newWidth * newHeight > maxSize)
            {
                EmulationState.messages.AppendMessage("Failed to scale image down D:", "This should really not happen");
            }

            Rectangle destRect  = new Rectangle(0, 0, newWidth, newHeight);
            Bitmap    destImage = new Bitmap(newWidth, newHeight);

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

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

                using (ImageAttributes wrapMode = new ImageAttributes())
                {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                    graphics.DrawImage(source, destRect, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }
            return(destImage);
        }
        public ActionResult AddPhoto(HttpPostedFileBase file)
        {
            var fileName      = string.Empty;
            var path          = string.Empty;
            var thumbFileName = string.Empty;
            var thumbFilePath = string.Empty;

            //check exist file from from
            if (file != null)
            {
                var fileSize = file.ContentLength;

                //check file size
                //max image size
                int maxImageSize = int.Parse(ConfigurationManager.AppSettings["MaxByteImageSize"]);

                if (fileSize > maxImageSize * 1024)
                {
                    TempData["Message"] = "file is too big";
                    return(RedirectToAction("UserGallery", "Gallery"));
                }

                var fileExtention = Path.GetExtension(file.FileName).ToLower();

                //valid exeptions
                string[] listOfExtensions = ConfigurationManager.AppSettings["ValidImageExtensions"].Split(',');

                var isAccept = false;

                //check valid file extension
                foreach (var item in listOfExtensions)
                {
                    if (fileExtention == item)
                    {
                        isAccept = true;
                        break;
                    }
                }

                if (!isAccept)
                {
                    TempData["Message"] = "File isn't a picture";

                    return(RedirectToAction("UserGallery"));
                }

                fileName = Path.GetFileName(file.FileName);
                //upload path from app.settings
                var uploadPath = ConfigurationManager.AppSettings["UploadImagePath"];

                var dirPath = Path.Combine(Server.MapPath(uploadPath), User.Identity.GetUserId());


                path = Path.Combine(dirPath, fileName);

                //check exist directory
                if (Directory.Exists(dirPath))
                {
                    if (System.IO.File.Exists(path))
                    {
                        TempData["Message"] = "The file with same name ia already exist";

                        return(RedirectToAction("UserGallery"));
                    }
                    else
                    {
                        file.SaveAs(path);
                    }
                }
                else
                {
                    Directory.CreateDirectory(dirPath);
                    file.SaveAs(path);
                }

                //creates thumbnail
                Rectangle cropRectangle = new Rectangle(0, 0, 420, 236);
                Bitmap    src           = Image.FromStream(file.InputStream, true, true) as Bitmap;
                Bitmap    target        = new Bitmap(cropRectangle.Width, cropRectangle.Height);

                target.SetResolution(src.HorizontalResolution, src.VerticalResolution);

                using (Graphics g = Graphics.FromImage(target))
                {
                    g.CompositingMode    = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

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

                //thumbnail file name
                thumbFileName  = Path.GetFileNameWithoutExtension(file.FileName) + "_thumb";
                thumbFileName += Path.GetExtension(file.FileName);

                //thumbnail path
                var thumbPath = Path.Combine(Server.MapPath(uploadPath + User.Identity.GetUserId()), "thumbnail");
                thumbFilePath = Path.Combine(thumbPath, thumbFileName);


                //check exist directory
                if (Directory.Exists(thumbPath))
                {
                    if (!System.IO.File.Exists(thumbFilePath))
                    {
                        target.Save(thumbFilePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    }
                }
                else
                {
                    Directory.CreateDirectory(thumbPath);
                    target.Save(thumbFilePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }

            var userId = _userService.FindUserByName(User.Identity.Name).Result.Id;

            var pic = new PhotoDto()
            {
                Id                = Guid.NewGuid().ToString(),
                PhotoName         = fileName,
                DateTimeUploading = DateTime.Now,
                PhotoPath         = path,
                ThumbnailPath     = thumbFilePath,
                IsPublish         = false,
                ApplicationUserId = userId
            };


            _photoService.Add(pic);

            ViewBag.StatusMessage = "File successfully uploaded!";

            return(RedirectToAction("GetAllPath", "Gallery", new { userId = pic.ApplicationUserId }));
        }
    protected override void Apply(ImageProcessingActionExecuteArgs args)
    {
        Bitmap result = null;
        try
        {
            // Create the result image
            result = new Bitmap(350, 350, CodeCarvings.Piczard.CommonData.DefaultPixelFormat);

            // Set the right image resolution (DPI)
            ImageHelper.SetImageResolution(result, args.ImageProcessingJob.OutputResolution);

            using (Graphics g = Graphics.FromImage(result))
            {
                // Use the max quality
                ImageHelper.SetGraphicsMaxQuality(g);

                if ((args.IsLastAction) && (!args.AppliedImageBackColorValue.HasValue))
                {
                    // Optimization (not mandatory)
                    // This is the last filter action and the ImageBackColor has not been yet applied...
                    // Apply the ImageBackColor now to save RAM & CPU
                    args.ApplyImageBackColor(g);
                }

                using (ImageAttributes imageAttributes = new ImageAttributes())
                {
                    // Important
                    imageAttributes.SetWrapMode(WrapMode.TileFlipXY);

                    // Draw the scaled image
                    Rectangle destinationRectangle = new Rectangle(75, 52, 200, 200);
                    using (Image resizedImage = new FixedCropConstraint(GfxUnit.Pixel, destinationRectangle.Size).GetProcessedImage(args.Image))
                    {
                        g.DrawImage(resizedImage, destinationRectangle, 0, 0, resizedImage.Width, resizedImage.Height, GraphicsUnit.Pixel, imageAttributes);

                        // Draw the reflection
                        destinationRectangle = new Rectangle(75, 252, 200, 98);
                        using (Image flippedImage = ImageTransformation.FlipVertical.GetProcessedImage(resizedImage))
                        {
                            g.DrawImage(flippedImage, destinationRectangle, 0, 0, flippedImage.Width, flippedImage.Height, GraphicsUnit.Pixel, imageAttributes);
                        }
                    }

                    // Draw the mask
                    destinationRectangle = new Rectangle(0, 0, result.Width, result.Height);
                    using (LoadedImage loadedImage = ImageArchiver.LoadImage("~/repository/filters/MyCustomFilter1Mask.png"))
                    {
                        g.DrawImage(loadedImage.Image, destinationRectangle, 0, 0, loadedImage.Size.Width, loadedImage.Size.Height, GraphicsUnit.Pixel, imageAttributes);
                    }
                }

                // Draw the text
                string text = "Generated by 'MyCustomFilter1' on " + DateTime.Now.ToString();
                FontDefinition fontDefinition = new FontDefinition();
                fontDefinition.Size = 12; //12px
                using (Font font = fontDefinition.GetFont())
                {
                    // Setup the custom parameters
                    g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

                    using (StringFormat stringFormat = new StringFormat())
                    {
                        SizeF textSize = g.MeasureString(text, font, int.MaxValue, stringFormat);
                        Size pixelTextSize = new Size(Convert.ToInt32(Math.Round(textSize.Width)), Convert.ToInt32(Math.Round(textSize.Height)));

                        // Calculate the text position
                        Point location = new Point((result.Width - pixelTextSize.Width) / 2, result.Height - 14 - pixelTextSize.Height);

                        // Draw the text
                        using (Brush brush = new SolidBrush(ColorTranslator.FromHtml("#5b615d")))
                        {
                            g.DrawString(text, font, brush, location, stringFormat);
                        }
                    }
                }
            }

            // Return the image
            args.Image = result;
        }
        catch
        {
            // An error has occurred...

            // Release the resources
            if (result != null)
            {
                result.Dispose();
                result = null;
            }

            // Re-throw the exception
            throw;
        }
    }
Example #15
0
        /// <summary>
        /// Renders the layer
        /// </summary>
        /// <param name="graphics">Graphics object reference</param>
        /// <param name="map">Map which is rendered</param>
        public override void Render(IGraphics graphics, Map map)
        {
            if (!map.Size.IsEmpty && map.Size.Width > 0 && map.Size.Height > 0)
            {
                var bmp = new Bitmap(map.Size.Width, map.Size.Height, PixelFormat.Format32bppArgb);

                using (IGraphics g = Graphics.FromImage(bmp).G())
                {
                    g.InterpolationMode = InterpolationMode;
                    g.Transform         = graphics.Transform.Clone();

                    var extent = new Extent(map.Envelope.MinX, map.Envelope.MinY,
                                            map.Envelope.MaxX, map.Envelope.MaxY);
                    var level      = BruTile.Utilities.GetNearestLevel(_source.Schema.Resolutions, map.PixelSize);
                    var tiles      = new List <TileInfo>(_source.Schema.GetTilesInView(extent, level));
                    var tileWidth  = _source.Schema.GetTileWidth(level);
                    var tileHeight = _source.Schema.GetTileWidth(level);

                    IList <WaitHandle> waitHandles = new List <WaitHandle>();
                    var toRender       = new Dictionary <TileIndex, Bitmap>();
                    var takenFromCache = new Dictionary <TileIndex, bool>();
                    foreach (TileInfo info in tiles)
                    {
                        var image = _bitmaps.Find(info.Index);
                        if (image != null)
                        {
                            toRender.Add(info.Index, image);
                            takenFromCache.Add(info.Index, true);
                            continue;
                        }
                        if (_fileCache != null && _fileCache.Exists(info.Index))
                        {
                            _bitmaps.Add(info.Index, GetImageFromFileCache(info) as Bitmap);
                            toRender.Add(info.Index, _bitmaps.Find(info.Index));
                            takenFromCache.Add(info.Index, true);
                            continue;
                        }

                        var waitHandle = new AutoResetEvent(false);
                        waitHandles.Add(waitHandle);
                        ThreadPool.QueueUserWorkItem(GetTileOnThread,
                                                     new object[] { _source.Provider, info, toRender, waitHandle, true });
                    }

                    foreach (var handle in waitHandles)
                    {
                        handle.WaitOne();
                    }

                    using (var ia = new ImageAttributes())
                    {
                        if (!_transparentColor.IsEmpty)
                        {
                            ia.SetColorKey(_transparentColor, _transparentColor);
                        }
#if !PocketPC
                        ia.SetWrapMode(WrapMode.TileFlipXY);
#endif

                        foreach (var info in tiles)
                        {
                            if (!toRender.ContainsKey(info.Index))
                            {
                                continue;
                            }

                            var bitmap = toRender[info.Index];//_bitmaps.Find(info.Index);
                            if (bitmap == null)
                            {
                                continue;
                            }

                            var min = map.WorldToImage(new Coordinate(info.Extent.MinX, info.Extent.MinY));
                            var max = map.WorldToImage(new Coordinate(info.Extent.MaxX, info.Extent.MaxY));

                            min = new PointF((float)Math.Round(min.X), (float)Math.Round(min.Y));
                            max = new PointF((float)Math.Round(max.X), (float)Math.Round(max.Y));

                            try
                            {
                                g.DrawImage(bitmap,
                                            (int)min.X, (int)max.Y, (int)(max.X - min.X),
                                            (int)(min.Y - max.Y), 0, 0, tileWidth, tileHeight,
                                            GraphicsUnitType.Pixel, ia);
                            }
                            catch (Exception ee)
                            {
                                Logger.Error(ee.Message);
                            }
                        }
                    }

                    //Add rendered tiles to cache
                    foreach (var kvp in toRender)
                    {
                        if (takenFromCache.ContainsKey(kvp.Key) && !takenFromCache[kvp.Key])
                        {
                            _bitmaps.Add(kvp.Key, kvp.Value);
                        }
                    }

                    graphics.Transform = new Matrix();
                    graphics.DrawImageUnscaled(bmp, 0, 0);
                    graphics.Transform = g.Transform;
                }
            }
        }
Example #16
0
        // todo not used, remove?
        //private static Rectangle letterRect(Bitmap source, int hStart, int hEnd)
        //{
        //    int startWhite = -1, endWhite = -1;
        //    for (int j = 0; j < source.Height; j++)
        //    {
        //        for (int i = hStart; i < hEnd; i++)
        //        {
        //            if (startWhite == -1 && source.GetPixel(i, j).R == 255)
        //            {
        //                startWhite = j;
        //            }

        //            if (endWhite == -1 && source.GetPixel(i, (source.Height - j) - 1).R == 255)
        //            {
        //                endWhite = (source.Height - j);
        //            }
        //            if (startWhite != -1 && endWhite != -1)
        //                return new Rectangle(hStart, startWhite, hEnd - hStart, endWhite - startWhite);
        //        }
        //    }


        //    return Rectangle.Empty;
        //}

        public double[] DoOcr(out string OCRText, out string dinoName, out string species, out string ownerName, out string tribeName, out Sex sex, string useImageFilePath = "", bool changeForegroundWindow = true)
        {
            string finishedText = string.Empty;

            dinoName  = string.Empty;
            species   = string.Empty;
            ownerName = string.Empty;
            tribeName = string.Empty;
            sex       = Sex.Unknown;
            double[] finalValues = new double[1] {
                0
            };
            if (ocrConfig == null)
            {
                OCRText = "Error: no ocr configured";
                return(finalValues);
            }

            Bitmap screenshotbmp;

            _ocrControl.debugPanel.Controls.Clear();
            _ocrControl.ClearLists();

            if (System.IO.File.Exists(useImageFilePath))
            {
                screenshotbmp = (Bitmap)Image.FromFile(useImageFilePath);
            }
            else
            {
                // grab screenshot from ark
                screenshotbmp = Win32API.GetScreenshotOfProcess(screenCaptureApplicationName, waitBeforeScreenCapture, true);
            }
            if (screenshotbmp == null)
            {
                OCRText = "Error: no image for OCR. Is ARK running?";
                return(finalValues);
            }

            if (!CheckResolutionSupportedByOcr(screenshotbmp))
            {
                OCRText = "Error while calibrating: The game-resolution is not supported by the currently loaded OCR-configuration.\n"
                          + $"The tested image has a resolution of {screenshotbmp.Width} × {screenshotbmp.Height} px,\n"
                          + $"the resolution of the loaded ocr-config is {ocrConfig.resolutionWidth} × {ocrConfig.resolutionHeight} px.\n\n"
                          + "Load a ocr-config file with the resolution of the game to make it work.";
                return(finalValues);
            }

            // TODO resize image according to resize-factor. used for large screenshots
            if (ocrConfig.resize != 1 && ocrConfig.resize > 0)
            {
                Bitmap resized = new Bitmap((int)(ocrConfig.resize * ocrConfig.resolutionWidth), (int)(ocrConfig.resize * ocrConfig.resolutionHeight));
                using (var graphics = Graphics.FromImage(resized))
                {
                    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(screenshotbmp, new Rectangle(0, 0, 1920, 1080), 0, 0, screenshotbmp.Width, screenshotbmp.Height, GraphicsUnit.Pixel, wrapMode);
                    }

                    screenshotbmp?.Dispose();
                    screenshotbmp = resized;
                }
            }

            if (enableOutput && _ocrControl != null)
            {
                _ocrControl.AddBitmapToDebug(screenshotbmp);
                _ocrControl.SetScreenshot(screenshotbmp);
            }

            finalValues    = new double[ocrConfig.labelRectangles.Length];
            finalValues[8] = -1; // set imprinting to -1 to mark it as unknown and to set a difference to a creature with 0% imprinting.

            if (changeForegroundWindow)
            {
                Win32API.SetForegroundWindow(Application.OpenForms[0].Handle);
            }


            bool wild = false; // todo: set to true and find out if the creature is wild in the first loop
            int  stI  = -1;

            for (int lbI = 0; lbI < ocrConfig.labelNames.Count; lbI++)
            {
                stI++;
                if (lbI == 8)
                {
                    stI = 8;
                }
                string statName = ocrConfig.labelNames[stI];

                switch (statName)
                {
                case "NameSpecies":
                    if (ocrConfig.RecognitionPatterns.TrainingSettings.SkipName)
                    {
                        dinoName = string.Empty;
                        continue;
                    }
                    break;

                case "Tribe":
                    if (ocrConfig.RecognitionPatterns.TrainingSettings.SkipTribe)
                    {
                        tribeName = string.Empty;
                        continue;
                    }

                    break;

                case "Owner":
                    if (ocrConfig.RecognitionPatterns.TrainingSettings.SkipOwner)
                    {
                        ownerName = string.Empty;
                        continue;
                    }
                    break;
                }

                Rectangle rec = ocrConfig.labelRectangles[lbI];

                // wild creatures don't have the xp-bar, all stats are moved one row up
                if (wild && stI < 9)
                {
                    rec.Offset(0, ocrConfig.labelRectangles[0].Top - ocrConfig.labelRectangles[1].Top);
                }

                Bitmap testbmp = SubImage(screenshotbmp, rec.X, rec.Y, rec.Width, rec.Height);
                //AddBitmapToDebug(testbmp);

                string statOcr;

                try
                {
                    if (statName == "NameSpecies")
                    {
                        statOcr = PatternOcr.ReadImageOcr(testbmp, false, 0.85f, _ocrControl);
                    }
                    else if (statName == "Level")
                    {
                        statOcr = PatternOcr.ReadImageOcr(testbmp, true, 1.1f, _ocrControl).Replace(".", ": ");
                    }
                    else if (statName == "Tribe" || statName == "Owner")
                    {
                        statOcr = PatternOcr.ReadImageOcr(testbmp, false, 0.8f, _ocrControl);
                    }
                    else
                    {
                        statOcr = PatternOcr.ReadImageOcr(testbmp, true, ocrControl: _ocrControl).Trim('.'); // statValues are only numbers
                    }
                }
                catch (OperationCanceledException)
                {
                    OCRText = "Canceled";
                    return(finalValues);
                }

                if (statOcr == string.Empty &&
                    (statName == "Health" || statName == "Imprinting" || statName == "Tribe" || statName == "Owner"))
                {
                    if (wild && statName == "Health")
                    {
                        stI--;
                        wild = false;
                    }
                    continue; // these can be missing, it's fine
                }

                finishedText += (finishedText.Length == 0 ? string.Empty : "\r\n") + statName + ":\t" + statOcr;

                // parse the OCR String

                var r = new Regex(@"^[_\/\\]*(.*?)[_\/\\]*$");
                statOcr = r.Replace(statOcr, "$1");

                if (statName == "NameSpecies")
                {
                    r = new Regex(@".*?([♂♀])?[_.,-\/\\]*([^♂♀]+?)(?:[\(\[]([^\[\(\]\)]+)[\)\]]$|$)");
                }
                else if (statName == "Owner" || statName == "Tribe")
                {
                    r = new Regex(@"(.*)");
                }
                else if (statName == "Level")
                {
                    r = new Regex(@".*\D(\d+)");
                }
                else
                {
                    r = new Regex(@"(?:[\d.,%\/]*\/)?(\d+[\.,']?\d?)(%)?\.?"); // only the second numbers is interesting after the current weight is not shown anymore

                    //if (onlyNumbers)
                    //r = new Regex(@"((\d*[\.,']?\d?\d?)\/)?(\d*[\.,']?\d?\d?)");
                    //else
                    // r = new Regex(@"([a-zA-Z]*)[:;]((\d*[\.,']?\d?\d?)\/)?(\d*[\.,']?\d?\d?)");
                }

                MatchCollection mc = r.Matches(statOcr);

                if (mc.Count == 0)
                {
                    if (statName == "NameSpecies" || statName == "Owner" || statName == "Tribe")
                    {
                        continue;
                    }
                    //if (statName == "Torpor")
                    //{
                    //    // probably it's a wild creature
                    //    // todo
                    //}
                    //else
                    //{
                    finishedText    += "error reading stat " + statName;
                    finalValues[stI] = 0;
                    continue;
                    //}
                }

                if (statName == "NameSpecies" || statName == "Owner" || statName == "Tribe")
                {
                    if (statName == "NameSpecies" && mc[0].Groups.Count > 0)
                    {
                        if (mc[0].Groups[1].Value == "♀")
                        {
                            sex = Sex.Female;
                        }
                        else if (mc[0].Groups[1].Value == "♂")
                        {
                            sex = Sex.Male;
                        }
                        dinoName = mc[0].Groups[2].Value;
                        species  = mc[0].Groups[3].Value;
                        if (species.Length == 0)
                        {
                            species = dinoName;
                        }

                        // remove non-letter chars
                        r       = new Regex("[^a-zA-Z]");
                        species = r.Replace(species, string.Empty);
                        // replace capital I with lower l (common misrecognition)
                        r       = new Regex("(?<=[a-z])I(?=[a-z])");
                        species = r.Replace(species, "l");
                        // readd spaces before capital letters
                        r       = new Regex("(?<=[a-z])(?=[A-Z])");
                        species = r.Replace(species, " ");

                        finishedText += "\t→ " + sex.ToString() + ", " + species;
                    }
                    else if (statName == "Owner" && mc[0].Groups.Count > 0)
                    {
                        ownerName     = mc[0].Groups[0].Value;
                        finishedText += "\t→ " + ownerName;
                    }
                    else if (statName == "Tribe" && mc[0].Groups.Count > 0)
                    {
                        tribeName     = mc[0].Groups[0].Value.Replace("Tobe", "Tribe").Replace("Tdbe", "Tribe").Replace("Tribeof", "Tribe of ");
                        finishedText += "\t→ " + tribeName;
                    }
                    continue;
                }

                if (mc[0].Groups.Count > 2 && mc[0].Groups[2].Value == "%" && statName == "Weight")
                {
                    // first stat with a '%' is damage, if oxygen is missing, shift all stats by one
                    finalValues[4] = finalValues[3]; // shift food to weight
                    finalValues[3] = finalValues[2]; // shift oxygen to food
                    finalValues[2] = 0;              // set oxygen (which wasn't there) to 0
                    stI++;
                }

                var splitRes = statOcr.Split('/', ',', ':');
                var ocrValue = splitRes[splitRes.Length - 1] == "%" ? splitRes[splitRes.Length - 2] : splitRes[splitRes.Length - 1];

                ocrValue = PatternOcr.RemoveNonNumeric(ocrValue);

                double.TryParse(ocrValue, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.GetCultureInfo("en-US"), out double v); // common substitutions: comma and apostrophe to dot,

                if (statName == "MeleeDamage" && v > 1000)
                {
                    v = v / 10;
                }

                finishedText += $"\t→ {v}";

                // TODO: test here that the read stat name corresponds to the stat supposed to be read
                finalValues[stI] = v;
            }

            OCRText = finishedText;

            // TODO reorder stats to match 12-stats-order

            return(finalValues);

            /*
             * Bitmap grab = Win32Stuff.GetSreenshotOfProcess(screenCaptureApplicationName);
             * AddBitmapToDebug(grab);
             *
             * //grab.Save("E:\\Temp\\Calibration8.png", ImageFormat.Png);
             * if (changeForegroundWindow)
             *  Win32Stuff.SetForegroundWindow(Application.OpenForms[0].Handle);
             */
        }
Example #17
0
        /// <summary>
        /// 图片水印
        /// </summary>
        /// <param name="imgPath">服务器图片相对路径</param>
        /// <param name="filename">保存文件名</param>
        /// <param name="watermarkFilename">水印文件相对路径</param>
        /// <param name="watermarkStatus">图片水印位置 -1=不使用 0=平铺 1=左上 2=中上 3=右上 4=左中  9=右下</param>
        /// <param name="quality">附加水印图片质量,0-100</param>
        /// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param>
        public static void AddImageSignPic(string imgPath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
        {
            if (!File.Exists(Utils.GetMapPath(imgPath)))
            {
                return;
            }
            var imageBytes = File.ReadAllBytes(Utils.GetMapPath(imgPath));
            var img        = Image.FromStream(new MemoryStream(imageBytes));

            filename = Utils.GetMapPath(filename);

            if (watermarkFilename.StartsWith("/") == false)
            {
                watermarkFilename = "/" + watermarkFilename;
            }
            watermarkFilename = Utils.GetMapPath(watermarkFilename);
            if (!File.Exists(watermarkFilename))
            {
                return;
            }
            var g = Graphics.FromImage(img);

            //设置高质量插值法
            g.InterpolationMode = InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = SmoothingMode.HighQuality;
            Image watermark = new Bitmap(watermarkFilename);

            if (watermark.Height >= img.Height || watermark.Width >= img.Width)
            {
                return;
            }

            var imageAttributes = new ImageAttributes();
            var colorMap        = new ColorMap
            {
                OldColor = Color.FromArgb(255, 0, 255, 0),
                NewColor = Color.FromArgb(0, 0, 0, 0)
            };

            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            var transparency = 0.5F;

            if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
            {
                transparency = (watermarkTransparency / 10.0F);
            }


            float[][] colorMatrixElements =
            {
                new float[] { 1.0f, 0.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 1.0f, 0.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 1.0f,         0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, transparency, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f,         0.0f, 1.0f }
            };

            var colorMatrix = new ColorMatrix(colorMatrixElements);

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

            var xpos   = 0;
            var ypos   = 0;
            var width  = watermark.Width;
            var height = watermark.Height;

            switch (watermarkStatus)
            {
            case 0:
                imageAttributes.SetWrapMode(WrapMode.Tile);
                width  = img.Width;
                height = img.Height;
                break;

            case 1:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)(img.Height * (float).01);
                break;

            case 2:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)(img.Height * (float).01);
                break;

            case 3:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)(img.Height * (float).01);
                break;

            case 4:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 5:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 6:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 7:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 8:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 9:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;
            }

            g.DrawImage(watermark, new Rectangle(xpos, ypos, width, height), 0, 0, width, height, GraphicsUnit.Pixel, imageAttributes);

            var            codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici    = null;

            foreach (var codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                {
                    ici = codec;
                }
            }
            var encoderParams = new EncoderParameters();
            var qualityParam  = new long[1];

            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }

            qualityParam[0] = quality;

            var encoderParam = new EncoderParameter(Encoder.Quality, qualityParam);

            encoderParams.Param[0] = encoderParam;

            if (ici != null)
            {
                img.Save(filename, ici, encoderParams);
            }
            else
            {
                img.Save(filename);
            }

            g.Dispose();
            img.Dispose();
            watermark.Dispose();
            imageAttributes.Dispose();
        }
Example #18
0
        public bool ResizeImage(
            string sourceFilePath,
            string targetDirectoryPath,
            string newFileName,
            string mimeType,
            int maxWidth,
            int maxHeight,
            bool allowEnlargement = false,
            long quality          = 90,
            Color backgroundColor = default(Color)
            )
        {
            if (string.IsNullOrEmpty(sourceFilePath))
            {
                throw new ArgumentException("imageFilePath must be provided");
            }

            if (string.IsNullOrEmpty(targetDirectoryPath))
            {
                throw new ArgumentException("targetDirectoryPath must be provided");
            }

            if (string.IsNullOrEmpty(newFileName))
            {
                throw new ArgumentException("newFileName must be provided");
            }

            if (!File.Exists(sourceFilePath))
            {
                log.LogError("imageFilePath does not exist " + sourceFilePath);
                return(false);
            }

            if (!Directory.Exists(targetDirectoryPath))
            {
                log.LogError("targetDirectoryPath does not exist " + targetDirectoryPath);
                return(false);
            }

            double scaleFactor        = 0;
            bool   imageNeedsResizing = true;
            var    targetFilePath     = Path.Combine(targetDirectoryPath, newFileName);

            try
            {
                using (Stream tmpFileStream = File.OpenRead(sourceFilePath))
                {
                    using (Image fullsizeImage = Image.FromStream(tmpFileStream))
                    {
                        scaleFactor = GetScaleFactor(fullsizeImage.Width, fullsizeImage.Height, maxWidth, maxHeight);

                        if (!allowEnlargement)
                        {
                            // don't need to resize since image is smaller than max
                            if (scaleFactor > 1)
                            {
                                imageNeedsResizing = false;
                            }
                            if (scaleFactor == 0)
                            {
                                imageNeedsResizing = false;
                            }
                        }

                        if (imageNeedsResizing)
                        {
                            int newWidth  = (int)(fullsizeImage.Width * scaleFactor);
                            int newHeight = (int)(fullsizeImage.Height * scaleFactor);

                            var codecInfo = GetEncoderInfo(mimeType);

                            using (Bitmap resizedBitmap = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb))
                            {
                                using (Graphics graphics = Graphics.FromImage(resizedBitmap))
                                {
                                    using (var attributes = new ImageAttributes())
                                    {
                                        attributes.SetWrapMode(WrapMode.TileFlipXY);
                                        graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                                        graphics.CompositingQuality = CompositingQuality.HighSpeed;
                                        graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                                        graphics.CompositingMode    = CompositingMode.SourceCopy;
                                        graphics.DrawImage(
                                            fullsizeImage,
                                            Rectangle.FromLTRB(0, 0, newWidth, newHeight),
                                            0, 0, fullsizeImage.Width, fullsizeImage.Height, GraphicsUnit.Pixel, attributes);
                                        // Save the results
                                        using (var output = File.Open(targetFilePath, FileMode.Create))
                                        {
                                            using (EncoderParameters encoderParams = new EncoderParameters(1))
                                            {
                                                encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, quality);
                                                resizedBitmap.Save(output, codecInfo, encoderParams);
                                            }
                                        }
                                    } //end attributes
                                }     //end graphics
                            }         //end using resized bitmap
                        }             //if (imageNeedsResizing)
                    }                 //end using bitmap
                }                     //end using stream
            }
            catch (OutOfMemoryException ex)
            {
                log.LogError(MediaLoggingEvents.RESIZE_OPERATION, ex, ex.Message);
                return(false);
            }
            catch (ArgumentException ex)
            {
                log.LogError(MediaLoggingEvents.RESIZE_OPERATION, ex, ex.Message);
                return(false);
            }

            return(imageNeedsResizing);
        }
Example #19
0
        private void DrawControlBox(Graphics graphics)
        {
            var count = 0;

            #region  钮数量
            if (this.ControlBox)
            {
                count = 1;
                if (this.MaximizeBox)
                {
                    count++;
                }

                if (this.MinimizeBox)
                {
                    count++;
                }

                if (this.HelpButton)
                {
                    count++;
                }
            }
            else
            {
                return;
            }
            #endregion
            if (this.ControlBoxies != null)
            {
                count += this.controlBoxies.Count;
            }

            if (count == 0)
            {
                return;
            }

            var x = this.Width - this.Padding.Right - this.controlBoxSize.Width;
            var y = this.Padding.Top;//(this.Height - this.Padding.Top - this.Padding.Bottom - this.controlBoxSize.Height) / 2 + this.Padding.Top;
            if (this.centerControlBox)
            {
                y = (this.Height - y - this.ControlBoxSize.Height) / 2;
            }
            ImageAttributes ImgAtt = new ImageAttributes();
            ImgAtt.SetWrapMode(System.Drawing.Drawing2D.WrapMode.Clamp);

            if (this.CloseButtonImage != null)
            {
                CloseRect = new Rectangle(x, y, this.controlBoxSize.Width, this.controlBoxSize.Height);
                var color = CloseHover ? this.ControlActivedColor : this.ControlBackColor;
                RadiusDrawable.DrawRadius(graphics, CloseRect, RadiusMode.None, 0, color.FromColor, color.ToColor, color.GradientMode, Color.Empty, 0);

                graphics.DrawImage(this.CloseButtonImage, CloseRect, 0, 0, this.CloseButtonImage.Width, this.CloseButtonImage.Height, GraphicsUnit.Pixel, ImgAtt);
                x -= this.ControlBoxSize.Width;
            }

            if (this.MaximizeBox && this.WindowState == FormWindowState.Maximized && this.NormalBoxImage != null)
            {
                MaxRect = new Rectangle(x, y, this.controlBoxSize.Width, this.controlBoxSize.Height);

                var color = MaxHover ? this.ControlActivedColor : this.ControlBackColor;
                RadiusDrawable.DrawRadius(graphics, MaxRect, RadiusMode.None, 0, color.FromColor, color.ToColor, color.GradientMode, Color.Empty, 0);

                graphics.DrawImage(this.NormalBoxImage, MaxRect, 0, 0, this.NormalBoxImage.Width, this.NormalBoxImage.Height, GraphicsUnit.Pixel, ImgAtt);
                x -= this.ControlBoxSize.Width;
            }
            else if (this.MaximizeBox && this.WindowState != FormWindowState.Maximized && this.MaximizeBoxImage != null)
            {
                MaxRect = new Rectangle(x, y, this.controlBoxSize.Width, this.controlBoxSize.Height);
                var color = MaxHover ? this.ControlActivedColor : this.ControlBackColor;
                RadiusDrawable.DrawRadius(graphics, MaxRect, RadiusMode.None, 0, color.FromColor, color.ToColor, color.GradientMode, Color.Empty, 0);

                graphics.DrawImage(this.MaximizeBoxImage, MaxRect, 0, 0, this.MaximizeBoxImage.Width, this.MaximizeBoxImage.Height, GraphicsUnit.Pixel, ImgAtt);
                x -= this.ControlBoxSize.Width;
            }

            if (this.MinimizeBox && this.MinimizeBoxImage != null)
            {
                MinRect = new Rectangle(x, y, this.controlBoxSize.Width, this.controlBoxSize.Height);
                var color = MinHover ? this.ControlActivedColor : this.ControlBackColor;
                RadiusDrawable.DrawRadius(graphics, MinRect, RadiusMode.None, 0, color.FromColor, color.ToColor, color.GradientMode, Color.Empty, 0);
                graphics.DrawImage(this.MinimizeBoxImage, MinRect, 0, 0, this.MinimizeBoxImage.Width, this.MinimizeBoxImage.Height, GraphicsUnit.Pixel, ImgAtt);
                x -= this.ControlBoxSize.Width;
            }

            #region 帮助按钮
            if (this.HelpButton && this.HelpButtonImage != null)
            {
                HelpRect = new Rectangle(x, y, this.controlBoxSize.Width, this.controlBoxSize.Height);
                var color = HelpHover ? this.ControlActivedColor : this.ControlBackColor;
                RadiusDrawable.DrawRadius(graphics, HelpRect, RadiusMode.None, 0, color.FromColor, color.ToColor, color.GradientMode, Color.Empty, 0);
                graphics.DrawImage(this.HelpButtonImage, HelpRect, 0, 0, this.HelpButtonImage.Width, this.HelpButtonImage.Height, GraphicsUnit.Pixel, ImgAtt);
                x -= this.ControlBoxSize.Width;
            }
            #endregion

            #region 其他按钮
            if (this.ControlBoxies != null && this.ImageList != null && this.ImageList.Images.Count > 0)
            {
                foreach (var item in this.ControlBoxies)
                {
                    item.Click -= ControlBoxItem_Click;
                    item.Click += ControlBoxItem_Click;
                    item.ControlActivedColor = this.ControlActivedColor;
                    item.ControlBackColor    = this.ControlBackColor;

                    item.Rectangle = new Rectangle(x, y, this.controlBoxSize.Width, this.controlBoxSize.Height);
                    item.Image     = this.ImageList.Images[item.ImageIndex];

                    item.Draw(graphics);
                    x -= this.ControlBoxSize.Width;
                }
            }
            #endregion
        }
        /// <summary>
        /// 打印出带有边框(和水印)的照片
        /// Author: 王力
        /// 效果:http://img0.ph.126.net/wx-jJ9-8IEURg_ZBu1IApA==/6608567359748454180.jpg
        /// </summary>
        /// <param name="imgSrc"></param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="quality"></param>
        /// <param name="savePath"></param>
        /// <param name="t"></param>
        public void CutAvatarWithPadding(string imgSrc, int x, int y, int width, int height, long quality, string savePath, int t)
        {
            var original      = Image.FromFile(imgSrc);
            var paddingWidth  = (int)((t * 0.2) + t);
            var paddingHeight = (int)((t * 0.5) + t);
            var img           = new Bitmap(paddingWidth, paddingHeight, PixelFormat.Format24bppRgb);

            //var img = new Bitmap(t, t, PixelFormat.Format24bppRgb);
            try
            {
                img.MakeTransparent(img.GetPixel(0, 0));
                //img.SetResolution(paddingWidth, paddingHeight);
                //img.SetResolution(t, t);
                using (var gr = Graphics.FromImage(img))
                {
                    if (original.RawFormat.Equals(ImageFormat.Jpeg) || original.RawFormat.Equals(ImageFormat.Png) ||
                        original.RawFormat.Equals(ImageFormat.Bmp))
                    {
                        //gr.Clear(Color.Transparent);
                        gr.Clear(Color.White);
                    }
                    if (original.RawFormat.Equals(ImageFormat.Gif))
                    {
                        gr.Clear(Color.White);
                    }

                    gr.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                    gr.SmoothingMode      = SmoothingMode.AntiAlias;
                    gr.CompositingQuality = CompositingQuality.HighQuality;
                    gr.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                    gr.TextRenderingHint  = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;

                    using (var attribute = new ImageAttributes())
                    {
                        attribute.SetWrapMode(WrapMode.TileFlipXY);
                        //gr.DrawImage(original, new Rectangle(0, 0, t, t), x, y, width, height, GraphicsUnit.Pixel, attribute);
                        gr.DrawImage(original, new Rectangle(20, 20, t, t), x, y, width, height, GraphicsUnit.Pixel,
                                     attribute);
                    }

                    //var bordcolor = Color.Red;
                    ////var bordwidth = Convert.ToInt32(img.Width * 0.1);
                    ////var bordheight = Convert.ToInt32(img.Height * 0.1);

                    //var bordwidth = 200;
                    //var bordheight =200;

                    //var newheight = img.Height + bordheight;
                    //var newwidth = img.Width + bordwidth;

                    //using (var attribute = new ImageAttributes())
                    //{
                    //    attribute.SetWrapMode(WrapMode.TileFlipXY);
                    //    gr.DrawImage(original, new Rectangle(0, 0, t, t), x, y, width, height, GraphicsUnit.Pixel,
                    //        attribute);
                    //    gr.DrawLine(new Pen(bordcolor, bordheight), 0, 0, newwidth, 0);
                    //    gr.DrawLine(new Pen(bordcolor, bordheight), 0, newheight, newwidth, newheight);
                    //}
                    //水印 http://www.codeproject.com/Tips/323990/How-to-Create-watermarked-images-in-csharp-asp-net
                    //gr.DrawString("这是一个测试", new Font("Verdana", 14, FontStyle.Bold), new SolidBrush(Color.Beige), x: (img.Width / 2), y: (img.Height / 2));
                    gr.DrawString(@"胸有激雷而面如平湖者", new Font("Verdana", 14, FontStyle.Bold), new SolidBrush(Color.Tomato), x: 0, y: img.Height - 80);
                    gr.DrawString(@"可拜上将军也!", new Font("Verdana", 14, FontStyle.Bold), new SolidBrush(Color.Tomato), x: 0, y: img.Height - 60);
                }
                var myImageCodecInfo = GetEncoderInfo("image/jpeg");
                if (original.RawFormat.Equals(ImageFormat.Jpeg))
                {
                    myImageCodecInfo = GetEncoderInfo("image/jpeg");
                }
                else if (original.RawFormat.Equals(ImageFormat.Png))
                {
                    myImageCodecInfo = GetEncoderInfo("image/png");
                }
                else if (original.RawFormat.Equals(ImageFormat.Gif))
                {
                    myImageCodecInfo = GetEncoderInfo("image/gif");
                }
                else if (original.RawFormat.Equals(ImageFormat.Bmp))
                {
                    myImageCodecInfo = GetEncoderInfo("image/bmp");
                }

                var myEncoder           = Encoder.Quality;
                var myEncoderParameters = new EncoderParameters(1);
                var myEncoderParameter  = new EncoderParameter(myEncoder, quality);
                myEncoderParameters.Param[0] = myEncoderParameter;
                img.Save(savePath, myImageCodecInfo, myEncoderParameters);
                original.Dispose();
                img.Dispose();
            }
            catch (Exception ex)
            {
                NBCMSLoggerManager.Error("MediaController:cutAvatar,KeyWord:" + savePath);
                NBCMSLoggerManager.Error(ex.Message);
                NBCMSLoggerManager.Error(ex.Source);
                original.Dispose();
                img.Dispose();
            }
            finally
            {
                original.Dispose();
                img.Dispose();
            }
        }
Example #21
0
	public static void Main(string[] args)
	{	
		Graphics.DrawImageAbort imageCallback;
		Bitmap outbmp = new Bitmap (600, 600);				
		Bitmap bmp = new Bitmap("../../Test/System.Drawing/bitmaps/almogaver32bits.bmp");
		Graphics dc = Graphics.FromImage (outbmp);        
		SolidBrush br = new SolidBrush(Color.White);
		Bitmap img = bmp.Clone (new Rectangle (0,0, 60,60) , PixelFormat.Format32bppArgb);									
		
		ImageAttributes imageAttr = new ImageAttributes();
		
		Bitmap	bmpred = new Bitmap (100,100, PixelFormat.Format32bppArgb);		
		Graphics gr = Graphics.FromImage (bmpred);		
		
		/* Sample drawing*/
		Pen cyan = new Pen(Color.Cyan, 0);
		Pen green = new Pen(Color.Green, 0);
		Pen pink = new Pen(Color.Pink, 0);			
		Pen blue = new Pen(Color.Blue, 0);			
		gr.DrawLine(cyan, 10.0F, 10.0F, 90.0F, 90.0F);
		gr.DrawLine(pink, 10.0F, 30.0F, 90.0F, 30.0F);
		gr.DrawLine(green, 10.0F, 50.0F, 90.0F, 50.0F);
		gr.DrawRectangle (blue, 10.0F, 10.0F, 80.0F, 80.0F);				
		
		/* Draw image without any imageattributes*/		
		dc.DrawImage (bmpred, 0,0);				
		dc.DrawString ("Sample drawing", new Font ("Arial", 8), br,  10, 100);				
		
		/* Remmaping colours */
		ColorMap[] clr = new ColorMap[1];	
		clr[0] = new ColorMap(); 
		clr[0].OldColor = Color.Blue;
		clr[0].NewColor = Color.Yellow;	
		
		imageAttr.SetRemapTable (clr, ColorAdjustType.Bitmap);					
		dc.DrawImage (bmpred, new Rectangle (100, 0, 100,100), 0,0, 100,100, GraphicsUnit.Pixel, imageAttr);			
		dc.DrawString ("Remapping colors", new Font ("Arial", 8), br,  110, 100);				
		
		/* Gamma correction on*/
		imageAttr = new ImageAttributes();
		imageAttr.SetGamma (2);		
		dc.DrawImage (bmpred, new Rectangle (200, 0, 100,100), 0,0, 
			100,100, GraphicsUnit.Pixel, imageAttr);
			
		dc.DrawString ("Gamma corrected", new Font ("Arial", 8), br,  210, 100);				
		
		/* WrapMode: TitleX */
		imageAttr = new ImageAttributes();	
		imageAttr.SetWrapMode (WrapMode.TileFlipX);	
		
		dc.DrawImage (bmpred, new Rectangle (0, 120, 200, 200), 0,0, 
			200, 200, GraphicsUnit.Pixel, imageAttr);					
			
		dc.DrawString ("WrapMode.TileFlipX", new Font ("Arial", 8), br,  10, 320);								
			
		/* WrapMode: TitleY */		
		imageAttr.SetWrapMode (WrapMode.TileFlipY);	
		
		dc.DrawImage (bmpred, new Rectangle (200, 120, 200, 200), 0,0, 
			200, 200, GraphicsUnit.Pixel, imageAttr);				
			
		dc.DrawString ("WrapMode.TileFlipY", new Font ("Arial", 8), br,  210, 320);											
			
		/* WrapMode: TitleXY */		
		imageAttr.SetWrapMode (WrapMode.TileFlipXY);	
		
		dc.DrawImage (bmpred, new Rectangle (400, 120, 200, 200), 0,0, 
			200, 200, GraphicsUnit.Pixel, imageAttr);				
			
		dc.DrawString ("WrapMode.TileFlipXY", new Font ("Arial", 8), br,  410, 320);														
		
		outbmp.Save("imageattributes.bmp", ImageFormat.Bmp);				
		
	}
    public string GenerateImage(string savePath, string sPhysicalPath, string sOrgFileName, string sImageFileName, ImageFormat oFormat, int widthnew, int heightnew)
    {
        string filename = sOrgFileName.Substring(0, sOrgFileName.LastIndexOf("."));

        try
        {
            if (oFormat != ImageFormat.Gif)
            {
                Size thumsize             = new Size();
                System.Drawing.Image oImg = System.Drawing.Image.FromFile(sPhysicalPath + @"\" + sOrgFileName);
                if (oImg.Width > widthnew)
                {
                    thumsize.Width  = widthnew;
                    thumsize.Height = heightnew;
                }
                else
                {
                    thumsize.Width  = oImg.Width;
                    thumsize.Height = oImg.Height;
                }
                System.Drawing.Image oThumbNail = new Bitmap(thumsize.Width, thumsize.Height, oImg.PixelFormat);

                Graphics oGraphic = Graphics.FromImage(oThumbNail);
                oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                oGraphic.SmoothingMode      = SmoothingMode.AntiAlias;
                oGraphic.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                oGraphic.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                ImageAttributes attribute = new ImageAttributes();
                attribute.SetWrapMode(WrapMode.TileFlipXY);
                oGraphic.DrawImage(oImg, new Rectangle(new Point(0, 0), thumsize), 0, 0, oImg.Width, oImg.Height, GraphicsUnit.Pixel, attribute);

                oImg.Dispose();
                GC.Collect();
                GC.WaitForPendingFinalizers();

                // First delete the image
                FileInfo fi = new FileInfo(sPhysicalPath + sOrgFileName);
                fi.Attributes = FileAttributes.Normal;
                fi.Delete();

                // Then resave it with its new size
                oThumbNail.Save(sPhysicalPath + sImageFileName, oFormat);

                // Empty Garbage
                oGraphic.Dispose();
                oThumbNail.Dispose();
                GC.Collect();
                sb.Append(sPhysicalPath + sImageFileName);
            }
            else
            {
                Size   thumsize = new Size();
                Bitmap bm       = new Bitmap(sPhysicalPath + @"\" + sOrgFileName);

                if (bm.Width > widthnew)
                {
                    thumsize.Width  = widthnew;
                    thumsize.Height = heightnew;
                }
                else
                {
                    thumsize.Width  = bm.Width;
                    thumsize.Height = bm.Height;
                }

                Bitmap   bm2 = new Bitmap(thumsize.Width, thumsize.Height, PixelFormat.Format64bppArgb);
                Graphics g2  = Graphics.FromImage(bm2);

                Rectangle subRect = new Rectangle(0, 0, thumsize.Width, thumsize.Height);
                g2.DrawImage(bm, subRect);
                bm.Dispose();
                GC.Collect();
                GC.WaitForPendingFinalizers();

                bm2.Save(sPhysicalPath + sImageFileName, ImageFormat.Jpeg);
                g2.Dispose();
                bm2.Dispose();
                GC.Collect();

                sb.Append(sPhysicalPath + sImageFileName);
            }
        }
        catch (Exception e1) { sb.Append(e1.Message); }
        return(sb.ToString());
    }
Example #23
0
        public IActionResult Index(string widthHeight)
        {
            try
            {
                List <string> imageSizeString = new List <string>();
                if (widthHeight.Contains('x'))
                {
                    imageSizeString = widthHeight.Split('x').ToList();
                }
                else if (widthHeight.Contains('X'))
                {
                    imageSizeString = widthHeight.Split('X').ToList();
                }
                else if (widthHeight.Contains('×'))
                {
                    imageSizeString = widthHeight.Split('×').ToList();
                }

                if (imageSizeString.Count != 2)
                {
                    return(RedirectToAction("Error", new { message = "Values should not be more than two: width and height." }));
                }

                int    width = 0; int height = 0;
                string widthString      = imageSizeString[0];
                string heightString     = imageSizeString[1];
                bool   canConvertWidth  = int.TryParse(widthString, out width);
                bool   canConvertHeight = int.TryParse(heightString, out height);

                if (!canConvertHeight || !canConvertWidth)
                {
                    return(RedirectToAction("Error", new { message = "Values should be numerical." }));
                }

                var   rand             = new Random();
                var   puppyImageList   = Directory.GetFiles(_hostEnvironment.WebRootPath + @"\images", "*.jpg");
                Image randomPuppyImage = Image.FromFile(puppyImageList[rand.Next(puppyImageList.Length)]);
                var   destRect         = new Rectangle(0, 0, width, height);
                var   destImage        = new Bitmap(width, height);

                destImage.SetResolution(randomPuppyImage.HorizontalResolution, randomPuppyImage.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(WrapMode.TileFlipXY);
                        graphics.DrawImage(randomPuppyImage, destRect, 0, 0, randomPuppyImage.Width, randomPuppyImage.Height, GraphicsUnit.Pixel, wrapMode);
                    }
                }

                var selectedImage = _hostEnvironment.WebRootPath + @"\images\selectedImage\" + widthHeight + ".jpg";
                var outputStream  = new MemoryStream();
                destImage.Save(selectedImage, ImageFormat.Jpeg);
                string imgSrc = "../images/selectedImage/" + widthHeight + ".jpg";
                return(View((object)imgSrc));
            }
            catch (Exception ex)
            {
                return(RedirectToAction("Error"));

                throw;
            }
        }
        private static ProcessImageResult processImage(Stream istm, Stream ostm, ProcessImageSettings s)
        {
            using (var img = Image.FromStream(istm, s.ColorProfileMode <= ColorProfileMode.NormalizeAndEmbed, false))
            {
                if (s.FrameIndex > 0)
                {
                    var fd = img.RawFormat.Guid == ImageFormat.Gif.Guid ? FrameDimension.Time : FrameDimension.Page;
                    if (img.GetFrameCount(fd) > s.FrameIndex)
                    {
                        img.SelectActiveFrame(fd, s.FrameIndex);
                    }
                    else
                    {
                        throw new ArgumentOutOfRangeException("Invalid Frame Index");
                    }
                }

                if (s.OrientationMode == OrientationMode.Normalize)
                {
                    img.ExifRotate();
                }

                s = s.Clone();
                s.Fixup(img.Width, img.Height);

                bool alpha       = ((ImageFlags)img.Flags).HasFlag(ImageFlags.HasAlpha);
                var  pixelFormat = alpha && s.MatteColor.A < byte.MaxValue ? GdiPixelFormat.Format32bppArgb : GdiPixelFormat.Format24bppRgb;
                var  mode        = s.Interpolation.WeightingFunction.Support <0.1 ? InterpolationMode.NearestNeighbor :
                                                                              s.Interpolation.WeightingFunction.Support <1.0 ? s.ScaleRatio> 1.0 ? InterpolationMode.Bilinear : InterpolationMode.NearestNeighbor :
                                                                              s.Interpolation.WeightingFunction.Support> 1.0 ? s.ScaleRatio > 1.0 || s.Interpolation.Blur > 1.0 ? InterpolationMode.HighQualityBicubic : InterpolationMode.Bicubic :
                                   s.ScaleRatio > 1.0 ? InterpolationMode.HighQualityBilinear : InterpolationMode.Bilinear;

                var src  = img;
                var crop = s.Crop;
                if (s.HybridScaleRatio > 1d && (mode == InterpolationMode.HighQualityBicubic || mode == InterpolationMode.HighQualityBilinear))
                {
                    int intw = (int)Math.Ceiling(img.Width / s.HybridScaleRatio);
                    int inth = (int)Math.Ceiling(img.Height / s.HybridScaleRatio);

                    var bmp = new Bitmap(intw, inth);
                    using (var gfx = Graphics.FromImage(bmp))
                    {
                        gfx.PixelOffsetMode = PixelOffsetMode.Half;
                        gfx.CompositingMode = CompositingMode.SourceCopy;
                        gfx.DrawImage(img, new Rectangle(0, 0, intw, inth), crop.X, crop.Y, crop.Width, crop.Height, GraphicsUnit.Pixel);
                    }

                    img.Dispose();
                    src  = bmp;
                    crop = new Rectangle(0, 0, intw, inth);
                }

                using (src)
                    using (var iat = new ImageAttributes())
                        using (var bmp = new Bitmap(s.Width, s.Height, pixelFormat))
                            using (var gfx = Graphics.FromImage(bmp))
                            {
                                iat.SetWrapMode(WrapMode.TileFlipXY);
                                gfx.PixelOffsetMode   = PixelOffsetMode.Half;
                                gfx.CompositingMode   = CompositingMode.SourceCopy;
                                gfx.InterpolationMode = mode;

                                if ((alpha || s.InnerRect != s.OuterRect) && !s.MatteColor.IsEmpty)
                                {
                                    gfx.Clear(s.MatteColor);
                                    gfx.CompositingMode    = CompositingMode.SourceOver;
                                    gfx.CompositingQuality = CompositingQuality.GammaCorrected;
                                }

                                gfx.DrawImage(src, s.InnerRect, crop.X, crop.Y, crop.Width, crop.Height, GraphicsUnit.Pixel, iat);

                                switch (s.SaveFormat)
                                {
                                case FileFormat.Bmp:
                                    bmp.Save(ostm, ImageFormat.Bmp);
                                    break;

                                case FileFormat.Tiff:
                                    using (var encoderParams = new EncoderParameters(1))
                                        using (var param = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionNone))
                                        {
                                            encoderParams.Param[0] = param;
                                            bmp.Save(ostm, tiffCodec, encoderParams);
                                        }
                                    break;

                                case FileFormat.Jpeg:
                                    using (var encoderParams = new EncoderParameters(1))
                                        using (var param = new EncoderParameter(Encoder.Quality, s.JpegQuality))
                                        {
                                            encoderParams.Param[0] = param;
                                            bmp.Save(ostm, jpegCodec, encoderParams);
                                        }
                                    break;

                                default:
                                    if (s.IndexedColor)
                                    {
                                        bmp.Save(ostm, ImageFormat.Gif);
                                    }
                                    else
                                    {
                                        bmp.Save(ostm, ImageFormat.Png);
                                    }
                                    break;
                                }
                            }
            }

            return(new ProcessImageResult {
                Settings = s, Stats = Enumerable.Empty <PixelSourceStats>()
            });
        }
Example #25
0
        public static Image DoThumbnail(Image image, Size size, bool crop, bool transparent, bool rectangle)
        {
            var width      = size.Width;
            var height     = size.Height;
            var realWidth  = image.Width;
            var realHeight = image.Height;

            var thumbnail = new Bitmap(width, height);

            var maxSide = realWidth > realHeight ? realWidth : realHeight;
            var minSide = realWidth < realHeight ? realWidth : realHeight;

            var alignWidth = true;

            if (crop)
            {
                alignWidth = (minSide == realWidth);
            }
            else
            {
                alignWidth = (maxSide == realWidth);
            }

            double scaleFactor = (alignWidth) ? (realWidth / (1.0 * width)) : (realHeight / (1.0 * height));

            if (scaleFactor < 1)
            {
                scaleFactor = 1;
            }

            int locationX, locationY;
            int finalWidth, finalHeigth;

            finalWidth  = (int)(realWidth / scaleFactor);
            finalHeigth = (int)(realHeight / scaleFactor);


            if (rectangle)
            {
                locationY = (int)((height / 2.0) - (finalHeigth / 2.0));
                locationX = (int)((width / 2.0) - (finalWidth / 2.0));

                var rect = new Rectangle(locationX, locationY, finalWidth, finalHeigth);

                using (var graphic = Graphics.FromImage(thumbnail))
                {
                    if (!transparent)
                    {
                        graphic.Clear(Color.White);
                        graphic.SmoothingMode = SmoothingMode.HighQuality;
                    }
                    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphic.PixelOffsetMode   = PixelOffsetMode.HighQuality;

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

                    //graphic.DrawImage(image, rect);
                }
            }
            else
            {
                thumbnail = new Bitmap(finalWidth, finalHeigth);

                using (var graphic = Graphics.FromImage(thumbnail))
                {
                    if (!transparent)
                    {
                        graphic.Clear(Color.White);
                        graphic.SmoothingMode = SmoothingMode.HighQuality;
                    }
                    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphic.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                    graphic.DrawImage(image, 0, 0, finalWidth, finalHeigth);
                }
            }

            return(thumbnail);
        }
Example #26
0
        private async Task processOrder(Order order, Item item)
        {
            char[] seperator = { ';' };
            Config config = new Config();
            int    imWidth, imHeight, textWidth, testHeight;
            string text = "";
            PrivateFontCollection myFontCollection = new PrivateFontCollection();

            int index = Configs.FindIndex(x => x.SKU.Trim() == item.sku);

            if (index < 0)
            {
                return;
            }

            config = Configs[index];
            var destImage = new Bitmap(config.Width, config.Height);

            destImage.SetResolution(500.0F, 500.0F);
            if (config.ImageType == "IMAGE-ONLY")
            {
                string imageFile = config.SourceImage;
                Bitmap image     = new Bitmap(Application.StartupPath + @"\SourceImages\" + imageFile + ".png");
                var    destRect  = new Rectangle(0, 0, config.Width, config.Height);

                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(WrapMode.TileFlipXY);
                        graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
                    }
                    destImage.Save(String.Format("{0}\\{1}_{2}_{3}.png", outputFolder, order.orderNumber, item.orderItemId, item.sku));

                    //destImage.Save(Application.StartupPath + @"\Output\" + order.OrderId + "-" + item.OrderItemId + ".png");
                }
                //MessageBox.Show("Done");
            }
            else
            {
                string[] jsonURLs = order.internalNotes.Split(seperator);

                foreach (string mixedUrl in jsonURLs)
                {
                    int      i           = mixedUrl.IndexOf("https");
                    string[] vs          = mixedUrl.Split(':');
                    string   orderItemId = vs[0];
                    string   jsonFile    = vs[0];
                    destImage = new Bitmap(config.Width, config.Height);
                    //string jsonFile = mixedUrl.Substring(0, i - 1);
                    //string url = mixedUrl.Substring(i, mixedUrl.Length - i);
                    string url = vs[1] + ":" + vs[2];
                    foreach (string file in Directory.GetFiles(Application.StartupPath + @"\tmp"))
                    {
                        File.Delete(file);
                    }
                    using (WebClient wc = new WebClient())
                    {
                        string tmpFilename = Path.GetTempFileName();
                        await wc.DownloadFileTaskAsync(url, tmpFilename);

                        ZipFile.ExtractToDirectory(tmpFilename, Application.StartupPath + @"\tmp");
                    }

                    using (StreamReader reader = new StreamReader(Application.StartupPath + @"\tmp\" + jsonFile + ".json"))
                    {
                        var result = reader.ReadToEnd();

                        Main o = JsonConvert.DeserializeObject <Main>(result);

                        foreach (Area area in o.Version30.CustomizationInfo.Surfaces[0].Areas)
                        {
                            if (area.CustomizationType == "Options")
                            {
                                iconName = area.OptionValue;
                                if (iconName == string.Empty)
                                {
                                }
                                else
                                {
                                    //
                                }
                            }
                            if (area.CustomizationType == "TextPrinting")
                            {
                                //iconName = area.Label;
                                fontFamily = area.FontFamily.ToLower();
                                text       = area.Text;
                                //area.FontFamily;
                                //area.Fill;
                                imWidth  = area.Dimensions.Width;
                                imHeight = area.Dimensions.Height;

                                //area.Position.X;
                                //area.Position.Y;
                                text = area.Text;
                            }
                        }
                        Font myFont;

                        FontFamily myFontFamily = new FontFamily("Arial");
                        bool       systemFont   = true;
                        string     localFont    = Application.StartupPath + @"\Fonts\" + fontFamily + ".ttf";
                        if (File.Exists(localFont))
                        {
                            systemFont = false;
                            myFontCollection.AddFontFile(Application.StartupPath + @"\Fonts\" + fontFamily + ".ttf");
                            myFontFamily = myFontCollection.Families[0];
                        }
                        else
                        {
                            if (fontMap.Keys.Contains(fontFamily))
                            {
                                systemFont = false;
                                myFontCollection.AddFontFile(Application.StartupPath + @"\Fonts\" + fontMap[fontFamily]);
                                myFontFamily = myFontCollection.Families[0];
                            }
                        }
                        if (systemFont)
                        {
                            myFont = new Font(fontFamily, 72.0F);
                        }
                        else
                        {
                            myFont = new Font(myFontFamily, 72.0F);
                        }
                        SizeF layoutSize = new SizeF((float)config.C2_Width, (float)config.C2_Height);
                        SizeF stringSize = new SizeF();
                        var   tempImage = new Bitmap(1, 1);
                        float scaleX, scaleY, scale;

                        using (var g = Graphics.FromImage(destImage))
                        {
                            stringSize = g.MeasureString(text, myFont);
                            scaleX     = layoutSize.Width / stringSize.Width;
                            scaleY     = layoutSize.Height / stringSize.Height;
                            scale      = Math.Min(scaleX, scaleY);
                            float fontSize = 72.0F * scale;
                            if (systemFont)
                            {
                                myFont = new Font(fontFamily, fontSize, FontStyle.Regular, GraphicsUnit.Point);
                            }
                            else
                            {
                                myFont = new Font(myFontFamily, fontSize, FontStyle.Regular, GraphicsUnit.Point);
                            }
                            stringSize = g.MeasureString(text, myFont);
                        }
                        if (iconName == string.Empty || iconName == "None")
                        {
                            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;
                                graphics.FillRectangle(Brushes.White, 0.0F, 0.0F, destImage.Width, destImage.Height);
                                StringFormat stringFormat = new StringFormat();
                                stringFormat.Alignment     = StringAlignment.Center;
                                stringFormat.LineAlignment = StringAlignment.Center;

                                graphics.DrawString(text, myFont, Brushes.Black,
                                                    new Rectangle(0, 0, destImage.Width, destImage.Height), stringFormat);
                                destImage.Save(String.Format("{0}\\{1}_{2}_{3}.png", outputFolder, order.orderNumber, orderItemId, item.sku));
                                //destImage.Save(Application.StartupPath + @"\Output\" + order.OrderId+ "-" + item.OrderItemId + ".png");
                            }
                        }
                        else
                        {
                            string imageFile = config.SourceImage;
                            Bitmap icon      = new Bitmap(Application.StartupPath + @"\SourceImages\Icons\" + iconName + ".png");
                            //Bitmap image = new Bitmap(Application.StartupPath + @"\SourceImages\" + imageFile + ".png");
                            float startX = ((float)destImage.Width - (float)config.C1_Width) / 2.0F;

                            var destRect = new Rectangle((int)startX, (int)config.C1_StartY,
                                                         (int)config.C1_Width, (int)((float)config.C1_Width / (float)icon.Width * (float)icon.Height));

                            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(WrapMode.TileFlipXY);
                                    graphics.DrawImage(icon, destRect, 0, 0, icon.Width, icon.Height, GraphicsUnit.Pixel, wrapMode);
                                }
                                StringFormat stringFormat = new StringFormat();
                                stringFormat.Alignment     = StringAlignment.Center;
                                stringFormat.LineAlignment = StringAlignment.Near;
                                graphics.DrawString(text, myFont, Brushes.Black,
                                                    new Rectangle(0, (int)config.C2_StartY, destImage.Width, destImage.Height), stringFormat);
                                destImage.Save(String.Format("{0}\\{1}_{2}_{3}.png", outputFolder, order.orderNumber, orderItemId, item.sku));

                                //destImage.Save(Application.StartupPath + @"\Output\" + order.OrderId + "-" + item.OrderItemId + ".png");
                            }
                        }



                        //fileContent = reader.ReadToEnd();
                    }

                    // get json from URL , local file for testing
                }
            }
        }
Example #27
0
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="factory">
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class containing
        /// the image to process.
        /// </param>
        /// <returns>
        /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public Image ProcessImage(ImageFactory factory)
        {
            Bitmap newImage = null;
            Image  image    = factory.Image;

            try
            {
                int        sourceWidth  = image.Width;
                int        sourceHeight = image.Height;
                RectangleF rectangleF;
                CropLayer  cropLayer = this.DynamicParameter;

                if (cropLayer.CropMode == CropMode.Percentage)
                {
                    // Fix for whole numbers.
                    float percentageLeft   = cropLayer.Left > 1 ? cropLayer.Left / 100 : cropLayer.Left;
                    float percentageRight  = cropLayer.Right > 1 ? cropLayer.Right / 100 : cropLayer.Right;
                    float percentageTop    = cropLayer.Top > 1 ? cropLayer.Top / 100 : cropLayer.Top;
                    float percentageBottom = cropLayer.Bottom > 1 ? cropLayer.Bottom / 100 : cropLayer.Bottom;

                    // Work out the percentages.
                    float left   = percentageLeft * sourceWidth;
                    float top    = percentageTop * sourceHeight;
                    float width  = percentageRight < 1 ? (1 - percentageLeft - percentageRight) * sourceWidth : sourceWidth;
                    float height = percentageBottom < 1 ? (1 - percentageTop - percentageBottom) * sourceHeight : sourceHeight;

                    rectangleF = new RectangleF(left, top, width, height);
                }
                else
                {
                    rectangleF = new RectangleF(cropLayer.Left, cropLayer.Top, cropLayer.Right, cropLayer.Bottom);
                }

                Rectangle rectangle = Rectangle.Round(rectangleF);

                if (rectangle.X < sourceWidth && rectangle.Y < sourceHeight)
                {
                    if (rectangle.Width > (sourceWidth - rectangle.X))
                    {
                        rectangle.Width = sourceWidth - rectangle.X;
                    }

                    if (rectangle.Height > (sourceHeight - rectangle.Y))
                    {
                        rectangle.Height = sourceHeight - rectangle.Y;
                    }

                    newImage = new Bitmap(rectangle.Width, rectangle.Height, PixelFormat.Format32bppPArgb);
                    newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

                    using (Graphics graphics = Graphics.FromImage(newImage))
                    {
                        GraphicsHelper.SetGraphicsOptions(graphics);

                        // An unwanted border appears when using InterpolationMode.HighQualityBicubic to resize the image
                        // as the algorithm appears to be pulling averaging detail from surrounding pixels beyond the edge
                        // of the image. Using the ImageAttributes class to specify that the pixels beyond are simply mirror
                        // images of the pixels within solves this problem.
                        using (ImageAttributes wrapMode = new ImageAttributes())
                        {
                            wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                            graphics.DrawImage(
                                image,
                                new Rectangle(0, 0, rectangle.Width, rectangle.Height),
                                rectangle.X,
                                rectangle.Y,
                                rectangle.Width,
                                rectangle.Height,
                                GraphicsUnit.Pixel,
                                wrapMode);
                        }
                    }

                    // Reassign the image.
                    image.Dispose();
                    image = newImage;

                    if (factory.PreserveExifData && factory.ExifPropertyItems.Any())
                    {
                        // Set the width EXIF data.
                        factory.SetPropertyItem(ExifPropertyTag.ImageWidth, (ushort)image.Width);

                        // Set the height EXIF data.
                        factory.SetPropertyItem(ExifPropertyTag.ImageHeight, (ushort)image.Height);
                    }
                }
            }
            catch (Exception ex)
            {
                newImage?.Dispose();

                throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex);
            }

            return(image);
        }
Example #28
0
        public static Image Resize(this Image image, int width, int height, bool crop = false)
        {
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }

            float imageWidth  = image.Width;
            float imageHeight = image.Height;

            if (image.Width == 0 || image.Height == 0 || width == 0 || height == 0)
            {
                return(new Bitmap(width, height));
            }

            var aspect      = imageWidth / imageHeight;
            var deltaWidth  = width / imageWidth;
            var deltaHeight = height / imageHeight;

            float newHeight;
            float newWidth;

            if (deltaWidth < deltaHeight)
            {
                newWidth  = width;
                newHeight = newWidth / aspect;
            }
            else
            {
                newHeight = height;
                newWidth  = aspect * newHeight;
            }

            Rectangle destRect;
            Bitmap    destImage;

            if (crop)
            {
                destRect  = new Rectangle(0, 0, (int)newWidth, (int)newHeight);
                destImage = new Bitmap((int)newWidth, (int)newHeight);
            }
            else
            {
                destRect = new Rectangle((int)((width - newWidth) / 2), (int)((height - newHeight) / 2), (int)newWidth,
                                         (int)newHeight);
                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(WrapMode.TileFlipXY);
                    graphics.DrawImage(image, destRect, 0, 0, imageWidth, imageHeight, GraphicsUnit.Pixel, wrapMode);
                }
            }

            return(destImage);
        }
Example #29
0
        protected override RequestedAction PreRenderImage(ImageState s)
        {
            //Skip this when we are doing simulations
            if (s.destGraphics == null)
            {
                return(RequestedAction.None);
            }

            s.ApplyCropping();
            s.EnsurePreRenderBitmap();

            //Parse carve algorithm kind
            FilterType ftype = s.settings.Get <FilterType>("carve", FilterType.None);

            if ("true".Equals(s.settings["carve"], StringComparison.OrdinalIgnoreCase))
            {
                ftype = FilterType.Prewitt;
            }
            if (string.IsNullOrEmpty(s.settings["carve"]) && s.settings.Mode == FitMode.Carve)
            {
                ftype = FilterType.Prewitt;
            }

            //If we have carve data
            CarveDataPlotter carveData = s.Data.ContainsKey(CarveData) ? (s.Data[CarveData] as CarveDataPlotter) : null;

            if (carveData != null && ftype == FilterType.None)
            {
                ftype = FilterType.Prewitt;
            }

            RectangleF copyRect = s.copyRect;

            if (carveData != null)
            {
                copyRect = new RectangleF(new PointF(0, 0), s.sourceBitmap.Size);
            }

            if (ftype == FilterType.None)
            {
                return(RequestedAction.None);                          //Only override rendering when carving is requested.
            }
            //The minimum dimensions of the temporary bitmap.
            SizeF targetSize = PolygonMath.getParallelogramSize(s.layout["image"]);

            targetSize = new SizeF((float)Math.Ceiling(targetSize.Width), (float)Math.Ceiling(targetSize.Height));


            //The size of the temporary bitmap.
            //We want it larger than the size we'll use on the final copy, so we never upscale it
            //- but we also want it as small as possible so processing is fast.
            SizeF tempSize   = PolygonMath.ScaleOutside(targetSize, copyRect.Size);
            int   tempWidth  = (int)Math.Ceiling(tempSize.Width);
            int   tempHeight = (int)Math.Ceiling(tempSize.Height);

            //The intermediate and seam carved files
            string tempFile       = Path.GetTempFileName();
            string outputTempFile = Path.GetTempFileName();

            try {
                try {
                    //Create a temporary bitmap that is 'halfway resized', so we can efficiently perform seam carving.

                    //Unless it's already been done for us by FreeImageResize or something
                    if (s.preRenderBitmap != null && (tempWidth - s.preRenderBitmap.Width < 50 && tempHeight - s.preRenderBitmap.Height < 50))
                    {
                        s.preRenderBitmap.Save(tempFile, ImageFormat.Bmp);
                        tempWidth  = s.preRenderBitmap.Width;
                        tempHeight = s.preRenderBitmap.Height;
                    }
                    else
                    {
                        //Create the temporary bitmap and graphics.
                        using (Bitmap temp = new Bitmap(tempWidth, tempHeight, PixelFormat.Format32bppArgb))
                            using (Graphics g = Graphics.FromImage(temp))
                                using (ImageAttributes ia = new ImageAttributes()) {
                                    //High quality everthing
                                    g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                                    g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                                    g.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                                    g.CompositingMode    = CompositingMode.SourceOver;
                                    ia.SetWrapMode(WrapMode.TileFlipXY);
                                    if (s.preRenderBitmap != null)
                                    {
                                        g.DrawImage(s.preRenderBitmap, new Rectangle(0, 0, tempWidth, tempHeight), 0, 0, s.preRenderBitmap.Width, s.preRenderBitmap.Height, GraphicsUnit.Pixel, ia);
                                    }
                                    else
                                    {
                                        g.DrawImage(s.sourceBitmap, new Rectangle(0, 0, tempWidth, tempHeight), copyRect.X, copyRect.Y, copyRect.Width, copyRect.Height, GraphicsUnit.Pixel, ia);
                                    }
                                    g.Flush(FlushIntention.Flush);
                                    //Save
                                    temp.Save(tempFile, ImageFormat.Bmp);
                                }
                    }

                    string maskFile = carveData != null?Path.GetTempFileName() : null;

                    try {
                        if (carveData != null)
                        {
                            carveData.SaveBitmapAs(maskFile, tempWidth, tempHeight);
                        }

                        Size    intTargetSize = new Size((int)targetSize.Width, (int)targetSize.Height);
                        CairJob job           = new CairJob();
                        if (maskFile != null)
                        {
                            job.WeightPath = maskFile;
                        }
                        job.SourcePath = tempFile;
                        job.DestPath   = outputTempFile;
                        job.Size       = intTargetSize;
                        job.Filter     = ftype;
                        job.Timeout    = 5000;
                        cair.CairyIt(job);
                    } finally {
                        if (maskFile != null)
                        {
                            File.Delete(maskFile);
                        }
                    }
                } finally {
                    File.Delete(tempFile);
                }

                //Dispose old intermediate bitmap first
                if (s.preRenderBitmap != null)
                {
                    s.preRenderBitmap.Dispose();
                }

                //Load the new intermediate file from disk
                s.preRenderBitmap = new Bitmap(outputTempFile);
                s.preRenderBitmap.MakeTransparent();

                //Reset the s.copyRect to match the new bitmap
                s.copyRect = new RectangleF(new PointF(0, 0), new SizeF(targetSize.Width, targetSize.Height));
            } finally {
                File.Delete(outputTempFile);
            }

            return(RequestedAction.Cancel);
        }
Example #30
0
 /// <summary>
 /// Initializes a new layer, and downloads and parses the service description
 /// </summary>
 /// <remarks>In and ASP.NET application the service description is automatically cached for 24 hours when not specified</remarks>
 /// <param name="layername">Layername</param>
 /// <param name="url">Url of WMS server's Capabilities</param>
 public TiledWmsLayer(string layername, string url)
     : this(layername, url, new TimeSpan(24, 0, 0))
 {
     _ImageAttributes.SetWrapMode(WrapMode.TileFlipXY);
 }
Example #31
0
    protected override void Apply(ImageProcessingActionExecuteArgs args)
    {
        Bitmap result = null;

        try
        {
            // Create the result image
            result = new Bitmap(350, 350, CodeCarvings.Piczard.CommonData.DefaultPixelFormat);

            // Set the right image resolution (DPI)
            ImageHelper.SetImageResolution(result, args.ImageProcessingJob.OutputResolution);

            using (Graphics g = Graphics.FromImage(result))
            {
                // Use the max quality
                ImageHelper.SetGraphicsMaxQuality(g);

                if ((args.IsLastAction) && (!args.AppliedImageBackColorValue.HasValue))
                {
                    // Optimization (not mandatory)
                    // This is the last filter action and the ImageBackColor has not been yet applied...
                    // Apply the ImageBackColor now to save RAM & CPU
                    args.ApplyImageBackColor(g);
                }

                using (ImageAttributes imageAttributes = new ImageAttributes())
                {
                    // Important
                    imageAttributes.SetWrapMode(WrapMode.TileFlipXY);

                    // Draw the scaled image
                    Rectangle destinationRectangle = new Rectangle(75, 52, 200, 200);
                    using (Image resizedImage = new FixedCropConstraint(GfxUnit.Pixel, destinationRectangle.Size).GetProcessedImage(args.Image))
                    {
                        g.DrawImage(resizedImage, destinationRectangle, 0, 0, resizedImage.Width, resizedImage.Height, GraphicsUnit.Pixel, imageAttributes);

                        // Draw the reflection
                        destinationRectangle = new Rectangle(75, 252, 200, 98);
                        using (Image flippedImage = ImageTransformation.FlipVertical.GetProcessedImage(resizedImage))
                        {
                            g.DrawImage(flippedImage, destinationRectangle, 0, 0, flippedImage.Width, flippedImage.Height, GraphicsUnit.Pixel, imageAttributes);
                        }
                    }

                    // Draw the mask
                    destinationRectangle = new Rectangle(0, 0, result.Width, result.Height);
                    using (LoadedImage loadedImage = ImageArchiver.LoadImage("~/repository/filters/MyCustomFilter1Mask.png"))
                    {
                        g.DrawImage(loadedImage.Image, destinationRectangle, 0, 0, loadedImage.Size.Width, loadedImage.Size.Height, GraphicsUnit.Pixel, imageAttributes);
                    }
                }

                // Draw the text
                string         text           = "Generated by 'MyCustomFilter1' on " + DateTime.Now.ToString();
                FontDefinition fontDefinition = new FontDefinition();
                fontDefinition.Size = 12; //12px
                using (Font font = fontDefinition.GetFont())
                {
                    // Setup the custom parameters
                    g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

                    using (StringFormat stringFormat = new StringFormat())
                    {
                        SizeF textSize      = g.MeasureString(text, font, int.MaxValue, stringFormat);
                        Size  pixelTextSize = new Size(Convert.ToInt32(Math.Round(textSize.Width)), Convert.ToInt32(Math.Round(textSize.Height)));

                        // Calculate the text position
                        Point location = new Point((result.Width - pixelTextSize.Width) / 2, result.Height - 14 - pixelTextSize.Height);

                        // Draw the text
                        using (Brush brush = new SolidBrush(ColorTranslator.FromHtml("#5b615d")))
                        {
                            g.DrawString(text, font, brush, location, stringFormat);
                        }
                    }
                }
            }

            // Return the image
            args.Image = result;
        }
        catch
        {
            // An error has occurred...

            // Release the resources
            if (result != null)
            {
                result.Dispose();
                result = null;
            }

            // Re-throw the exception
            throw;
        }
    }
    public string GenerateImage(string savePath, string sPhysicalPath, string sOrgFileName, string sImageFileName, ImageFormat oFormat, int widthnew, int heightnew)
    {
        string filename = sOrgFileName.Substring(0, sOrgFileName.LastIndexOf("."));
        Size thumsize = new Size(widthnew, heightnew);
        try
        {
            if (oFormat != ImageFormat.Gif)
            {
                System.Drawing.Image oImg = System.Drawing.Image.FromFile(sPhysicalPath + @"\" + sOrgFileName);
                System.Drawing.Image oThumbNail = new Bitmap(thumsize.Width, thumsize.Height, oImg.PixelFormat);

                Graphics oGraphic = Graphics.FromImage(oThumbNail);
                oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                oGraphic.SmoothingMode = SmoothingMode.AntiAlias;
                oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                oGraphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                ImageAttributes attribute = new ImageAttributes();
                attribute.SetWrapMode(WrapMode.TileFlipXY);
                oGraphic.DrawImage(oImg, new Rectangle(new Point(0, 0), thumsize), 0, 0, oImg.Width, oImg.Height, GraphicsUnit.Pixel, attribute);

                oImg.Dispose();
                GC.Collect();
                GC.WaitForPendingFinalizers();

                // First delete the image
                //FileInfo fi = new FileInfo(sPhysicalPath + sOrgFileName);
                //fi.Attributes = FileAttributes.Normal;
                //fi.Delete();

                // Then resave it with its new size
                oThumbNail.Save(sPhysicalPath + sImageFileName, oFormat);

                // Empty Garbage
                oGraphic.Dispose();
                oThumbNail.Dispose();
                GC.Collect();
                sb.Append(sPhysicalPath + sImageFileName);
            }
            else
            {
                Bitmap bm = new Bitmap(sPhysicalPath + @"\" + sOrgFileName);
                Bitmap bm2 = new Bitmap(thumsize.Width, thumsize.Height, PixelFormat.Format64bppArgb);
                Graphics g2 = Graphics.FromImage(bm2);

                Rectangle subRect = new Rectangle(0, 0, thumsize.Width, thumsize.Height);
                g2.DrawImage(bm, subRect);
                bm.Dispose();
                GC.Collect();
                GC.WaitForPendingFinalizers();

                bm2.Save(sPhysicalPath + sImageFileName, ImageFormat.Jpeg);
                g2.Dispose();
                bm2.Dispose();
                GC.Collect();

                sb.Append(sPhysicalPath + sImageFileName);

            }
        }
        catch (Exception e1) { sb.Append(e1.Message); }
        return sb.ToString();
    }
Example #33
0
        /// <summary>
        ///     Scale the bitmap, keeping aspect ratio, but the canvas will always have the specified size.
        /// </summary>
        /// <param name="sourceImage">Image to scale</param>
        /// <param name="maintainAspectRatio">true to maintain the aspect ratio</param>
        /// <param name="canvasUseNewSize">Makes the image maintain aspect ratio, but the canvas get's the specified size</param>
        /// <param name="backgroundColor">The color to fill with, or Color.Empty to take the default depending on the pixel format</param>
        /// <param name="newWidth">new width</param>
        /// <param name="newHeight">new height</param>
        /// <param name="matrix">Matrix</param>
        /// <param name="interpolationMode">InterpolationMode</param>
        /// <returns>a new bitmap with the specified size, the source-Image scaled to fit with aspect ratio locked</returns>
        public static Bitmap Resize(this Image sourceImage, bool maintainAspectRatio, bool canvasUseNewSize, Color backgroundColor, int newWidth, int newHeight, Matrix matrix, InterpolationMode interpolationMode = InterpolationMode.HighQualityBicubic)
        {
            var destX = 0;
            var destY = 0;

            var nPercentW = newWidth / (float)sourceImage.Width;
            var nPercentH = newHeight / (float)sourceImage.Height;

            if (maintainAspectRatio)
            {
                if ((int)nPercentW == 1 || (int)nPercentH != 0 && nPercentH < nPercentW)
                {
                    nPercentW = nPercentH;
                    if (canvasUseNewSize)
                    {
                        destX = Math.Max(0, Convert.ToInt32((newWidth - sourceImage.Width * nPercentW) / 2));
                    }
                }
                else
                {
                    nPercentH = nPercentW;
                    if (canvasUseNewSize)
                    {
                        destY = Math.Max(0, Convert.ToInt32((newHeight - sourceImage.Height * nPercentH) / 2));
                    }
                }
            }

            var destWidth  = (int)(sourceImage.Width * nPercentW);
            var destHeight = (int)(sourceImage.Height * nPercentH);

            if (newWidth == 0)
            {
                newWidth = destWidth;
            }
            if (newHeight == 0)
            {
                newHeight = destHeight;
            }
            Bitmap newBitmap;

            if (maintainAspectRatio && canvasUseNewSize)
            {
                newBitmap = BitmapFactory.CreateEmpty(newWidth, newHeight, sourceImage.PixelFormat, backgroundColor, sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
                matrix?.Scale((float)newWidth / sourceImage.Width, (float)newHeight / sourceImage.Height, MatrixOrder.Append);
            }
            else
            {
                newBitmap = BitmapFactory.CreateEmpty(destWidth, destHeight, sourceImage.PixelFormat, backgroundColor, sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
                matrix?.Scale((float)destWidth / sourceImage.Width, (float)destHeight / sourceImage.Height, MatrixOrder.Append);
            }

            using (var graphics = Graphics.FromImage(newBitmap))
            {
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                graphics.SmoothingMode      = SmoothingMode.HighQuality;
                graphics.InterpolationMode  = interpolationMode;
                using (var wrapMode = new ImageAttributes())
                {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                    graphics.DrawImage(sourceImage, new NativeRect(destX, destY, destWidth, destHeight), 0, 0, sourceImage.Width, sourceImage.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }
            return(newBitmap);
        }