コード例 #1
0
        public static void Main(string[] args)
        {
            FileStream fs = new FileStream("d:\\DSC_6013.jpg", FileMode.Open, FileAccess.Read);
            Image img = new Image(fs);

            var resizer = new Resize(new BicubicResampler());

            var newImage = new Image();
            resizer.Apply(newImage, img, 100, 100);

            var wfs = new FileStream("d:\\DSC_6013_resized.jpg", FileMode.OpenOrCreate, FileAccess.Write);
            newImage.Save(wfs);
            wfs.Flush();

            string[] filenames;

            Parallel.ForEach<string>(filenames, ShrinkFile());
        }
コード例 #2
0
        public static ProcessResultArray <Clip> ProcessCommand(Command command, Clip[] incomingClips, ClipMetaData targetMetadata)
        {
            var clips = new Clip[incomingClips.Length];

            for (var i = 0; i < incomingClips.Length; i++)
            {
                clips[i] = new Clip(incomingClips[i]);
            }

            return(command.Id switch
            {
                TokenType.Arpeggiate => Arpeggiate.Apply(command, clips),
                TokenType.Concat => Concat.Apply(clips),
                TokenType.Crop => Crop.Apply(command, clips),
                TokenType.Filter => Filter.Apply(command, clips),
                TokenType.Interleave => Interleave.Apply(command, targetMetadata, clips, InterleaveMode.NotSpecified),
                TokenType.InterleaveEvent => Interleave.Apply(command, targetMetadata, clips, InterleaveMode.Event),
                TokenType.Legato => Legato.Apply(clips),
                TokenType.Loop => Loop.Apply(command, clips),
                TokenType.Mask => Mask.Apply(command, clips),
                TokenType.Monophonize => Monophonize.Apply(clips),
                TokenType.Padding => Padding.Apply(command, clips),
                TokenType.Quantize => Quantize.Apply(command, clips),
                TokenType.Ratchet => Ratchet.Apply(command, clips),
                TokenType.Relength => Relength.Apply(command, clips),
                TokenType.Remap => Remap.Apply(command, clips),
                TokenType.Resize => Resize.Apply(command, clips),
                TokenType.Scale => Scale.Apply(command, clips),
                TokenType.Scan => Scan.Apply(command, clips),
                TokenType.SetLength => SetLength.Apply(command, clips),
                TokenType.SetPitch => SetPitch.Apply(command, clips),
                TokenType.SetRhythm => SetRhythm.Apply(command, clips),
                TokenType.Shuffle => Shuffle.Apply(command, clips),
                TokenType.Skip => Skip.Apply(command, clips),
                TokenType.Slice => Slice.Apply(command, clips),
                TokenType.Take => Take.Apply(command, clips),
                TokenType.Transpose => Transpose.Apply(command, clips),
                TokenType.VelocityScale => VelocityScale.Apply(command, clips),
                _ => new ProcessResultArray <Clip>($"Unsupported command {command.Id}")
            });
コード例 #3
0
ファイル: TaskHelpers.cs プロジェクト: KoMiI/ShareX
        public static string CreateThumbnail(Image img, string folder, string filename, TaskSettings taskSettings)
        {
            if ((taskSettings.ImageSettings.ThumbnailWidth > 0 || taskSettings.ImageSettings.ThumbnailHeight > 0) && (!taskSettings.ImageSettings.ThumbnailCheckSize ||
                                                                                                                      (img.Width > taskSettings.ImageSettings.ThumbnailWidth && img.Height > taskSettings.ImageSettings.ThumbnailHeight)))
            {
                string thumbnailFileName = Path.GetFileNameWithoutExtension(filename) + taskSettings.ImageSettings.ThumbnailName + ".jpg";
                string thumbnailFilePath = CheckFilePath(folder, thumbnailFileName, taskSettings);

                if (!string.IsNullOrEmpty(thumbnailFilePath))
                {
                    Image thumbImage = null;

                    try
                    {
                        thumbImage = (Image)img.Clone();
                        thumbImage = new Resize
                        {
                            Width  = taskSettings.ImageSettings.ThumbnailWidth,
                            Height = taskSettings.ImageSettings.ThumbnailHeight
                        }.Apply(thumbImage);
                        thumbImage = ImageHelpers.FillBackground(thumbImage, Color.White);
                        thumbImage.SaveJPG(thumbnailFilePath, 90);
                        return(thumbnailFilePath);
                    }
                    catch (Exception e)
                    {
                        DebugHelper.WriteException(e);
                    }
                    finally
                    {
                        if (thumbImage != null)
                        {
                            thumbImage.Dispose();
                        }
                    }
                }
            }

            return(null);
        }
コード例 #4
0
    private static void TrackProgress()
    {
        Console.WriteLine("Progress Sample\r\n");

        // reader --->  resize  --->  progress  --->  writer
        using (var reader = ImageReader.Create("../../../../_Input/Venice.jpg"))
            using (var resize = new Resize(3200, 0, ResizeInterpolationMode.High))
                using (var progress = new ProgressReporter())
                    using (var writer = ImageWriter.Create("../../../../_Output/TrackProgress.jpg"))
                    {
                        progress.Progress += (s, e) =>
                        {
                            Console.WriteLine("{0:F2}%", e.Progress);
                        };

                        Console.WriteLine("Start pipeline processing...\n");

                        Pipeline.Run(reader + resize + progress + writer);

                        Console.WriteLine("\nEnd pipeline processing...\n");
                    }
    }
コード例 #5
0
        /// <summary>
        /// Resizes the current image to the given dimensions.
        /// </summary>
        /// <param name="size">
        /// The <see cref="T:System.Drawing.Size"/> containing the width and height to set the image to.
        /// </param>
        /// <returns>
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public ImageFactory Resize(Size size)
        {
            if (this.ShouldProcess)
            {
                int width  = size.Width;
                int height = size.Height;

                var resizeSettings = new Dictionary <string, string> {
                    { "MaxWidth", width.ToString("G") }, { "MaxHeight", height.ToString("G") }
                };

                ResizeLayer resizeLayer = new ResizeLayer(new Size(width, height));

                Resize resize = new Resize {
                    DynamicParameter = resizeLayer, Settings = resizeSettings
                };

                this.Image = resize.ProcessImage(this);
            }

            return(this);
        }
コード例 #6
0
        public void ChangeSize(Resize resize, int times)
        {
            if (times != 0)
            {
                switch (resize)
                {
                case Resize.enlarge:
                {
                    Width  *= times;
                    Height *= times;
                    break;
                }

                case Resize.reduce:
                {
                    Width  /= times;
                    Height /= times;
                    break;
                }
                }
            }
        }
コード例 #7
0
        public override IImmagine applica(IImmagine immagineSorgente, Correzione correzione)
        {
            _giornale.Debug("Richiesta correzione: " + correzione.GetType().Name);

            long   calcW, calcH;
            Resize resizeCorrezione = (Resize)correzione;

            ResizeCorrettore.calcolaEsattaWeH(immagineSorgente, resizeCorrezione.latoMax, out calcW, out calcH);

            BitmapSource bitmapSource = ((ImmagineWic)immagineSorgente).bitmapSource;


            /* I dpi sono una indicazione per la stampa.
             * Non impattano sui dati dell'immagine.
             * Non impattano sulla dimensione dell'immagine.
             * Non impattano sulla qualità dell'immagine.
             * In pratica è solo un "consiglio" per la stampa.
             *
             * Siccome credo che le stampanti termiche/sublimazione se ne fregano di questo parametro (per ovvi motivi)
             * allora me ne sbatto.
             * Occorrebbe fare una prova con una laser o con una InkJet per vedere se il risultato stampato cambia.
             *
             * int quantiDpi;
             * quantiDpi = (int) Math.Max( bitmapSource.DpiX, bitmapSource.DpiY );
             * quantiDpi = (int) Math.Max( quantiDpi, DPI_PROVINO );
             */

            BitmapSource bitmapFrame = Resize(bitmapSource, calcW, calcH, DPI_PROVINO);

            // _giornale.Debug( "effettuato resize" );
            if (bitmapFrame.CanFreeze)
            {
                bitmapFrame.Freeze();
            }
            ImmagineWic immagine = new ImmagineWic(bitmapFrame);

            return(immagine);
        }
コード例 #8
0
 public override void Configure(DataMap node, ElementFactory fac)
 {
     base.Configure(node, fac);
     if (node.Has("error"))
     {
         Error err;
         if (Enum.TryParse(node.Get("error"), true, out err))
         {
             error = err;
         }
     }
     if (node.Has("resize"))
     {
         Resize rs;
         if (Enum.TryParse(node.Get("resize"), true, out rs))
         {
             resize = rs;
         }
     }
     if (node.Has("pitch"))
     {
         int pt;
         if (int.TryParse(node.Get("pitch"), out pt))
         {
             pitch = pt;
         }
     }
     if (node.Has("margin"))
     {
         int mg;
         if (int.TryParse(node.Get("margin"), out mg))
         {
             margin = mg;
         }
     }
 }
コード例 #9
0
ファイル: ImagePrintItem.cs プロジェクト: lanicon/WinControls
        private void StripPrint(Bitmap image, System.Drawing.Graphics graphics, Point leftTopPosition, Size resizeSize, Rectangle cropRectangle)
        {
            const int MaxStripSize = 20000000;

            PixelFormat format = image.PixelFormat;

            if (format.IsIndexed)
            {
                format = PixelFormat.Format32bppArgb;
            }

            int pixelSize   = Math.Max(1, format.Size);
            int stripHeight = MaxStripSize / (pixelSize * cropRectangle.Width);
            int stripCount  = (int)Math.Ceiling((float)cropRectangle.Height / stripHeight);

            Rectangle objCurStrip = new Rectangle(cropRectangle.X, cropRectangle.Y, cropRectangle.Width, stripHeight);
            int       curShiftY   = 0;

            for (int i = 0; i < stripCount; i++)
            {
                using (var resize = new Resize(resizeSize.Width, resizeSize.Height, _interpolationMode))
                    using (var crop = new Crop())
                        using (var strip = new Bitmap())
                        {
                            objCurStrip.Height = Math.Min(stripHeight, cropRectangle.Height - curShiftY);

                            crop.Rectangle = objCurStrip;

                            Pipeline.Run(image + resize + crop + strip);
                            strip.DrawOn(graphics, leftTopPosition.X, leftTopPosition.Y + curShiftY, objCurStrip.Width, objCurStrip.Height, CombineMode.Copy, 1.0f, ResizeInterpolationMode.NearestNeighbour);
                        }

                objCurStrip.Y += objCurStrip.Height;
                curShiftY     += objCurStrip.Height;
            }
        }
コード例 #10
0
        /// <summary>
        /// Resizes an image to the given width and height with the given sampler and
        /// source rectangle.
        /// </summary>
        /// <param name="source">The image to resize.</param>
        /// <param name="width">The target image width.</param>
        /// <param name="height">The target image height.</param>
        /// <param name="sampler">The <see cref="IResampler"/> to perform the resampling.</param>
        /// <param name="sourceRectangle">
        /// The <see cref="Rectangle"/> structure that specifies the portion of the image object to draw.
        /// </param>
        /// <param name="progressHandler">A delegate which is called as progress is made processing the image.</param>
        /// <returns>The <see cref="Image"/></returns>
        /// <remarks>Passing zero for one of height or width will automatically preserve the aspect ratio of the original image</remarks>
        public static Image Resize(this Image source, int width, int height, IResampler sampler, Rectangle sourceRectangle, ProgressEventHandler progressHandler = null)
        {
            if (width == 0 && height > 0)
            {
                width = source.Width * height / source.Height;
            }

            if (height == 0 && width > 0)
            {
                height = source.Height * width / source.Width;
            }

            Resize processor = new Resize(sampler);
            processor.OnProgress += progressHandler;

            try
            {
                return source.Process(width, height, sourceRectangle, new Rectangle(0, 0, width, height), processor);
            }
            finally
            {
                processor.OnProgress -= progressHandler;
            }
        }
コード例 #11
0
ファイル: NativeWindow.cs プロジェクト: ipud2/OpenGL.Net-1
 /// <summary>
 /// Raise the event <see cref="Resize"/>.
 /// </summary>
 protected virtual void OnResize()
 {
     Resize?.Invoke(this, EventArgs.Empty);
 }
コード例 #12
0
 public ResizeBuildStep(ImageCasterConfig config)
 {
     this.Config = config.Build.Resize.RequireNonNull();
 }
コード例 #13
0
 private void ResizeDecreaseColumn_Click(object sender, RibbonControlEventArgs e)
 {
     Resize.DecreaseColumn(xlApplication);
 }
コード例 #14
0
    /// <summary>
    /// Gets thumbnail of image using different approaches (EXIF, JPEG scale, resize)
    /// </summary>
    private static void GetThumbnail(string inputPath, string outputPath, int thumbnailSize)
    {
        using (var reader = ImageReader.Create(inputPath))
            using (var converter = new ColorConverter(PixelFormat.Format24bppRgb))
                using (var resize = new Resize(thumbnailSize, thumbnailSize, ResizeInterpolationMode.High, ResizeMode.Fit))
                    using (var jpegWriter = new JpegWriter(outputPath, 85))
                    {
                        if (reader.Width <= thumbnailSize && reader.Height <= thumbnailSize)
                        {
                            if (reader.PixelFormat == PixelFormat.Format24bppRgb)
                            {
                                Pipeline.Run(reader + jpegWriter);
                            }
                            else
                            {
                                Pipeline.Run(reader + converter + jpegWriter);
                            }

                            return;
                        }

                        var jpegReader = reader as JpegReader;

                        if (jpegReader != null)
                        {
                            if (jpegReader.Exif.Contains(ExifDictionary.Thumbnail))
                            {
                                using (var thumbnail = (Bitmap)jpegReader.Exif[ExifDictionary.Thumbnail])
                                {
                                    if (thumbnail.Width > thumbnailSize || thumbnail.Height > thumbnailSize)
                                    {
                                        if (thumbnail.PixelFormat == PixelFormat.Format24bppRgb)
                                        {
                                            Pipeline.Run(thumbnail + resize + jpegWriter);
                                        }
                                        else
                                        {
                                            Pipeline.Run(thumbnail + resize + converter + jpegWriter);
                                        }

                                        return;
                                    }
                                }
                            }

                            var size = Math.Max(jpegReader.Width, jpegReader.Height);

                            const float k = 1.5f;

                            if (size / 8 >= thumbnailSize * k)
                            {
                                jpegReader.Scale = JpegScale.x8;
                            }
                            else if (size / 4 >= thumbnailSize * k)
                            {
                                jpegReader.Scale = JpegScale.x4;
                            }
                            else if (size / 2 >= thumbnailSize * k)
                            {
                                jpegReader.Scale = JpegScale.x2;
                            }
                        }

                        if (reader.PixelFormat == PixelFormat.Format24bppRgb)
                        {
                            Pipeline.Run(reader + resize + jpegWriter);
                        }
                        else
                        {
                            Pipeline.Run(reader + resize + converter + jpegWriter);
                        }
                    }
    }
コード例 #15
0
 protected virtual void OnResize()
 {
     //System.Diagnostics.Debug.WriteLine($"On Resize {Name}");
     Resize?.Invoke(this);
 }
コード例 #16
0
 public void RaiseResize()
 {
     Resize?.Invoke(null, EventArgs.Empty);
 }
コード例 #17
0
        public FileContentResult ImageEditRequest([FromBody] string RequestData)
        {
            //map request to DTO RequestModel
            JObject model = new JObject();

            try
            {
                model = JObject.Parse(RequestData);
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.ToString());
            }
            RequestModel request = new RequestModel();

            try
            {
                request.ImageData  = model["ImageData"].ToString();
                request.Operations = model["Operations"].ToObject <List <JObject> >();
            }
            catch (Exception ex)
            {
                throw new SystemException("Invalid String", ex);
            }


            //create data stream
            var imageDataByteArray = Convert.FromBase64String(request.ImageData);

            var imageDataStream = new MemoryStream(imageDataByteArray);

            imageDataStream.Position = 0;

            //Save edited image result here
            var imageOutStream = new MemoryStream();

            ImageFactory imageFactory = new ImageFactory();

            imageFactory.Load(imageDataStream);

            foreach (JObject JOp in request.Operations)
            {
                if (JOp.ContainsKey("Resize"))
                {
                    var    JTemp  = JOp["Resize"];
                    Resize resize = JTemp.ToObject <Resize>();
                    resize.PerformAction(imageFactory);
                }
                else if (JOp.ContainsKey("Filter"))
                {
                    var    JTemp  = JOp["Filter"];
                    Filter filter = JTemp.ToObject <Filter>();
                    filter.PerformAction(imageFactory);
                }
                else if (JOp.ContainsKey("Flip"))
                {
                    var  JTemp = JOp["Flip"];
                    Flip flip  = JTemp.ToObject <Flip>();
                    flip.PerformAction(imageFactory);
                }
                else if (JOp.ContainsKey("RotateRight"))
                {
                    var         JTemp  = JOp["RotateRight"];
                    RotateRight rotate = JTemp.ToObject <RotateRight>();
                    rotate.PerformAction(imageFactory);
                }
                else if (JOp.ContainsKey("RotateDegrees"))
                {
                    var           JTemp         = JOp["RotateDegrees"];
                    RotateDegrees rotateDegrees = JTemp.ToObject <RotateDegrees>();
                    rotateDegrees.PerformAction(imageFactory);
                }
                else if (JOp.ContainsKey("Thumbnail"))
                {
                    var       JTemp     = JOp["Thumbnail"];
                    Thumbnail thumbnail = JTemp.ToObject <Thumbnail>();
                    thumbnail.PerformAction(imageFactory);
                }
            }
            imageFactory.Save(imageOutStream);

            return(File(imageOutStream.ToArray(), "image/png"));
        }
コード例 #18
0
ファイル: Graphics.cs プロジェクト: vizv/SMAPI
 internal static void InvokeResize(object sender, EventArgs e)
 {
     Resize.Invoke(sender, e);
 }
コード例 #19
0
 private void BottomRightCorner_PointerMoved(object?sender, Avalonia.Input.PointerEventArgs e)
 {
     Resize?.Invoke(this, e);
 }
コード例 #20
0
 internal void OnResize(int width, int height)
 {
     Resize?.Invoke(width, height);
 }
コード例 #21
0
 private void ResizeIncreaseRow_Click(object sender, RibbonControlEventArgs e)
 {
     Resize.IncreaseRow(xlApplication);
 }
コード例 #22
0
ファイル: Program.cs プロジェクト: jekaqvop/korse2sem-1-
 public void Resize1(int a) => Resize?.Invoke(a);
コード例 #23
0
 /// <summary>
 /// Handles the Resize event of the GameWindow control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
 private void GameWindow_Resize(object sender, EventArgs e)
 {
     GL.Viewport(0, 0, gameWindow.Width, gameWindow.Height);
     Resize?.Invoke(gameWindow.Width, gameWindow.Height);
 }
コード例 #24
0
 public Score(Vector2 position, Resize resize, Rectangle window, SpriteFont font, Color textColor) : base(position, resize, window, "0", font, true, textColor, Color.Black, false, null)
 {
 }
コード例 #25
0
ファイル: NativeWindow.cs プロジェクト: razorware/netcore
 public void OnResize(Resize onResize)
 {
     resize = onResize;
 }
コード例 #26
0
        internal static void Update()
        {
            if (!Main.hasFocus)
            {
                return;
            }

            Input.CursorType       = 0;
            Input.DisabledMouse    = false;
            Input.DisabledKeyboard = false;
            Input.Update();
            textBlinkTimer++;

            // Do not allow Terraria's chat code to run b/c we handle it ourselves
            Main.chatRelease = false;

            if (Main.gameMenu)
            {
                if (Main.netMode != 1)
                {
                    chat.Clear();
                    rawChat.Clear();
                    chatViewOffset = 0;
                }
                typedChat.Clear();
                typedCommands.Clear();
                typedChatOffset    = 0;
                typedCommandOffset = 0;
                chatMode           = 0;
                Main.chatText      = "";

                isEditingRegions = false;
                isEditingWarps   = false;
                permissions.Clear();
                negatedPermissions.Clear();
                regions.Clear();
                regionsToDraw.Clear();
                warps.Clear();
                warpsToDraw.Clear();
                return;
            }

            #region Region editing
            if (isEditingRegions)
            {
                regionsToDraw.Clear();

                if (Input.MouseLeftClick)
                {
                    selectedRegion = null;
                }
                if (!Input.MouseLeftDown)
                {
                    if (regionMove)
                    {
                        Utils.SendRegion(selectedRegion);
                        Log.LogInfo("Moved region \"{0}\" to ({1}, {2}).",
                                    selectedRegion.Name, selectedRegion.Area.X, selectedRegion.Area.Y);
                        regionMove = false;
                    }
                    else if (regionResize > 0)
                    {
                        Utils.SendRegion(selectedRegion);
                        Log.LogInfo("Resized region \"{0}\" to ({1}, {2}).",
                                    selectedRegion.Name, selectedRegion.Area.Width, selectedRegion.Area.Height);
                        regionResize = 0;
                    }
                }

                #region Drawing, moving, & resizing
                var screen = new Rectangle(0, 0, Main.screenWidth, Main.screenHeight);
                for (int i = 0; i < regions.Count; i++)
                {
                    Region r = regions[i];

                    var rectangle = new Rectangle(
                        r.Area.X * 16 - (int)Main.screenPosition.X, r.Area.Y * 16 - (int)Main.screenPosition.Y,
                        r.Area.Width * 16, r.Area.Height * 16);

                    if (rectangle.Intersects(screen))
                    {
                        regionsToDraw.Add(r);

                        if (regionClickPt != Point.Zero)
                        {
                            continue;
                        }

                        #region Resizing Checks
                        bool isLeft  = new Rectangle(rectangle.Left, rectangle.Top, 8, rectangle.Height).Contains(Input.MouseX, Input.MouseY);
                        bool isRight = new Rectangle(rectangle.Right - 8, rectangle.Top, 8, rectangle.Height).Contains(Input.MouseX, Input.MouseY);
                        bool isUp    = new Rectangle(rectangle.Left, rectangle.Top, rectangle.Width, 8).Contains(Input.MouseX, Input.MouseY);
                        bool isDown  = new Rectangle(rectangle.Left, rectangle.Bottom - 8, rectangle.Width, 8).Contains(Input.MouseX, Input.MouseY);

                        if (isLeft || isRight)
                        {
                            Input.CursorType    = 2;
                            Input.DisabledMouse = true;

                            if (Input.MouseLeftClick)
                            {
                                regionResize    |= isLeft ? Resize.Left : Resize.Right;
                                regionResizeArea = r.Area;
                                selectedRegion   = r;
                            }
                        }
                        if (isUp || isDown)
                        {
                            Input.CursorType = Input.CursorType == 2 ? 4 : 3;
                            if ((isUp && isLeft) || (isDown && isRight))
                            {
                                Input.CursorType++;
                            }
                            Input.DisabledMouse = true;

                            if (Input.MouseLeftClick)
                            {
                                regionResize    |= isUp ? Resize.Up : Resize.Down;
                                regionResizeArea = r.Area;
                                selectedRegion   = r;
                            }
                        }
                        #endregion

                        if (rectangle.Contains(Input.MouseX, Input.MouseY) && !isLeft && !isRight && !isUp && !isDown)
                        {
                            mouseText           = "Region name: " + r.Name;
                            Input.CursorType    = 1;
                            Input.DisabledMouse = true;

                            if (Input.MouseLeftClick)
                            {
                                regionMove     = true;
                                regionMovePt   = new Point(Input.MouseX - rectangle.X, Input.MouseY - rectangle.Y);
                                selectedRegion = r;
                            }
                        }
                    }
                }
                #endregion
                #region Resizing
                if (regionResize != 0)
                {
                    bool isLeft  = regionResize.HasFlag(Resize.Left);
                    bool isRight = regionResize.HasFlag(Resize.Right);
                    bool isUp    = regionResize.HasFlag(Resize.Up);
                    bool isDown  = regionResize.HasFlag(Resize.Down);
                    mouseText           = "Region name: " + selectedRegion.Name;
                    Input.DisabledMouse = true;

                    if (isLeft)
                    {
                        Input.CursorType = 2;

                        int x     = (int)Math.Round((Input.MouseX + Main.screenPosition.X) / 16);
                        int width = regionResizeArea.X - x + regionResizeArea.Width;

                        if (width <= 0)
                        {
                            width = 1;
                            x     = regionResizeArea.Right - 1;
                        }

                        selectedRegion.Area.X     = x;
                        selectedRegion.Area.Width = width;
                    }
                    if (isRight)
                    {
                        Input.CursorType = 2;

                        int width = (int)Math.Round((Input.MouseX + Main.screenPosition.X) / 16) - regionResizeArea.X;
                        if (width <= 0)
                        {
                            width = 1;
                        }

                        selectedRegion.Area.Width = width;
                    }
                    if (isUp)
                    {
                        Input.CursorType = Input.CursorType == 2 ? 4 : 3;
                        if (isLeft)
                        {
                            Input.CursorType++;
                        }

                        int y      = (int)Math.Round((Input.MouseY + Main.screenPosition.Y) / 16);
                        int height = regionResizeArea.Y - y + regionResizeArea.Height;

                        if (height <= 0)
                        {
                            height = 1;
                            y      = regionResizeArea.Bottom - 1;
                        }

                        selectedRegion.Area.Y      = y;
                        selectedRegion.Area.Height = height;
                    }
                    if (isDown)
                    {
                        Input.CursorType = Input.CursorType == 2 ? 4 : 3;
                        if (isRight)
                        {
                            Input.CursorType++;
                        }

                        int height = (int)Math.Round((Input.MouseY + Main.screenPosition.Y) / 16) - regionResizeArea.Y;
                        if (height <= 0)
                        {
                            height = 1;
                        }

                        selectedRegion.Area.Height = height;
                    }
                }
                #endregion
                #region Moving
                if (regionMove)
                {
                    mouseText           = "Region name: " + selectedRegion.Name;
                    Input.CursorType    = 1;
                    Input.DisabledMouse = true;

                    selectedRegion.Area.X = (int)Math.Round((Main.screenPosition.X + Input.MouseX - regionMovePt.X) / 16.0);
                    selectedRegion.Area.Y = (int)Math.Round((Main.screenPosition.Y + Input.MouseY - regionMovePt.Y) / 16.0);
                }
                #endregion
                #region Creating
                if (Input.MouseRightClick && regionClickPt == Point.Zero)
                {
                    Input.DisabledMouse = true;

                    isCreatingRegion = true;
                    regionClickPt.X  = (int)(Main.screenPosition.X + Input.MouseX) / 16;
                    regionClickPt.Y  = (int)(Main.screenPosition.Y + Input.MouseY) / 16;
                    selectedRegion   = null;
                }

                if (isCreatingRegion)
                {
                    Input.DisabledMouse = true;

                    if (Input.MouseRightDown && regionClickPt != Point.Zero)
                    {
                        int X = (int)(Main.screenPosition.X + Input.MouseX) / 16;
                        int Y = (int)(Main.screenPosition.Y + Input.MouseY) / 16;
                        if (X < regionClickPt.X)
                        {
                            regionPt1.X = X;
                            regionPt2.X = regionClickPt.X;
                        }
                        else
                        {
                            regionPt1.X = regionClickPt.X;
                            regionPt2.X = X;
                        }
                        if (Y < regionClickPt.Y)
                        {
                            regionPt1.Y = Y;
                            regionPt2.Y = regionClickPt.Y;
                        }
                        else
                        {
                            regionPt1.Y = regionClickPt.Y;
                            regionPt2.Y = Y;
                        }
                    }
                    if (Input.MouseRightRelease)
                    {
                        isCreatingRegion = false;
                        isNamingRegion   = true;
                        regionName       = "";
                        Main.PlaySound(10);
                    }
                }
                #endregion
                #region Naming
                else if (isNamingRegion)
                {
                    var rectangle = new Rectangle(
                        regionPt1.X * 16 - (int)Main.screenPosition.X,
                        regionPt1.Y * 16 - (int)Main.screenPosition.Y,
                        (regionPt2.X - regionPt1.X + 1) * 16,
                        (regionPt2.Y - regionPt1.Y + 1) * 16);
                    if (rectangle.Contains(Input.MouseX, Input.MouseY))
                    {
                        Input.DisabledKeyboard = true;
                        Input.DisabledMouse    = true;

                        regionName = Input.GetInputText(regionName);
                        mouseText  = "Region name: " + regionName + (textBlinkTimer % 40 > 10 ? "|" : "");
                    }

                    if (Input.IsKeyTapped(Keys.Enter) && regionName != "")
                    {
                        if (regions.Any(r => String.Equals(r.Name, regionName, StringComparison.OrdinalIgnoreCase)))
                        {
                            Utils.NewErrorText("Invalid region name.");
                        }
                        else
                        {
                            Region region = new Region();
                            region.Area = new Rectangle(regionPt1.X, regionPt1.Y, regionPt2.X - regionPt1.X + 1, regionPt2.Y - regionPt1.Y + 1);
                            region.Name = regionName;
                            regions.Add(region);
                            regionsToDraw.Add(region);
                            Utils.SendRegion(region);
                            Log.LogInfo("Created new region \"{0}\" at ({1}, {2}) with size ({3}, {4})",
                                        regionName, region.Area.X, region.Area.Y, region.Area.Width, region.Area.Height);

                            isNamingRegion = false;
                            regionClickPt  = regionPt1 = regionPt2 = Point.Zero;
                        }

                        Main.PlaySound(11);
                    }
                    else if (Input.IsKeyTapped(Keys.Escape))
                    {
                        isNamingRegion = false;
                        regionClickPt  = regionPt1 = regionPt2 = Point.Zero;
                        Main.PlaySound(11);
                    }
                }
                #endregion
                #region Deleting
                if (selectedRegion != null && Input.IsKeyTapped(Keys.Delete))
                {
                    Utils.SendRegionDelete(selectedRegion);
                    regions.Remove(selectedRegion);
                    regionsToDraw.Remove(selectedRegion);
                    Log.LogInfo("Deleted region \"{0}\".", selectedRegion);

                    Main.PlaySound(11);
                }
                #endregion
            }
            #endregion
            #region Warp editing
            else if (isEditingWarps)
            {
                warpsToDraw.Clear();

                if (Input.MouseLeftClick)
                {
                    selectedWarp = null;
                }
                if (!Input.MouseLeftDown)
                {
                    if (warpMove)
                    {
                        Utils.SendWarp(selectedWarp);
                        Log.LogInfo("Moved warp \"{0}\" to ({1}, {2}).",
                                    selectedWarp.Name, selectedWarp.Position.X, selectedWarp.Position.Y);
                        warpMove = false;
                    }
                }

                #region Drawing & moving
                var screen = new Rectangle(0, 0, Main.screenWidth, Main.screenHeight);
                for (int i = 0; i < warps.Count; i++)
                {
                    Warp w = warps[i];

                    var rectangle = new Rectangle(
                        w.Position.X * 16 - (int)Main.screenPosition.X, w.Position.Y * 16 - (int)Main.screenPosition.Y,
                        32, 48);

                    if (rectangle.Intersects(screen))
                    {
                        warpsToDraw.Add(w);

                        if (rectangle.Contains(Input.MouseX, Input.MouseY))
                        {
                            mouseText           = "Warp name: " + w.Name;
                            Input.CursorType    = 1;
                            Input.DisabledMouse = true;

                            if (Input.MouseLeftClick)
                            {
                                warpMove     = true;
                                warpMovePt   = new Point(Input.MouseX - rectangle.X, Input.MouseY - rectangle.Y);
                                selectedWarp = w;
                            }
                        }
                    }
                }
                #endregion
                #region Moving
                if (warpMove)
                {
                    mouseText           = "Warp name: " + selectedWarp.Name;
                    Input.CursorType    = 1;
                    Input.DisabledMouse = true;

                    selectedWarp.Position.X = (int)Math.Round((Main.screenPosition.X + Input.MouseX - warpMovePt.X) / 16.0);
                    selectedWarp.Position.Y = (int)Math.Round((Main.screenPosition.Y + Input.MouseY - warpMovePt.Y) / 16.0);
                }
                #endregion
                #region Creating
                if (Input.MouseRightClick && warpPt == Point.Zero)
                {
                    Input.DisabledMouse = true;

                    isCreatingWarp = true;
                    selectedWarp   = null;
                    warpPt.X       = (int)(Main.screenPosition.X + Input.MouseX) / 16;
                    warpPt.Y       = (int)(Main.screenPosition.Y + Input.MouseY) / 16;
                }

                if (isCreatingWarp)
                {
                    Input.DisabledMouse = true;

                    if (Input.MouseRightDown && warpPt != Point.Zero)
                    {
                        warpPt.X = (int)(Main.screenPosition.X + Input.MouseX) / 16;
                        warpPt.Y = (int)(Main.screenPosition.Y + Input.MouseY) / 16;
                    }
                    if (Input.MouseRightRelease)
                    {
                        isCreatingWarp = false;
                        isNamingWarp   = true;
                        warpName       = "";
                        Main.PlaySound(10);
                    }
                }
                #endregion
                #region Naming
                else if (isNamingWarp)
                {
                    var rectangle = new Rectangle(
                        warpPt.X * 16 - (int)Main.screenPosition.X, warpPt.Y * 16 - (int)Main.screenPosition.Y,
                        32, 48);
                    if (rectangle.Contains(Input.MouseX, Input.MouseY))
                    {
                        Input.DisabledKeyboard = true;
                        Input.DisabledMouse    = true;

                        warpName  = Input.GetInputText(warpName);
                        mouseText = "Warp name: " + warpName + (textBlinkTimer % 40 > 10 ? "|" : "");
                    }

                    if (Input.IsKeyTapped(Keys.Enter) && warpName != "")
                    {
                        if (warps.Any(w => String.Equals(w.Name, warpName, StringComparison.OrdinalIgnoreCase)))
                        {
                            Utils.NewErrorText("Invalid warp name.");
                        }
                        else
                        {
                            var warp = new Warp();
                            warp.Name     = warpName;
                            warp.Position = warpPt;
                            warps.Add(warp);
                            warpsToDraw.Add(warp);
                            Utils.SendWarp(warp);
                            Log.LogInfo("Created new warp \"{0}\" at ({1}, {2}).", warpName, warpPt.X, warpPt.Y);

                            isNamingWarp = false;
                            warpPt       = Point.Zero;
                        }

                        Main.PlaySound(11);
                    }
                    else if (Input.IsKeyTapped(Keys.Escape))
                    {
                        isNamingWarp = false;
                        warpPt       = Point.Zero;
                        Main.PlaySound(11);
                    }
                }
                #endregion
                #region Deleting
                if (selectedWarp != null && Input.IsKeyTapped(Keys.Delete))
                {
                    Utils.SendWarpDelete(selectedWarp);
                    warps.Remove(selectedWarp);
                    warpsToDraw.Remove(selectedWarp);
                    Log.LogInfo("Deleted warp \"{0}\".", selectedWarp.Name);

                    Main.PlaySound(11);
                }
                #endregion
            }
            #endregion

            #region Chat handling
            if (((Input.IsKeyTapped(Keys.Enter) && !Input.Alt) || (Input.IsKeyTapped(Keys.OemQuestion) && !Input.Shift)) &&
                chatMode == 0 && !Main.editSign && !Main.gameMenu && !Input.DisabledKeyboard)
            {
                chatMode = Input.IsKeyTapped(Keys.OemQuestion) ? 2 : 1;
                Main.PlaySound(10);
            }
            else if (chatMode > 0)
            {
                var chatRectangle = new Rectangle(96, Main.screenHeight - 49 - Config.ChatShow * 19, Main.screenWidth - 312, Config.ChatShow * 19 + 12);
                if (chatRectangle.Contains(Input.MouseX, Input.MouseY))
                {
                    Input.DisabledMouse = true;
                    if (chat.Count > Config.ChatShow)
                    {
                        chatViewOffset += Math.Sign(Input.MouseDScroll) * -Config.ChatScrollSpeed;
                        chatViewOffset  = (chatViewOffset < Config.ChatShow) ? Config.ChatShow : chatViewOffset;
                        chatViewOffset  = (chatViewOffset > chat.Count) ? chat.Count : chatViewOffset;
                    }
                }

                Input.DisabledKeyboard = true;
                Main.chatText          = Main.GetInputText(Main.chatText);
                while (Main.fontMouseText.MeasureString(Main.chatText).X > Main.screenWidth - 324)
                {
                    Main.chatText = Main.chatText.Substring(0, Main.chatText.Length - 1);
                }

                if (Input.ActiveSpecialKeys.HasFlag(Input.SpecialKeys.Up))
                {
                    if (chatMode == 1 && typedChat.Count != 0)
                    {
                        typedChatOffset--;
                        if (typedChatOffset < 0)
                        {
                            typedChatOffset = 0;
                        }
                        Main.chatText = typedChat[typedChatOffset];
                    }
                    else if (chatMode == 2 && typedCommands.Count != 0)
                    {
                        typedCommandOffset--;
                        if (typedCommandOffset < 0)
                        {
                            typedCommandOffset = 0;
                        }
                        Main.chatText = typedCommands[typedCommandOffset];
                    }
                }
                else if (Input.ActiveSpecialKeys.HasFlag(Input.SpecialKeys.Down))
                {
                    if (chatMode == 1 && typedChat.Count != 0)
                    {
                        typedChatOffset++;

                        if (typedChatOffset >= typedChat.Count)
                        {
                            typedChatOffset = typedChat.Count;
                            Main.chatText   = "";
                        }
                        else
                        {
                            Main.chatText = typedChat[typedChatOffset];
                        }
                    }
                    else if (chatMode == 2 && typedCommands.Count != 0)
                    {
                        typedCommandOffset++;

                        if (typedCommandOffset >= typedCommands.Count)
                        {
                            typedCommandOffset = typedCommands.Count;
                            Main.chatText      = "";
                        }
                        else
                        {
                            Main.chatText = typedCommands[typedCommandOffset];
                        }
                    }
                }
                else if (Input.IsKeyTapped(Keys.Escape) || (Input.IsKeyTapped(Keys.Enter) && Main.chatText == ""))
                {
                    chatMode           = 0;
                    chatViewOffset     = chat.Count;
                    typedChatOffset    = typedChat.Count;
                    typedCommandOffset = typedCommands.Count;

                    Main.chatText = "";
                    Main.PlaySound(11);
                }
                else if (Input.IsKeyTapped(Keys.Enter))
                {
                    if (chatMode == 1)
                    {
                        typedChat.Add(Main.chatText);
                        if (typedChat.Count > 1000)
                        {
                            typedChat.RemoveAt(0);
                        }
                        typedChatOffset = typedChat.Count;
                        if (Main.netMode == 1)
                        {
                            NetMessage.SendData(25, -1, -1, Main.chatText, Main.myPlayer);
                        }
                        else
                        {
                            Main.NewText(String.Format("<{0}> {1}", Main.player[Main.myPlayer].name, Main.chatText));
                        }
                    }
                    else
                    {
                        typedCommands.Add(Main.chatText);
                        if (typedCommands.Count > 1000)
                        {
                            typedCommands.RemoveAt(0);
                        }
                        typedCommandOffset = typedCommands.Count;
                        Commands.Execute(Main.chatText);
                    }

                    Main.chatText = "";
                    Main.PlaySound(11);
                    chatViewOffset = chat.Count;
                }
            }
            for (int i = 0; i < chat.Count; i++)
            {
                if (chat[i].timeOut > 0)
                {
                    chat[i].timeOut--;
                }
            }
            for (int i = 0; i < rawChat.Count; i++)
            {
                if (rawChat[i].timeOut > 0)
                {
                    rawChat[i].timeOut = 0;
                }
            }
            #endregion
            #region Key bindings
            if (chatMode == 0 && !Main.editSign && !Main.gameMenu && !Input.DisabledKeyboard)
            {
                foreach (KeyValuePair <Keys, string> kvp in Config.KeyBindings)
                {
                    if (Input.IsKeyTapped(kvp.Key))
                    {
                        Commands.Execute(kvp.Value);
                    }
                }
            }
            #endregion

            if (Input.DisabledMouse)
            {
                Main.mouseState = Main.oldMouseState = new MouseState(-100, -100, Input.MouseScroll, 0, 0, 0, 0, 0);
            }
            if (Input.DisabledKeyboard)
            {
                Main.keyState = Main.inputText = Main.oldInputText = new KeyboardState(null);
            }
        }
コード例 #27
0
        // Process new frame
        public void ProcessFrame(ref Bitmap image)
        {
            if (_mForm.leftMouseButtonDown == true)
            {
                //Code to draw a rubberband selection rectangle

                //Compute width and height of rectangle
                int w = Math.Abs((int)_mForm.x2 - (int)_mForm.x1);
                int h = Math.Abs((int)_mForm.y2 - (int)_mForm.y1);

                //Decide x and y of rectangle
                int x = 0, y = 0;

                if (_mForm.x1 < _mForm.x2)
                {
                    x = (int)_mForm.x1;
                }
                else if ((int)_mForm.x1 > _mForm.x2)
                {
                    x = (int)_mForm.x2;
                }

                if (_mForm.y1 < _mForm.y2)
                {
                    y = (int)_mForm.y1;
                }
                else if (_mForm.y1 > _mForm.y2)
                {
                    y = (int)_mForm.y2;
                }

                //Draw the rectangle
                Rectangle rect = new Rectangle(x, y, w, h);

                Graphics g = Graphics.FromImage((System.Drawing.Image)image);

                g.FillRectangle(new SolidBrush(Color.FromArgb
                                                   (60, 184, 184, 0)), rect); //Draws a semi-transparent rectangle using alpha blending

                g.Dispose();
                return;
            }

            if (_mForm.videoCropHeight == -1)
            {
                //Set or reset video cropping so that nothing gets trimmed out
                _mForm.videoCropHeight = image.Height;
                _mForm.videoCropWidth  = image.Width;
            }

            //Crop the bitmap
            Bitmap tmpImage0 = image.Clone(new Rectangle(_mForm.videoCropX,
                                                         _mForm.videoCropY, _mForm.videoCropWidth, _mForm.videoCropHeight),
                                           System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            //Resize the bitmap
            AForge.Imaging.Filters.Resize resize = new Resize(image.Width / _mForm.resizeFactor,
                                                              image.Height / _mForm.resizeFactor, InterpolationMethod.NearestNeighbor);

            Bitmap tmpImage1 = resize.Apply(tmpImage0);

            //Get width and height of Bitmap
            imageWidth  = tmpImage1.Width;
            imageHeight = tmpImage1.Height;

            tmpImage0.Dispose();

            Utility.UnsafeBitmap uBitmap = new Utility.UnsafeBitmap(tmpImage1);

            //Locate the brightest pixel in the bitmap

            bool brightnessFound = false;

            uBitmap.LockBitmap();

            float brightest = 0;
            int   xPos = 0, yPos = 0, xprev = 0, yprev = 0, currx = 0, curry = 0, dispx = 0, dispy = 0;



            for (int y = 0; y < imageHeight; y += 1)
            {
                for (int x = 0; x < imageWidth; x += 1)
                {
                    byte red, green, blue;
                    red   = uBitmap.GetPixel(x, y).red;
                    green = uBitmap.GetPixel(x, y).green;
                    blue  = uBitmap.GetPixel(x, y).blue;



                    if (red > 150 && green < 100 && blue < 100)
                    {
                        xPos            = x;
                        yPos            = y;
                        currx           = x;
                        curry           = y;
                        brightnessFound = true;
                        s_red           = red; s_green = green; s_blue = blue;
                    }

                    if (green > 170 && red < 150 && blue < 190)
                    {
                        xPos            = x;
                        yPos            = y;
                        currx           = x;
                        curry           = y;
                        brightnessFound = true;

                        s_red = red; s_green = green; s_blue = blue;
                    }

                    if (blue > 150 && green < 100 && red < 100)
                    {
                        xPos            = x;
                        yPos            = y;
                        currx           = x;
                        curry           = y;
                        brightnessFound = true;
                        s_red           = red; s_green = green; s_blue = blue;
                    }

                    /* if (red > 220 && green > 220 && blue > 220)
                     * {
                     *
                     *   xPos = x;
                     *   yPos = y;
                     *   currx = x;
                     *   curry = y;
                     *   brightnessFound = true;
                     *   s_red = red; s_green = green; s_blue = blue;
                     * } */
                    if (red > 150 && green > 150 && blue < 100)
                    {
                        xPos            = x;
                        yPos            = y;
                        currx           = x;
                        curry           = y;
                        brightnessFound = true;
                        s_red           = red; s_green = green; s_blue = blue;
                    }

                    // (brightest > _mForm.threshold)
                } // x loop
            }     // y loop

            string path = "ByteValues.txt";

            // This text is added only once to the file.
            if (File.Exists(path))
            {
                File.Delete(path);
            }

            if (!File.Exists(path))
            {
                // Create a file to write to.
                using (StreamWriter sw = new StreamWriter(path, true))
                {
                    sw.WriteLine(s_red.ToString() + " " + s_green.ToString() + " " + s_blue.ToString());
                    sw.Close();
                }
            }
            if (brightnessFound == true)
            {
                int colour = 0;

                if (((s_red > s_blue) && (s_red > s_green) && (Math.Abs(s_red - s_green) > 65) && ((Math.Abs(s_red - s_blue) > 65))))
                {
                    colour = 1;
                }
                else if ((((s_green > s_red) && (s_green > s_blue) && Math.Abs(s_green - s_red) > 65) && ((Math.Abs(s_green - s_blue) > 65))))
                {
                    colour = 2;
                }
                else if (((s_blue > s_red) && (s_blue > s_green) && (Math.Abs(s_blue - s_red) > 65) && ((Math.Abs(s_blue - s_green) > 65))))
                {
                    colour = 3;
                }
                // else if (s_red>220  &&  s_green>220 && s_blue>220 )  colour = 4;
                else if (s_red > 150 && s_green > 150 && s_blue < 100)
                {
                    colour = 5;
                }

                string path1 = "Colour Detected.txt";



                switch (colour)
                {
                case 1:

                    if (!File.Exists(path1))
                    {
                        // Create a file to write to.
                        using (StreamWriter sw = new StreamWriter(path1, true))
                        {
                            sw.Write("Red Detected  ");
                            sw.Close();
                        }
                    }
                    else
                    {
                        using (StreamWriter sw = File.AppendText(path1))
                        {
                            sw.Write("Red Detected  ");
                            sw.Close();
                        }
                    }

                    if ((xprev - currx != 0) || (yprev - curry != 0))
                    {
                        dispx = xprev - currx;
                        dispy = yprev - curry;

                        ControlCursor(xPos, yPos, _mForm.enableClick);                  //Set cursor position
                    }
                    xprev = currx;
                    yprev = curry;

                    break;

                case 2:


                    if (!File.Exists(path1))
                    {
                        // Create a file to write to.
                        using (StreamWriter sw = new StreamWriter(path1, true))
                        {
                            sw.Write("Green Detected  ");
                            sw.Close();
                        }
                    }
                    else
                    {
                        using (StreamWriter sw = File.AppendText(path1))
                        {
                            sw.Write("Green Detected  ");
                            sw.Close();
                        }
                    }

                    //Generate a left mouse button click
                    mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);

                    break;

                case 3:

                    if (!File.Exists(path1))
                    {
                        // Create a file to write to.
                        using (StreamWriter sw = new StreamWriter(path1, true))
                        {
                            sw.Write("Blue Detected  ");
                            sw.Close();
                        }
                    }
                    else
                    {
                        using (StreamWriter sw = File.AppendText(path1))
                        {
                            sw.Write("Blue Detected  ");
                            sw.Close();
                        }
                    }
                    //Generate a left mouse button click
                    mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
                    break;

                /*  case 4:
                 *        if (!File.Exists(path1))
                 *             {
                 *                 // Create a file to write to.
                 *                 using (StreamWriter sw = new StreamWriter(path1, true))
                 *                 {
                 *                     sw.Write("White Detected ");
                 *                     sw.Close();
                 *                 }
                 *             }
                 *             else
                 *             {
                 *                 using (StreamWriter sw = File.AppendText(path1))
                 *                 {
                 *                     sw.Write("White Detected ");
                 *                     sw.Close();
                 *                 }
                 *             }
                 *                break;*/
                case 5:


                    if (!File.Exists(path1))
                    {
                        // Create a file to write to.
                        using (StreamWriter sw = new StreamWriter(path1, true))
                        {
                            sw.Write("Yellow Detected  ");
                            sw.Close();
                        }
                    }
                    else
                    {
                        using (StreamWriter sw = File.AppendText(path1))
                        {
                            sw.Write("Yellow Detected  ");
                            sw.Close();
                        }
                    }
                    break;
                }



                uBitmap.UnlockBitmap();

                //Encircle the brightest pixel
                Graphics dc = Graphics.FromImage(tmpImage1);
                Pen      p  = new Pen(Color.LimeGreen, 1);

                dc.DrawEllipse(p, xPos - 5, yPos - 5, 10, 10);

                //Show the x and y coordinates of the brightest pixel
                dc.DrawString("X: " + xPos.ToString() + ", Y: " +
                              yPos.ToString(), new Font("Verdana", 7, FontStyle.Regular),
                              Brushes.Yellow, new Point(xPos, yPos + 8));

                if (_mForm.controlMouse == true)
                {
                    ControlCursor(xPos, yPos, _mForm.enableClick); //Set cursor position
                }
                dc.Dispose();

                uBitmap.LockBitmap();
            }
            else
            {
                if (_mForm.enableClick == true && leftMouseButtonDown == true)
                {
                    //Generate a left mouse button click
                    mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
                    leftMouseButtonDown = false;
                }
            }

            uBitmap.UnlockBitmap();
            uBitmap.Bitmap.Dispose();

            image.Dispose();
            image = tmpImage1;
        }
コード例 #28
0
        public void run(Image image)
        {
            // merge undo history
            GSImage gsImage = image as GSImage;
            if (gsImage != null) {
                gsImage.Image.UndoGroupStart();
            }

            if (PreResize != null) {
                PreResize.run(image);
            }
            if (PreDotGain != null) {
                PreDotGain.run(image);
            }
            if (PreSharpen != null) {
                PreSharpen.run(image);
            }
            Method.run(image);
            if (SupersamplingEnabled && (PreResize != null)) {
                PreResize.Forward = true;
                if (PostResize == null) {
                    PostResize = new Resize();
                }
                PostResize.Factor = PreResize.Factor;
                PostResize.Forward = false;
            }
            if (PostResize != null) {
                PostResize.run(image);
            }
            if (PostSmoothen != null) {
                PostSmoothen.run(image);
            }

            if (gsImage != null) {
                gsImage.Image.UndoGroupEnd();
            }
        }
コード例 #29
0
 public static void CallResize(int width, int height) => Resize?.Invoke(width, height);
コード例 #30
0
 void IHandler <Resize> .Handle(FrameArgs frame, Resize e)
 {
 }
コード例 #31
0
 protected internal virtual void OnResize(EventArgs e)
 {
     Resize?.Invoke(this, e);
 }
コード例 #32
0
        public void Generate()
        {
            if (InputFilePath == null)
            {
                throw new InvalidOperationException("Input file path is not specified.");
            }

            if (OutputDirPath == null)
            {
                throw new InvalidOperationException("Output directory path is not specified.");
            }

            if (ViewerCreation && BaseName == null)
            {
                throw new InvalidOperationException("Base name should be specified for viewer creation.");
            }

            var zoomLevels = new List <ZoomLevel>();

            ImageReader reader = null;

            try
            {
                reader = ImageReader.Create(InputFilePath);

                var d = 1f;

                ZoomLevel zoomLevel;

                do
                {
                    zoomLevel.ImageWidth  = (int)((float)reader.Width / d);
                    zoomLevel.ImageHeight = (int)((float)reader.Height / d);
                    zoomLevel.GridWidth   = (zoomLevel.ImageWidth + TileSize - 1) / TileSize;
                    zoomLevel.GridHeight  = (zoomLevel.ImageHeight + TileSize - 1) / TileSize;

                    zoomLevels.Add(zoomLevel);

                    tileTotal += zoomLevel.GridWidth * zoomLevel.GridHeight;

                    d *= 2;
                } while (zoomLevel.ImageWidth > TileSize || zoomLevel.ImageHeight > TileSize);

                zoomLevels.Reverse();


                if (ViewerCreation)
                {
                    var bd = AppDomain.CurrentDomain.BaseDirectory;

                    try
                    {
                        if (!Directory.Exists(OutputDirPath))
                        {
                            Directory.CreateDirectory(OutputDirPath);
                        }
                    }
                    catch (Exception e)
                    {
                        throw new IOException(String.Format("Can't create directory {0}.\r\n  {1}", OutputDirPath, e.Message));
                    }

                    File.Copy(Path.Combine(bd, ScriptFileName), Path.Combine(OutputDirPath, ScriptFileName), true);

                    var viewer = File.ReadAllText(Path.Combine(bd, ViewerFileName)).
                                 Replace("{viewerwidth}", ViewerWidth.ToString()).
                                 Replace("{viewerheight}", ViewerHeight.ToString()).
                                 Replace("{imagewidth}", reader.Width.ToString()).
                                 Replace("{imageheight}", reader.Height.ToString()).
                                 Replace("{basename}", BaseName).
                                 Replace("{structure}", FileStructure.Replace("{ext}", GetTileFileExt()));

                    if (TileSize != 256)
                    {
                        viewer = viewer.Replace("{tilesize}", TileSize.ToString());
                    }
                    else
                    {
                        var r = new Regex(@"^.*{tilesize}.*\r\n", RegexOptions.Multiline);
                        viewer = r.Replace(viewer, "");
                    }

                    File.WriteAllText(Path.Combine(OutputDirPath, BaseName + ".htm"), viewer);
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Dispose();
                }
            }

            tileProcessedTotal = 0;

            //Application can't have more than 2048 file handlers.
            //We can reach the limit with >~100 MP images
            for (int minTileIndex = 1; minTileIndex <= tileTotal; minTileIndex += MaxOpenFileCount)
            {
                int maxTileIndex = Math.Min(minTileIndex + MaxOpenFileCount - 1, tileTotal);
                int tileIndex    = 0;

                //Store reference to all pipeline elements for further correct object disposing
                var pipelineElements = new List <PipelineElement>();

                try
                {
                    reader = ImageReader.Create(InputFilePath);

                    pipelineElements.Add(reader);

                    PipelineElement source;

                    //Create progress tracker
                    if (Progress != null)
                    {
                        var progress = new ProgressReporter();
                        progress.Progress += (s, e) =>
                        {
                            OnProgress(e);
                        };
                        pipelineElements.Add(progress);
                        reader.Receivers.Add(progress);

                        source = progress;
                    }
                    else
                    {
                        source = reader;
                    }

                    for (int zoom = 0; zoom < zoomLevels.Count; zoom++)
                    {
                        PipelineElement resize;

                        if (zoom == zoomLevels.Count)
                        {
                            resize = source;
                        }
                        else
                        {
                            resize = new Resize(zoomLevels[zoom].ImageWidth, zoomLevels[zoom].ImageHeight, ResizeInterpolationMode.Anisotropic9);
                            pipelineElements.Add(resize);
                            source.Receivers.Add(resize);
                        }


                        for (int tileX = 0; tileX < zoomLevels[zoom].GridWidth; tileX++)
                        {
                            for (int tileY = 0; tileY < zoomLevels[zoom].GridHeight; tileY++)
                            {
                                tileIndex++;

                                if (tileIndex < minTileIndex)
                                {
                                    continue;
                                }

                                int x      = tileX * TileSize;
                                int y      = tileY * TileSize;
                                int width  = Math.Min((tileX + 1) * TileSize, zoomLevels[zoom].ImageWidth) - x;
                                int height = Math.Min((tileY + 1) * TileSize, zoomLevels[zoom].ImageHeight) - y;

                                var crop = new Crop(x, y, width, height);
                                pipelineElements.Add(crop);
                                resize.Receivers.Add(crop);

                                var outputFilePath = Path.Combine(GetTileOutputDirPath(),
                                                                  String.Format(GetFileStructureFormat(), zoom, tileX, tileY, GetTileFileExt()));

                                var p = Path.GetDirectoryName(outputFilePath);

                                try
                                {
                                    if (!Directory.Exists(p))
                                    {
                                        Directory.CreateDirectory(p);
                                    }
                                }
                                catch (Exception e)
                                {
                                    throw new IOException(String.Format("Can't create directory {0}.\r\n  {1}", p, e.Message));
                                }

                                ImageWriter writer;

                                switch (TileImageFormat)
                                {
                                case TileImageFormat.PNG:
                                    writer = new PngWriter(outputFilePath);
                                    break;

                                default:
                                    writer = new JpegWriter(outputFilePath, TileJpegQuality);
                                    break;
                                }

                                pipelineElements.Add(writer);
                                crop.Receivers.Add(writer);

                                if (tileIndex == maxTileIndex)
                                {
                                    //Remove resize elements without crop receivers
                                    for (var l = source.Receivers.Count - 1; l >= 0; l--)
                                    {
                                        if (source.Receivers[l].Receivers.Count == 0)
                                        {
                                            source.Receivers.RemoveAt(l);
                                        }
                                    }

                                    Pipeline.Run(reader);

                                    tileProcessedTotal = maxTileIndex;

                                    goto LoopOut;
                                }
                            }
                        }
                    }

LoopOut:
                    ;
                }
                finally
                {
                    for (var i = 0; i < pipelineElements.Count; i++)
                    {
                        pipelineElements[i].Dispose();
                    }
                }
            }
        }
コード例 #33
0
ファイル: Window.cs プロジェクト: yaram/Mulion
 protected void OnResize()
 {
     Resize?.Invoke();
 }
コード例 #34
0
ファイル: MainForm.cs プロジェクト: PhotoVision/CCWireframe
 private void ShrinkWorkingImage(string path)
 {
     using (var bitmap = new Aurigma.GraphicsMill.Bitmap(path))
     using (var resize = new Resize(display.Width, display.Height, ResizeInterpolationMode.High, ResizeMode.Fit))
     using (var result = resize.Apply(bitmap))
     {
         result.Save(resizedImage);
     }
 }