Inheritance: IDisposable
Esempio n. 1
2
        public async Task<ValidationResult> Execute(MediaInfo mediaInfo, Int32 x, Int32 y, Int32 width, Int32 height)
        {
            if (x < 0 || y < 0 || width <= 0 || height <= 0)
            {
                return new ValidationResult("サイズの指定が不正です。");
            }

            var mediaContent = await _mediaRepository.Get(mediaInfo);
            if (mediaContent == null)
            {
                return new ValidationResult("指定されたメディアが見つかりませんでした。");
            }

            var data = await mediaContent.GetContentAsync();
            var imageInfo = new MagickImageInfo(data);
            if (imageInfo.Width < (x + width) || imageInfo.Height < (y + height))
            {
                return new ValidationResult("指定されたサイズは画像のサイズを超えています。");
            }

            // リサイズするよ!
            using (var image = new MagickImage(data))
            {
                image.Crop(new MagickGeometry(x, y, width, height));
                image.Page = new MagickGeometry(0, 0, width, height);
                
                // そして更新
                await _mediaRepository.Update(mediaInfo, image.ToByteArray());
            }

            return ValidationResult.Success;
        }
Esempio n. 2
2
        private static void Process(int width, int height, MagickImage image, int? quality)
        {
            image.Strip();

            if (quality.HasValue)
            {
                image.Quality = quality.Value;
            }

            //模版的宽高比例
            var templateRate = (double)width / height;

            //原图片的宽高比例
            var nowRate = (double)image.Width / image.Height;

            if (templateRate < nowRate)
            {
                //以高为准缩放
                // Resize each image in the collection to a width of 200. When zero is specified for the height
                // the height will be calculated with the aspect ratio.
                image.Resize(0, height);
                image.ChopHorizontal(width, image.Width - width);
            }
            else
            {
                //以宽为准缩放
                image.Resize(width, 0);
                image.ChopVertical(height, image.Height - height);
            }
        }
Esempio n. 3
1
        public string Execute(FileItem item, string infile, string dest, ValuePairEnumerator configData)
        {
            var conf = new CropTransformViewModel(configData);
            using (MagickImage image = new MagickImage(infile))
            {
                if (conf.FromLiveView && ServiceProvider.DeviceManager.SelectedCameraDevice != null)
                {
                    var prop = ServiceProvider.DeviceManager.SelectedCameraDevice.LoadProperties();
                    conf.Left = (int) (image.Width*prop.LiveviewSettings.HorizontalMin/100);
                    conf.Width = (image.Width*
                                  (prop.LiveviewSettings.HorizontalMax - prop.LiveviewSettings.HorizontalMin)/100);
                    conf.Top = (image.Height*prop.LiveviewSettings.VerticalMin/100);
                    conf.Height = (image.Height*(prop.LiveviewSettings.VerticalMax - prop.LiveviewSettings.VerticalMin)/
                                   100);
                }
                if (conf.CropMargins)
                {
                    conf.Left = image.Width * conf.WidthProcent / 100;
                    conf.Width = image.Width - (conf.Left*2);
                    conf.Top = image.Height * conf.HeightProcent / 100;
                    conf.Height = image.Height - (conf.Top*2);
                }

                MagickGeometry geometry = new MagickGeometry();
                geometry.Width = conf.Width;
                geometry.Height = conf.Height;
                geometry.X = conf.Left;
                geometry.Y = conf.Top;
                image.Crop(geometry);
                image.Format = MagickFormat.Jpeg;
                image.Write(dest);
            }
            return dest;
        }
Esempio n. 4
1
    public void Test_Image_ByteArray()
    {
      using (Image img = Image.FromFile(Files.Coders.PageTIF))
      {
        byte[] bytes = null;
        using (MemoryStream memStream = new MemoryStream())
        {
          img.Save(memStream, ImageFormat.Tiff);
          bytes = memStream.GetBuffer();
        }

        using (MagickImage image = new MagickImage(bytes))
        {
          image.CompressionMethod = CompressionMethod.Group4;

          using (MemoryStream memStream = new MemoryStream())
          {
            image.Write(memStream);
            memStream.Position = 0;

            using (MagickImage before = new MagickImage(Files.Coders.PageTIF))
            {
              using (MagickImage after = new MagickImage(memStream))
              {
                Assert.AreEqual(0.0, before.Compare(after, ErrorMetric.RootMeanSquared));
              }
            }
          }
        }
      }
    }
Esempio n. 5
0
    public void Test_IptcProfile()
    {
      using (MagickImage input = new MagickImage(Files.MagickNETIconPNG))
      {
        IptcProfile profile = input.GetIptcProfile();
        Assert.IsNull(profile);

        profile = new IptcProfile();
        profile.SetValue(IptcTag.Headline, "Magick.NET");
        profile.SetValue(IptcTag.CopyrightNotice, "Copyright.NET");

        input.AddProfile(profile);

        using (MemoryStream memStream = new MemoryStream())
        {
          input.Format = MagickFormat.Tiff;
          input.Write(memStream);

          memStream.Position = 0;
          using (MagickImage output = new MagickImage(memStream))
          {
            profile = output.GetIptcProfile();
            Assert.IsNotNull(profile);
            TestValue(profile, IptcTag.Headline, "Magick.NET");
            TestValue(profile, IptcTag.CopyrightNotice, "Copyright.NET");
          }
        }
      }
    }
Esempio n. 6
0
 public static void sharpen(string image_path, string output_path, double radius = 5, double sigma = 30)
 {
     using (MagickImage image = new MagickImage(image_path)) {
         image.Sharpen(radius, sigma);
         image.Write(output_path);
     }
 }
Esempio n. 7
0
    public void Test_Constructor()
    {
      using (MemoryStream memStream = new MemoryStream())
      {
        using (MagickImage image = new MagickImage(Files.ImageMagickJPG))
        {
          ExifProfile profile = image.GetExifProfile();
          Assert.IsNull(profile);

          profile = new ExifProfile();
          profile.SetValue(ExifTag.Copyright, "Dirk Lemstra");

          image.AddProfile(profile);

          profile = image.GetExifProfile();
          Assert.IsNotNull(profile);

          image.Write(memStream);
        }

        memStream.Position = 0;
        using (MagickImage image = new MagickImage(memStream))
        {
          ExifProfile profile = image.GetExifProfile();

          Assert.IsNotNull(profile);
          Assert.AreEqual(1, profile.Values.Count());

          ExifValue value = profile.Values.FirstOrDefault(val => val.Tag == ExifTag.Copyright);
          TestValue(value, "Dirk Lemstra");
        }
      }
    }
Esempio n. 8
0
    public void Test_RemoveAlpha()
    {
      string tempFile = GetTemporaryFileName(".png");

      try
      {
        using (MagickImage image = new MagickImage(Files.MagickNETIconPNG))
        {
          Assert.IsTrue(image.HasAlpha);
          image.ColorAlpha(new MagickColor("yellow"));
          image.HasAlpha = true;
          image.Write(tempFile);

          image.Read(tempFile);

          Assert.IsTrue(image.HasAlpha);

          PngOptimizer optimizer = new PngOptimizer();
          optimizer.LosslessCompress(tempFile);

          image.Read(tempFile);
          Assert.IsFalse(image.HasAlpha);
        }
      }
      finally
      {
        File.Delete(tempFile);
      }
    }
        public Image <TPixel> ReadPict <TPixel>(Configuration configuration, string filename)
            where TPixel : unmanaged, SixLabors.ImageSharp.PixelFormats.IPixel <TPixel>
        {
            using Magick.MagickImage magickImage = new Magick.MagickImage(filename);
            var width  = magickImage.Width;
            var height = magickImage.Height;

            var image = new Image <TPixel>(configuration, width, height);


            var framePixels = image.GetPixelMemoryGroup();

            using Magick.IUnsafePixelCollection <ushort> pixels = magickImage.GetPixelsUnsafe();

            if (magickImage.Depth == 8 || magickImage.Depth == 6 || magickImage.Depth == 4 || magickImage.Depth == 2 || magickImage.Depth == 1 || magickImage.Depth == 10 || magickImage.Depth == 12)
            {
                byte[]? data = pixels.ToByteArray(Magick.PixelMapping.RGBA);

                FromRgba32Bytes(configuration, data, framePixels);
            }
            else if (magickImage.Depth == 16 || magickImage.Depth == 14)
            {
                ushort[]? data = pixels.ToShortArray(Magick.PixelMapping.RGBA);
                Span <byte> bytes = MemoryMarshal.Cast <ushort, byte>(data.AsSpan());
                FromRgba64Bytes(configuration, bytes, framePixels);
            }
            else
            {
                throw new InvalidOperationException();
            }

            return(image);
        }
Esempio n. 10
0
    public static void UsingColors()
    {
      using (MagickImage image = new MagickImage(SampleFiles.SnakewarePng))
      {
        image.TransparentChroma(Color.Black, Color.Blue);
        image.BackgroundColor = new ColorMono(true);

        // Q16 (Blue):
        image.TransparentChroma(new MagickColor(0, 0, 0), new MagickColor(0, 0, 65535));
        image.TransparentChroma(new ColorRGB(0, 0, 0), new ColorRGB(0, 0, 65535));
        image.BackgroundColor = new MagickColor("#00f");
        image.BackgroundColor = new MagickColor("#0000ff");
        image.BackgroundColor = new MagickColor("#00000000ffff");

        // With transparency (Red):
        image.BackgroundColor = new MagickColor(0, 0, 65535, 32767);
        image.BackgroundColor = new MagickColor("#0000ff80");

        // Q8 (Green):
        image.TransparentChroma(new MagickColor(0, 0, 0), new MagickColor(0, 255, 0));
        image.TransparentChroma(new ColorRGB(0, 0, 0), new ColorRGB(0, 255, 0));
        image.BackgroundColor = new MagickColor("#0f0");
        image.BackgroundColor = new MagickColor("#00ff00");
      }
    }
Esempio n. 11
0
 public static void AreEqual(MagickColor expected, MagickImage image, int x, int y)
 {
   using (PixelCollection pixels = image.GetPixels())
   {
     AreEqual(expected, pixels.GetPixel(x, y));
   }
 }
Esempio n. 12
0
    public static void ExceptionHandling()
    {
      try
      {
        // Read invalid jpg file
        using (MagickImage image = new MagickImage(SampleFiles.InvalidFileJpg))
        {
        }
      }
      // Catch any MagickException
      catch (MagickException exception)
      {
        // Write excepion raised when reading the invalid jpg to the console
        Console.WriteLine(exception.Message);
      }

      try
      {
        // Read corrupt jpg file
        using (MagickImage image = new MagickImage(SampleFiles.CorruptImageJpg))
        {
        }
      }
      // Catch only MagickCorruptImageErrorException
      catch (MagickCorruptImageErrorException exception)
      {
        // Write excepion raised when reading the corrupt jpg to the console
        Console.WriteLine(exception.Message);
      }
    }
Esempio n. 13
0
    public void Test_AlphaUnblend()
    {
      MagickReadSettings settings = new MagickReadSettings()
      {
        Defines = new PsdReadDefines()
        {
          AlphaUnblend = false
        }
      };

      using (MagickImage image = new MagickImage())
      {
        image.Read(Files.Coders.PlayerPSD, settings);

        string define = image.Settings.GetDefine(MagickFormat.Psd, "alpha-unblend");
        Assert.AreEqual("False", define);
      }

      using (MagickImage image = new MagickImage())
      {
        settings.Defines = new PsdReadDefines()
        {
          AlphaUnblend = true
        };

        image.Read(Files.Coders.PlayerPSD, settings);

        string define = image.Settings.GetDefine(MagickFormat.Psd, "alpha-unblend");
        Assert.IsNull(define);
      }
    }
Esempio n. 14
0
    public void Test_Log()
    {
      using (MagickImage image = new MagickImage(Files.SnakewarePNG))
      {
        int count = 0;
        EventHandler<LogEventArgs> logDelegate = delegate (object sender, LogEventArgs arguments)
        {
          Assert.IsNull(sender);
          Assert.IsNotNull(arguments);
          Assert.AreNotEqual(LogEvents.None, arguments.EventType);
          Assert.IsNotNull(arguments.Message);
          Assert.AreNotEqual(0, arguments.Message.Length);

          count++;
        };

        MagickNET.Log += logDelegate;

        image.Flip();
        Assert.AreEqual(0, count);

        MagickNET.SetLogEvents(LogEvents.All);

        image.Flip();
        Assert.AreNotEqual(0, count);

        MagickNET.Log -= logDelegate;
        count = 0;

        image.Flip();
        Assert.AreEqual(0, count);
      }
    }
Esempio n. 15
0
    public void Test_DctMethod_OptimizeCoding_Quality_QuantizationTables_SamplingFactors()
    {
      JpegWriteDefines defines = new JpegWriteDefines()
      {
        DctMethod = DctMethod.Fast,
        OptimizeCoding = false,
        Quality = new MagickGeometry(80, 80),
        QuantizationTables = @"C:\path\to\file.xml",
        SamplingFactors = new MagickGeometry[]
        {
          new MagickGeometry(5, 10),
          new MagickGeometry(15, 20)
        }
      };

      using (MagickImage image = new MagickImage(Files.Builtin.Logo))
      {
        image.Settings.SetDefines(defines);

        Assert.AreEqual("Fast", image.Settings.GetDefine(MagickFormat.Jpeg, "dct-method"));
        Assert.AreEqual("False", image.Settings.GetDefine(MagickFormat.Jpeg, "optimize-coding"));
        Assert.AreEqual("80x80", image.Settings.GetDefine(MagickFormat.Jpeg, "quality"));
        Assert.AreEqual(@"C:\path\to\file.xml", image.Settings.GetDefine(MagickFormat.Jpeg, "q-table"));
        Assert.AreEqual("5x10,15x20", image.Settings.GetDefine(MagickFormat.Jpeg, "sampling-factor"));
      }
    }
        public void WhenCompareItToTheScreenshot(string screenshotName)
        {
            using (var leftImage = new MagickImage(new FileInfo(this.screenshotFileName)))
            {
                using (var rightImage = new MagickImage())
                {
                    using (var extractResource = EmbeddedResources.ExtractResource(Assembly.GetExecutingAssembly().GetName().Name, "Screenshots", screenshotName))
                    {
                        rightImage.Read(extractResource);
                    }

                    MagickImage diffImage = null;

                    try
                    {
                        this.screenshotDistortion = this.screenShotService.Compare(leftImage, rightImage, out diffImage);
                    }
                    finally
                    {
                        if (diffImage != null)
                        {
                            var diffFileName = Path.GetFileNameWithoutExtension(this.screenshotFileName) + "_diff" + Path.GetExtension(this.screenshotFileName);
                            // ReSharper disable once AssignNullToNotNullAttribute
                            diffImage.Write(Path.Combine(Path.GetDirectoryName(this.screenshotFileName), diffFileName));
                            diffImage.Dispose();
                        }
                    }
                }
            }
        }
Esempio n. 17
0
 public static void AreNotEqual(MagickColor notExpected, MagickImage image, int x, int y)
 {
   using (PixelCollection collection = image.GetPixels())
   {
     AreNotEqual(notExpected, collection.GetPixel(x, y));
   }
 }
Esempio n. 18
0
        private static async Task <byte[]> NormalizeImageAsync(byte[] imageData)
        {
            return(await Task.Run <byte[]>(() =>
            {
                // https://github.com/tesseract-ocr/tesseract/wiki/ImproveQuality
                var image = new ImageMagick.MagickImage(imageData);

                image.AutoOrient();

                image.Density = new Density(300);

                image.Despeckle();

                image.Normalize();

                image.Grayscale();

                //image.Negate();

                //image.AdaptiveThreshold(25, 10, 5);

                //image.ContrastStretch(new Percentage(0), new Percentage(0));

                //image.Negate();

                return image.ToByteArray(ImageMagick.MagickFormat.Tiff);
            }));
        }
Esempio n. 19
0
 public void Test_Format()
 {
   using (MagickImage image = new MagickImage(Files.Coders.CartoonNetworkStudiosLogoAI))
   {
     Test_Image(image);
   }
 }
Esempio n. 20
0
    public void Test_RemoveAlpha()
    {
      string tempFile = Path.GetTempPath() + Guid.NewGuid().ToString() + ".png";
      try
      {
        using (MagickImage image = new MagickImage(Files.MagickNETIconPNG))
        {
          Assert.IsTrue(image.HasAlpha);
          image.ColorAlpha(new MagickColor("yellow"));
          image.HasAlpha = true;
          image.Write(tempFile);

          image.Read(tempFile);

          // TODO: Figure out why this does not fail in a single run but does when all tests are run.
          //Assert.IsTrue(image.HasAlpha);

          PngOptimizer optimizer = new PngOptimizer();
          optimizer.LosslessCompress(tempFile);

          image.Read(tempFile);
          Assert.IsFalse(image.HasAlpha);
        }
      }
      finally
      {
        if (File.Exists(tempFile))
          File.Delete(tempFile);
      }
    }
Esempio n. 21
0
 public static void crop(string image_path, string output_path, Tuple<int, int> from, Tuple<int, int> to)
 {
     using (MagickImage image = new MagickImage(image_path)) {
         image.Crop(new MagickGeometry(from.Item1, from.Item2, to.Item1 - from.Item1, to.Item2 - from.Item2));
         image.Write(output_path);
     }
 }
Esempio n. 22
0
 public static void scale(string image_path, string output_path, int width_mul = 150, int height_mul = 150)
 {
     using (MagickImage image = new MagickImage(image_path)) {
         image.Scale(new Percentage(width_mul), new Percentage(height_mul));
         image.Write(output_path);
     }
 }
Esempio n. 23
0
    public void Test_PreserveiCCP_SwapBytes()
    {
      PngReadDefines defines = new PngReadDefines()
      {
        PreserveiCCP = true,
        SwapBytes = false
      };

      using (MagickImage image = new MagickImage())
      {
        image.Settings.SetDefines(defines);

        Assert.AreEqual("True", image.Settings.GetDefine(MagickFormat.Png, "preserve-iCCP"));
        Assert.AreEqual(null, image.Settings.GetDefine(MagickFormat.Png, "swap-bytes"));
      }

      defines = new PngReadDefines()
      {
        PreserveiCCP = false,
        SwapBytes = true
      };

      using (MagickImage image = new MagickImage())
      {
        image.Settings.SetDefines(defines);

        Assert.AreEqual(null, image.Settings.GetDefine(MagickFormat.Png, "preserve-iCCP"));
        Assert.AreEqual("True", image.Settings.GetDefine(MagickFormat.Png, "swap-bytes"));
      }
    }
Esempio n. 24
0
 public static void blur(string image_path, string output_path, double width = 2, double sigma = 2)
 {
     using (MagickImage image = new MagickImage(image_path)) {
         image.GaussianBlur(width, sigma);
         image.Write(output_path);
     }
 }
Esempio n. 25
0
    private static void TestPixels(MagickImage image, MagickColor firstRow, MagickColor secondRow)
    {
      using (PixelCollection pixels = image.GetPixels())
      {
        for (int y = 0; y < 2; y++)
          for (int x = 0; x < 10; x++)
            ColorAssert.AreEqual(y == 0 ? firstRow : secondRow, pixels.GetPixel(x, y).ToColor());
      }

      using (MemoryStream memStream = new MemoryStream())
      {
        image.Format = MagickFormat.Bmp;
        image.Write(memStream);
        memStream.Position = 0;

        using (MagickImage output = new MagickImage(memStream))
        {
          using (PixelCollection pixels = output.GetPixels())
          {
            for (int y = 0; y < 2; y++)
              for (int x = 0; x < 10; x++)
                ColorAssert.AreEqual(y == 0 ? firstRow : secondRow, pixels.GetPixel(x, y).ToColor());
          }
        }
      }
    }
        private bool MagickConvert()
        {
            try
            {
                using (MagickImage image = new MagickImage(m_filePath))
                {
                    //Use PNG if the image have an alpha channel
                    if (image.HasAlpha)
                    {
                        m_tempFilePath = Path.GetDirectoryName(m_filePath) + @"\" + Path.GetFileNameWithoutExtension(m_filePath) + ".png";
                        Framework.Log("Alpha channel found, using PNG");
                    }
                    else
                    {
                        m_tempFilePath = Path.GetDirectoryName(m_filePath) + @"\" + Path.GetFileNameWithoutExtension(m_filePath) + ".bmp";
                    }

                    image.Write(m_tempFilePath);

                    Framework.Log("(Magick) Temporary image saved: " + m_tempFilePath);
                }
                return true;
            }
            catch (InvalidCastException e)
            {
                Framework.ShowError("Unable to save the temporary image at: " + m_tempFilePath);
                return false;
            }
        }
 public static void ConvertCR2ToJPG()
 {
   using (MagickImage image = new MagickImage(SampleFiles.StillLifeCR2))
   {
     image.Write(SampleFiles.OutputDirectory + "StillLife.jpg");
   }
 }
Esempio n. 28
0
		//public PhotoInfo ReadExif2(string name)
		//{
		//	PhotoInfo info = new PhotoInfo() { FileName = name };

		//	using (MagickImage image = new MagickImage(name))
		//	{
		//		ExifProfile profile = image.GetExifProfile();

		//		ExifValue value = profile.GetValue(ExifTag.DateTimeDigitized);

		//		if (value.Value == null)
		//			throw new Exception("Неудалось считать дату и время файла");

		//		info.DateTimeDigitized = (DateTime)value.Value;

		//		value = profile.GetValue(ExifTag.Model);

		//		info.Model = (string)value.Value;

		//		if (info.Model == null)
		//			info.Model = "Неизвестная модель";

		//	}

		//	return info;
		//}

		public static void WriteExif(PhotoInfo info, int? quality)
        {
			// Для моего телефона не работает метод image.AddProfile. Т.к. для моего телефона дату менять ненадо, то пропускаем.
			if (info.Model.ToUpper().Contains("HUAWEI P7-L10"))
				return;

			using (MagickImage image = new MagickImage(info.FileName))
            {
				if (quality != null && quality < image.Quality)
					image.Quality = quality.Value;

                ExifProfile profile = image.GetExifProfile();

				if (profile == null)
					profile = new ExifProfile();

                profile.SetValue(ExifTag.DateTimeDigitized, info.DateTimeDigitized.ToString(DATE_TIME_FORMAT));
				profile.SetValue(ExifTag.DateTime, info.DateTimeDigitized.ToString(DATE_TIME_FORMAT));
				profile.SetValue(ExifTag.DateTimeOriginal, info.DateTimeDigitized.ToString(DATE_TIME_FORMAT));

				//try
				//{
					image.AddProfile(profile, true);

					image.Write(info.FileName);
				//}
				//catch (Exception exc)
				//{ 
				
				//}
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Returns the path to the sketch image just created
        /// <param name="mask">Mask image of the button</param>
        /// <param name="texture">Texture image of the item</param>
        /// <param name="nameSketch">Name of the image to create</param>
        public static string CreateSketchesPath(string mask, string texture, string nameSketch)
        {
            MagickImage Mask = new MagickImage(mask);

            MagickImage Texture = new MagickImage(texture);

            Texture.Crop(Mask.Width, Mask.Height);

            Texture.Composite(Mask, CompositeOperator.CopyAlpha);
            Mask.Composite(Texture, CompositeOperator.Multiply);
            MagickImage sketch = Mask;

            try
            {
                // sketch.Write(Helpers.ResourcesHelper.SketchesPath() + nameSketch);
                string p = Helpers.ResourcesHelper.SketchesPath() + nameSketch;
                System.IO.Stream s = new System.IO.FileStream(p, System.IO.FileMode.Create);

                sketch.Write(s);
                s.Close();
            }
            catch (MagickException ex)
            {
                string s= ex.Message;
            }
            catch
            {

            }
            sketch.Dispose();
            sketch = null;
            string path = Helpers.ResourcesHelper.SketchesPath() + nameSketch;
            return path;
        }
Esempio n. 30
0
    public static void ConvertImageFromOneFormatToAnother()
    {
      // Read first frame of gif image
      using (MagickImage image = new MagickImage(SampleFiles.SnakewareGif))
      {
        // Save frame as jpg
        image.Write(SampleFiles.OutputDirectory + "Snakeware.jpg");
      }

      MagickReadSettings settings = new MagickReadSettings();
      // Tells the xc: reader the image to create should be 800x600
      settings.Width = 800;
      settings.Height = 600;

      using (MemoryStream memStream = new MemoryStream())
      {
        // Create image that is completely purple and 800x600
        using (MagickImage image = new MagickImage("xc:purple", settings))
        {
          // Sets the output format to png
          image.Format = MagickFormat.Png;
          // Write the image to the memorystream
          image.Write(memStream);
        }
      }

      // Read image from file
      using (MagickImage image = new MagickImage(SampleFiles.SnakewarePng))
      {
        // Sets the output format to jpeg
        image.Format = MagickFormat.Jpeg;
        // Create byte array that contains a jpeg file
        byte[] data = image.ToByteArray();
      }
    }
Esempio n. 31
0
    public void Test_Disabled()
    {
      using (MemoryStream memStream = new MemoryStream())
      {
        using (StreamWriter writer = new StreamWriter(memStream))
        {
          writer.Write(@"push graphic-context
              viewbox 0 0 640 480
              image over 0,0 0,0 ""label:Magick.NET""
              pop graphic-context");

          writer.Flush();

          memStream.Position = 0;

          using (MagickImage image = new MagickImage())
          {
            ExceptionAssert.Throws<MagickMissingDelegateErrorException>(delegate ()
            {
              image.Read(memStream);
            });

            ExceptionAssert.Throws<MagickPolicyErrorException>(delegate ()
            {
              MagickReadSettings settings = new MagickReadSettings()
              {
                Format = MagickFormat.Mvg
              };

              image.Read(memStream, settings);
            });
          }
        }
      }
    }
Esempio n. 32
0
        /// <summary>
        /// Método que trata a imagem e copia para a pasta de saída
        /// </summary>
        /// <param name="arq">Imagem a ser editada</param>
        /// <param name="width">Define  o Width da imagem de saída</param>
        /// <param name="height">Define o height da imagem de saída</param>
        /// <param name="transparent">Identifica se deve deixar a imagem com o fundo transparent ou não</param>
        /// <returns>True - Sucesso; False - Erro</returns>
        public bool TrataImagem(FileInfo arq, int width, int height, bool transparent, ref string mensagemErro)
        {
            mensagemErro = "";
            try
            {
                ImageMagick.MagickImage img = new ImageMagick.MagickImage(arq);

                if (transparent)
                {
                    img.ColorFuzz = new Percentage(10);
                    // -transparent white
                    img.Transparent(MagickColors.White);
                }

                img.Resize(width, height);
                img.Write(caminhoSaida + "\\" + arq.Name.Replace(arq.Extension, width.ToString() + "x" + height.ToString()) + cbx_tipos.SelectedItem.ToString());

                return(true);
            }
            catch (Exception e)
            {
                mensagemErro = "Erro ao tratar a imagem " + arq.FullName + ". Erro " + e.Message;
                return(false);
            }
        }
Esempio n. 33
0
        /// <summary>
        /// 设置图片水印,使用MagickImage.Net
        /// </summary>
        /// <param name="path">需要加载水印的图片路径(绝对路径)</param>
        /// <param name="waterpath">水印图片(绝对路径)</param>
        /// <param name="location">水印位置</param>
        /// <returns></returns>
        public static string ImageWatermarkByMagick(string path, string waterpath, ImageLocationMode location)
        {
            string extName = Path.GetExtension(path);

            if (string.IsNullOrEmpty(extName))
            {
                return(path);
            }
            extName = extName.ToLower();
            if (!(extName == ".jpg" || extName == ".bmp" || extName == ".jpeg" || extName == ".png"))
            {
                return(path);
            }
            // 读取需要水印的图片
            using (ImageMagick.MagickImage image = new ImageMagick.MagickImage(path))
            {
                // 读取水印图片
                using (ImageMagick.MagickImage watermark = new ImageMagick.MagickImage(waterpath))
                {
                    // 设置水印透明度
                    //watermark.Evaluate(Channels.Alpha, EvaluateOperator.Divide, 7);
                    // 设置绘制水印位置
                    image.Composite(watermark, GetLocation(location), CompositeOperator.Over);
                }
                image.Resize(image.Width, image.Height);
                image.Quality           = 75;
                image.CompressionMethod = ImageMagick.CompressionMethod.JPEG;
                image.Write(path);
                return(path);
            }
        }
Esempio n. 34
0
        public MagickImage(ImageMagick.MagickImage image, IImageCodec codec)
        {
            if (image is null)
            {
                throw new ArgumentNullException(nameof(image));
            }

            this.image = image;
            Format     = GetImageFormatFromMagickFormat(image.Format);
            Codec      = codec;
        }
Esempio n. 35
0
        private void Save(ImageMagick.MagickImage magickImage, Stream stream, IImageEncoderOptions encoderOptions)
        {
            if (imageFormat is object)
            {
                magickImage.Format = GetMagickFormatForFileExtension(imageFormat.Extensions.FirstOrDefault());
            }

            magickImage.Quality = encoderOptions.Quality;

            magickImage.Write(stream);
        }
Esempio n. 36
0
			// Get image from Imagick
			protected byte[] GetImageFromImagick(Dictionary<string, string> chart)
			{
				string svgdata = chart["stream"];
				if (Empty(svgdata))
					return null;
				svgdata = svgdata.Replace("+", " "); // Replace + to ' '

				// IMPORTANT NOTE: Magick.NET does not support SVG syntax: fill="url('#id')". Need to replace the attributes:
				// - fill="url('#id')" style="fill-opacity: n1; ..."
				// to:
				// - fill="color" style="fill-opacity: n2; ..."
				// from xml below:
				// <linearGradient ... id="id">
				// <stop stop-opacity="0.5" stop-color="#ff0000" offset="0%"></stop>
				// ...</linearGradient>

				var doc = new XmlDocument();
				doc.LoadXml(svgdata);
				var nodes = doc.SelectNodes("//*[@fill]");
				foreach (XmlElement node in nodes) {
					string fill = node.GetAttribute("fill");
					string style = node.GetAttribute("style");
					if (fill.StartsWith("url(") && fill.Substring(5, 1) == "#") {
						var id = fill.Substring(6, fill.Length - 8);
						var nsmgr = new XmlNamespaceManager(doc.NameTable);
						nsmgr.AddNamespace("ns", "http://www.w3.org/2000/svg");
						var gnode = doc.SelectSingleNode("//*/ns:linearGradient[@id='" + id + "']", nsmgr);
						if (gnode != null) {
							XmlElement snode = (XmlElement)gnode.SelectSingleNode("ns:stop[@offset='0%']", nsmgr);
							if (snode != null) {
								var fillcolor = snode.GetAttribute("stop-color");
								var fillopacity = snode.GetAttribute("stop-opacity");
								if (!Empty(fillcolor))
									node.SetAttribute("fill", fillcolor);
								if (!Empty(fillopacity) && !Empty(style)) {
									style = Regex.Replace(style, @"fill-opacity:\s*\S*;", "fill-opacity: " + fillopacity + ";");
									node.SetAttribute("style", style);
								}
							}
						}
					}
				}
				svgdata = doc.DocumentElement.OuterXml;
				ImageMagick.MagickNET.SetLogEvents(ImageMagick.LogEvents.All);
				ImageMagick.MagickReadSettings settings = new ImageMagick.MagickReadSettings();
				settings.ColorSpace = ImageMagick.ColorSpace.RGB;
				settings.Format = ImageMagick.MagickFormat.Svg;
				using var image = new ImageMagick.MagickImage(Encoding.UTF8.GetBytes(svgdata), settings);

				//image.BackgroundColor = new ImageMagick.MagickColor(System.Drawing.Color.Transparent);
				image.Format = ImageMagick.MagickFormat.Png;
				return image.ToByteArray();
			}
Esempio n. 37
0
        public static Engine.Surface.Canvas Blur(Engine.Surface.Canvas c, double radius, double sigma)
        {
            Bitmap bmp = Engine.Surface.Ops.ToBitmap(c);

            using (ImageMagick.MagickImage image = new ImageMagick.MagickImage(bmp))
            {
                image.Blur(radius, sigma);

                bmp = image.ToBitmap();
            }

            return(Engine.Surface.Ops.ToCanvas(bmp));
        }
Esempio n. 38
0
 public static Bitmap cannyedge(Image sourceimg)
 {
     if (sourceimg != null)
     {
         ImageMagick.MagickImage originalMagickImage;
         originalMagickImage = new ImageMagick.MagickImage((Bitmap)sourceimg);
         originalMagickImage.CannyEdge();
         Bitmap bitmap = originalMagickImage.ToBitmap();
         return(bitmap);
     }
     else
     {
         return((Bitmap)sourceimg);
     }
 }
Esempio n. 39
0
 public static Bitmap oilpaint(Image sourceimg)
 {
     if (sourceimg != null)
     {
         ImageMagick.MagickImage originalMagickImage;
         originalMagickImage = new ImageMagick.MagickImage((Bitmap)sourceimg);
         originalMagickImage.OilPaint();
         Bitmap bitmap = originalMagickImage.ToBitmap();
         return(bitmap);
     }
     else
     {
         return((Bitmap)sourceimg);
     }
 }
Esempio n. 40
0
 public static Bitmap arc(Image sourceimg)
 {
     if (sourceimg != null)
     {
         ImageMagick.MagickImage originalMagickImage;
         originalMagickImage = new ImageMagick.MagickImage((Bitmap)sourceimg);
         originalMagickImage.Distort(DistortMethod.Arc, 360);
         Bitmap bitmap = originalMagickImage.ToBitmap();
         return(bitmap);
     }
     else
     {
         return((Bitmap)sourceimg);
     }
 }
Esempio n. 41
0
 public static Bitmap decode(Image sourceimg, string code)
 {
     if (sourceimg != null)
     {
         ImageMagick.MagickImage originalMagickImage;
         originalMagickImage = new ImageMagick.MagickImage((Bitmap)sourceimg);
         originalMagickImage.Decipher(code);
         Bitmap bitmap = originalMagickImage.ToBitmap();
         return(bitmap);
     }
     else
     {
         return((Bitmap)sourceimg);
     }
 }
Esempio n. 42
0
 public static Bitmap charcoal(Image sourceimg)
 {
     if (sourceimg != null)
     {
         ImageMagick.MagickImage originalMagickImage;
         originalMagickImage = new ImageMagick.MagickImage((Bitmap)sourceimg);
         originalMagickImage.Charcoal(5, 0);
         Bitmap bitmap = originalMagickImage.ToBitmap();
         return(bitmap);
     }
     else
     {
         return((Bitmap)sourceimg);
     }
 }
Esempio n. 43
0
 public static Bitmap reducenoise(Image sourceimg)
 {
     if (sourceimg != null)
     {
         ImageMagick.MagickImage originalMagickImage;
         originalMagickImage = new ImageMagick.MagickImage((Bitmap)sourceimg);
         originalMagickImage.ReduceNoise();
         Bitmap bitmap = originalMagickImage.ToBitmap();
         return(bitmap);
     }
     else
     {
         return((Bitmap)sourceimg);
     }
 }
Esempio n. 44
0
 public static Bitmap sepiatone(Image sourceimg)
 {
     if (sourceimg != null)
     {
         ImageMagick.MagickImage originalMagickImage;
         originalMagickImage = new ImageMagick.MagickImage((Bitmap)sourceimg);
         originalMagickImage.SepiaTone();
         Bitmap bitmap = originalMagickImage.ToBitmap();
         return(bitmap);
     }
     else
     {
         return((Bitmap)sourceimg);
     }
 }
Esempio n. 45
0
        public async Task <MemoryStream> CreateImage(VetMember from, VetMember to, int amount)
        {
            var colorCode = AmountToColor(amount);

            //HttpClientBuilderExtensions
            HttpClient hc = new HttpClient();


            //キャンバス画像を作成 100*50pixel
            using (var myMagick = new ImageMagick.MagickImage(new ImageMagick.MagickColor(colorCode), 640, 128))
            {
                //var  hc.GetByteArrayAsync($"https://cdn.discordapp.com/avatars/{from.DiscordId}/{from.AvatarId}.png?size=128"));
                var tmpFilePath       = Path.GetTempPath();
                var fromImageFilePath = await GetImagePath(from);

                var toImageFilePath = await GetImagePath(to);

                using (var icon = new ImageMagick.MagickImage(fromImageFilePath))
                {
                    myMagick.Composite(icon);
                }

                using (var icon = new ImageMagick.MagickImage(toImageFilePath))
                {
                    myMagick.Composite(icon, new PointD(640 - 128, 0));
                }

                new Drawables()
                // Draw text on the image
                .FontPointSize(60)
                .Font("Comic Sans")
                .StrokeColor(MagickColors.White)
                .FillColor(MagickColors.White)
                //.TextAlignment(TextAlignment.Center)
                .Text(158, 64, $"{amount:#,0}{StaticSettings.CurrenryUnit}")
                // Add an ellipse
                .StrokeColor(new MagickColor(0, Quantum.Max, 0))
                //.FillColor(MagickColors.SaddleBrown)
                //.Ellipse(256, 96, 192, 8, 0, 360)
                .Draw(myMagick);

                MemoryStream ms = new MemoryStream();
                myMagick.Write(ms, MagickFormat.Png);

                ms.Seek(0, SeekOrigin.Begin);
                return(ms);
            }
        }
Esempio n. 46
0
        private ImageMagick.MagickImage originalMagickImage = null; // 图层图像修改前的状态
        //点击状态下饱和度调节
        private void MouseButtonDown(object sender, MouseButtonEventArgs args)
        {
            if (down == null)
            {
                return;
            }
            originalMagickImage = new ImageMagick.MagickImage(bitmap);
            ImageMagick.Percentage  brightness = new ImageMagick.Percentage(100);                  // 100%表示不改变该属性
            ImageMagick.Percentage  saturation = new ImageMagick.Percentage(50);
            ImageMagick.Percentage  hue        = new ImageMagick.Percentage(100);                  // 滑动条范围值0%~200%
            ImageMagick.MagickImage newImage   = new ImageMagick.MagickImage(originalMagickImage); // 相当于深复制
            newImage.Modulate(brightness, saturation, hue);

            // 重新给Image控件赋值新图像
            down   = newImage.ToBitmapSource();
            Source = down;
            originalMagickImage.Dispose();
        }
Esempio n. 47
0
 /// <summary>
 /// 色相、饱和度、亮度、对比度
 /// </summary>
 /// <param name="sourceimg"></param>
 /// <param name="threshold"></param>
 /// <returns></returns>
 public static Bitmap HSLC(Image sourceimg, int H, int S, int L, int C)
 {
     if (sourceimg != null)
     {
         ImageMagick.MagickImage originalMagickImage;
         originalMagickImage = new ImageMagick.MagickImage((Bitmap)sourceimg);
         // 只调整图像的Hue色相值
         ImageMagick.Percentage  brightness = new ImageMagick.Percentage(L);                    // 100%表示不改变该属性
         ImageMagick.Percentage  saturation = new ImageMagick.Percentage(S);
         ImageMagick.Percentage  hue        = new ImageMagick.Percentage(H);                    // 滑动条范围值0%~200%
         ImageMagick.MagickImage newImage   = new ImageMagick.MagickImage(originalMagickImage); // 相当于深复制
         newImage.Modulate(brightness, saturation, hue);
         // 重新给Image控件赋值新图像
         Bitmap bitmap1 = newImage.ToBitmap();
         Bitmap bitmap  = Contrast(bitmap1, C);
         return(bitmap);
     }
     else
     {
         return((Bitmap)sourceimg);
     }
 }
Esempio n. 48
0
        public void loaded(object sender, EventArgs args)
        {
            if (originalMagickImage == null)
            {
                up = Source;
                if (down == null)
                {
                    bitmap = ImageSourceToBitmap(this.Source); // img是前台Image控件
                    new Task(new Action(() =>
                    {
                        originalMagickImage = new ImageMagick.MagickImage(bitmap);
                        ImageMagick.Percentage brightness = new ImageMagick.Percentage(100);                  // 100%表示不改变该属性
                        ImageMagick.Percentage saturation = new ImageMagick.Percentage(50);
                        ImageMagick.Percentage hue        = new ImageMagick.Percentage(100);                  // 滑动条范围值0%~200%
                        ImageMagick.MagickImage newImage  = new ImageMagick.MagickImage(originalMagickImage); // 相当于深复制
                        newImage.Modulate(brightness, saturation, hue);

                        // 重新给Image控件赋值新图像
                        down = newImage.ToBitmapSource();
                    })).Start();
                }
            }
        }
Esempio n. 49
0
        public ActionResult CreateProduct(HttpPostedFileBase ImgFile, Product cProduct, string base64str)
        {
            if (ImgFile != null && ImgFile.ContentLength > 0)
            {
                //local
                string str  = "";
                string type = ImgFile.ContentType;
                if (ImgFile.ContentType == "image/jpg")
                {
                    str = ".jpg";
                }
                else if (ImgFile.ContentType == "image/jpeg")
                {
                    str = ".jpeg";
                }
                else if (ImgFile.ContentType == "image/png")
                {
                    str = ".png";
                }
                string fileName = cProduct.ProductID + str;
                var    path     = Path.Combine(Server.MapPath("~/Image"), fileName);
                ImgFile.SaveAs(path);
                cProduct.ProductImg = "~/Image/" + fileName;

                //compress
                using (ImageMagick.MagickImage oImage = new ImageMagick.MagickImage(path))
                {
                    oImage.Format     = ImageMagick.MagickFormat.Jpg;
                    oImage.ColorSpace = ImageMagick.ColorSpace.sRGB; //色盤採用sRGB
                    oImage.Quality    = 80;                          //壓縮率
                    oImage.Resize(200, 0);
                    oImage.Strip();
                    oImage.Write(path);
                }
                //db
                byte[] FileBytes;
                using (MemoryStream ms = new MemoryStream())
                {
                    ImgFile.InputStream.CopyTo(ms);
                    FileBytes = ms.GetBuffer();
                }
                cProduct.ProductImg_DB = FileBytes;
            }
            cProduct.Create_Date = DateTime.Now;
            cProduct.Delete_Flag = false;
            if (ModelState.IsValid)
            {
                if (db.Product.Any(p => p.ProductID.Equals(cProduct.ProductID)))    //判斷資料是否重複
                {
                    ViewBag.DBResultErrorMessage = cProduct.ProductID + "資料已重複";
                    return(View("CreateProduct", Session["UserTag"].ToString()));
                }
                try
                {
                    db.Product.Add(cProduct);
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    logger.Error(ex.Message);
                    ViewBag.DBResultErrorMessage = ex.Message;
                    return(View("CreateProduct", Session["UserTag"].ToString()));
                }

                ViewBag.DBResultErrorMessage = cProduct.ProductID + "新增成功!";
            }

            return(View("CreateProduct", Session["UserTag"].ToString()));
        }
Esempio n. 50
0
        public ActionResult CreateProduct(HttpPostedFileBase ImgFile, Product cProduct, string base64str)
        {
            //驗證檔案
            ImgUploadValidate ImgV = new ImgUploadValidate();

            ImgV.filesize = 2000; //限制2mb
            if (ImgV.UploadUserFile(ImgFile))
            {                     //檔案驗證成功
                //local
                string fileName = cProduct.ProductID + ImgV.contentType;
                var    path     = Path.Combine(Server.MapPath("~/Image"), fileName);
                ImgFile.SaveAs(path);
                cProduct.ProductImg = "~/Image/" + fileName;

                //compress
                using (ImageMagick.MagickImage oImage = new ImageMagick.MagickImage(path))
                {
                    oImage.Format     = MagickFormat.Jpg;
                    oImage.ColorSpace = ImageMagick.ColorSpace.sRGB; //色盤採用sRGB
                    oImage.Quality    = 80;                          //壓縮率
                    if (oImage.Height < 200)
                    {
                        oImage.Resize(0, 200);
                    }
                    oImage.Strip(); //去除圖片profile
                    oImage.Write(path);
                }
                //db
                byte[] FileBytes;
                using (MemoryStream ms = new MemoryStream())
                {
                    ImgFile.InputStream.CopyTo(ms);
                    FileBytes = ms.GetBuffer();
                }
                cProduct.ProductImg_DB = FileBytes;
                cProduct.Create_Date   = DateTime.Now;
                cProduct.Delete_Flag   = false;
                cProduct.Shelf_Flag    = true;
                if (ModelState.IsValid)
                {                                                                    //model驗證成功
                    if (db.Product.Any(p => p.ProductID.Equals(cProduct.ProductID))) //判斷資料是否重複
                    {
                        TempData["DBResultErrorMessage"] = cProduct.ProductID + "資料已重複,請重新輸入";
                        return(View("CreateProduct"));
                    }
                    try
                    {
                        db.Product.Add(cProduct);
                        db.SaveChanges();
                    }
                    catch (Exception ex)
                    {//資料庫異動例外狀況
                        logger.Error(ex.Message);
                        TempData["DBResultErrorMessage"] = ex.Message;
                        return(View("CreateProduct"));
                    }
                    TempData["DBResultErrorMessage"] = cProduct.ProductID + "新增成功!";
                    return(RedirectToAction("ProductList"));    //新增成功
                }
                else
                {   //model 驗證失敗
                    return(View("CreateProduct"));
                }
            }
            else
            {//檔案驗證失敗
                TempData["ImgValidate"] = ImgV.ErrorMessage;
                return(View("CreateProduct"));
            }
        }
Esempio n. 51
0
 public DrawingWand(MagickImage image)
 {
     _NativeInstance = new NativeDrawingWand(image, image.Settings.Drawing);
 }
Esempio n. 52
0
 internal static IMagickImage CreateIMagickImage(this IntPtr self)
 {
     return(MagickImage.Create(self));
 }
Esempio n. 53
0
 protected PixelCollection(MagickImage image)
 {
     Image           = image;
     _nativeInstance = new NativePixelCollection(image);
 }
Esempio n. 54
0
        private DrawableComposite(MagickImage image)
        {
            Throw.IfNull("image", image);

            _Image = image;
        }
 public UnsafePixelCollection(MagickImage image)
     : base(image)
 {
 }
Esempio n. 56
0
 /// <summary>
 /// Creates a new DrawableCompositeImage instance.
 /// </summary>
 /// <param name="offset">The offset from origin.</param>
 /// <param name="compose">The algorithm to use.</param>
 /// <param name="image">The image to draw.</param>
 public Drawables Composite(MagickGeometry offset, CompositeOperator compose, MagickImage image)
 {
     _Drawables.Add(new DrawableComposite(offset, compose, image));
     return(this);
 }
Esempio n. 57
0
 /// <summary>
 /// Creates a new DrawableCompositeImage instance.
 /// </summary>
 /// <param name="x">The X coordinate.</param>
 /// <param name="y">The Y coordinate.</param>
 /// <param name="compose">The algorithm to use.</param>
 /// <param name="image">The image to draw.</param>
 public Drawables Composite(double x, double y, CompositeOperator compose, MagickImage image)
 {
     _Drawables.Add(new DrawableComposite(x, y, compose, image));
     return(this);
 }
Esempio n. 58
0
 internal EightBimProfile(MagickImage image, byte[] data)
     : base("8bim", data)
 {
     _width  = image.Width;
     _height = image.Height;
 }
Esempio n. 59
0
        //public DateTime s_局部高清_處理方式 = DateTime.Now;

        /// <summary>
        ///
        /// </summary>
        public void func_局部高清_初始化()
        {
            String s_path     = ""; //圖片路徑
            double d_倍率       = 1;  //縮放倍率
            double d_倍率_old   = 1;  //超過500毫秒沒有進行縮放才重新算圖
            double d_x        = 1;  //圖片位置
            double d_y        = 1;
            double d_window_w = 1;  //視窗寬度
            double d_window_h = 1;
            int    int_旋轉角度   = 0;
            bool   bool_剪裁    = false;

            DateTime time_避免捲動中算圖 = DateTime.Now;//



            //-------------

            new Thread(() => {
                while (bool_程式運行中)
                {
                    //-------------

                    Thread.Sleep(100);

                    if (u_大量瀏覽模式 != null)
                    {
                        s_path = "";
                        continue;
                    }

                    if (bool_啟動局部高清 == false)
                    {
                        s_path = "";
                        continue;
                    }

                    //在程式預設開啟的資料夾不啟用
                    if (int_目前圖片位置 < ar_path.Count)
                    {
                        if (ar_path[int_目前圖片位置].IndexOf(fun_執行檔路徑() + "\\data\\imgs") == 0)
                        {
                            s_path = "";
                            continue;
                        }
                    }

                    /*
                     * if (this.Visibility != Visibility.Visible) {
                     *  //s_path = "";
                     *  Thread.Sleep(100);
                     *  continue;
                     * }*/


                    /*
                     * if (s_img_type_附檔名 == "PNG" || s_img_type_附檔名 == "JPG" ||
                     *  s_img_type_附檔名 == "TIF" || s_img_type_附檔名 == "BMP" ||
                     *  image_局部高清 != null) {
                     *
                     * } else {
                     *  continue;
                     * }*/



                    bool bool_重新繪製      = false;
                    bool bool_新圖片       = false;
                    bool bool_不剪裁且不重新繪製 = false;


                    C_adapter.fun_UI執行緒(() => {
                        try {
                            if (d_倍率 == img.ActualWidth && bool_剪裁 == false)
                            {
                                //System.Console.WriteLine("不剪裁且不重新繪製: " + ar_path[int_目前圖片位置]);
                                bool_不剪裁且不重新繪製 = true;
                            }

                            if (s_path != ar_path[int_目前圖片位置])
                            {
                                //System.Console.WriteLine("新圖片: " + ar_path[int_目前圖片位置]);

                                s_path         = ar_path[int_目前圖片位置];
                                bool_新圖片       = true;
                                bool_不剪裁且不重新繪製 = false;
                                bool_重新繪製      = true;

                                //讓新圖片一定能立即運算
                                d_倍率     = 0.123456;
                                d_倍率_old = img.ActualWidth;
                            }

                            if (d_倍率_old == img.ActualWidth)
                            {
                                //bool_重新繪製 = false;

                                if (d_倍率 != img.ActualWidth ||
                                    d_x != scrollviewer_1.ContentHorizontalOffset || d_y != scrollviewer_1.ContentVerticalOffset ||
                                    d_window_w != this.ActualWidth || d_window_h != this.ActualHeight ||
                                    int_旋轉角度 != c_旋轉.int_旋轉)
                                {
                                    d_倍率 = img.ActualWidth;

                                    d_x        = scrollviewer_1.ContentHorizontalOffset;
                                    d_y        = scrollviewer_1.ContentVerticalOffset;
                                    d_window_w = this.ActualWidth;
                                    d_window_h = this.ActualHeight;
                                    int_旋轉角度   = c_旋轉.int_旋轉;

                                    bool_重新繪製 = true;
                                }
                            }

                            if (((TimeSpan)(DateTime.Now - time_避免捲動中算圖)).TotalMilliseconds < 800)  //連點低於400毫秒

                            {
                            }
                            else
                            {
                                d_倍率_old     = img.ActualWidth;
                                time_避免捲動中算圖 = DateTime.Now;
                            }
                        } catch {
                            s_path    = "";
                            bool_重新繪製 = false;
                            return;
                        }
                    });


                    if (bool_不剪裁且不重新繪製)
                    {
                        continue;
                    }
                    if (bool_重新繪製 == false)
                    {
                        continue;
                    }



                    if (bool_新圖片)
                    {
                        try {
                            if (File.Exists(ar_path[int_目前圖片位置]))
                            {
                                if (image_局部高清 == null)
                                {
                                    var im5 = new ImageMagick.MagickImage((ar_path[int_目前圖片位置]));
                                    //

                                    //如果讀取完圖片後,使用者已經切換到其他圖片,就不要寫入到「image_局部高清」,直接解析新圖片
                                    if (int_目前圖片位置 < 0 || int_目前圖片位置 >= ar_path.Count || s_path != ar_path[int_目前圖片位置])
                                    {
                                        image_局部高清 = null;
                                        s_path     = null;
                                        im5        = null;
                                        continue;
                                    }
                                    else
                                    {
                                        image_局部高清 = im5;
                                    }

                                    //System.Console.WriteLine("一般  " + s_path);
                                }
                                else
                                {
                                    //image_局部高清 = new ImageMagick.MagickImage((ar_path[int_目前圖片位置]));
                                    //System.Console.WriteLine("特殊 " + s_path);
                                }


                                //https://www.smashingmagazine.com/2015/06/efficient-image-resizing-with-imagemagick/
                                //不使用 漸進式渲染
                                image_局部高清.Interlace = Interlace.NoInterlace;


                                //剝離所有配置文件和註釋的圖像。
                                image_局部高清.Strip();

                                //雙線性插值
                                //image_局部高清.FilterType = FilterType.Hann;
                            }
                            else
                            {
                                s_path = "";
                                continue;
                            }
                        } catch {
                            s_path = "";
                            System.Console.WriteLine("*******局部高清 失敗");
                            continue;
                        }
                    }

                    //避免已經切換到其他圖片
                    if (int_目前圖片位置 < 0 || int_目前圖片位置 >= ar_path.Count)
                    {
                        continue;
                    }
                    if (d_倍率 != img.ActualWidth || s_path != ar_path[int_目前圖片位置])
                    {
                        continue;
                    }
                    if (bool_啟動局部高清 == false)
                    {
                        s_path = "";
                        continue;
                    }

                    double w03    = 1;
                    double h03    = 1;
                    double l03    = 1;
                    double t03    = 1;
                    double d_縮放倍率 = 1;

                    C_adapter.fun_UI執行緒(() => {
                        w03 = scrollviewer_1.ViewportWidth;
                        h03 = scrollviewer_1.ViewportHeight;
                        l03 = scrollviewer_1.ContentHorizontalOffset;
                        t03 = scrollviewer_1.ContentVerticalOffset;

                        if (c_旋轉.bool_垂直鏡像)
                        {
                            t03 = scrollviewer_1.ScrollableHeight - t03;
                        }
                        if (c_旋轉.bool_水平鏡像)
                        {
                            l03 = scrollviewer_1.ScrollableWidth - l03;
                        }

                        if (c_旋轉.int_旋轉 == 0)
                        {
                            if (w03 > grid_img.ActualWidth)
                            {
                                w03 = grid_img.ActualWidth;
                            }
                            if (h03 > grid_img.ActualHeight)
                            {
                                h03 = grid_img.ActualHeight;
                            }
                        }

                        if (c_旋轉.int_旋轉 == 180)
                        {
                            if (w03 > grid_img.ActualWidth)
                            {
                                w03 = grid_img.ActualWidth;
                            }
                            if (h03 > grid_img.ActualHeight)
                            {
                                h03 = grid_img.ActualHeight;
                            }
                            l03 = scrollviewer_1.ScrollableWidth - l03;
                            t03 = scrollviewer_1.ScrollableHeight - t03;
                        }

                        if (c_旋轉.int_旋轉 == 90)
                        {
                            if (w03 > grid_img.ActualWidth)
                            {
                                h03 = grid_img.ActualHeight;
                            }
                            else
                            {
                                h03 = scrollviewer_1.ViewportWidth;
                            }

                            if (h03 > grid_img.ActualHeight)
                            {
                                w03 = grid_img.ActualWidth;
                            }
                            else
                            {
                                w03 = scrollviewer_1.ViewportHeight;
                            }

                            var zzz2 = scrollviewer_1.ScrollableWidth - l03;
                            l03      = t03;
                            t03      = zzz2;
                        }

                        if (c_旋轉.int_旋轉 == 270)
                        {
                            if (w03 > grid_img.ActualWidth)
                            {
                                h03 = grid_img.ActualHeight;
                            }
                            else
                            {
                                h03 = scrollviewer_1.ViewportWidth;
                            }

                            if (h03 > grid_img.ActualHeight)
                            {
                                w03 = grid_img.ActualWidth;
                            }
                            else
                            {
                                w03 = scrollviewer_1.ViewportHeight;
                            }

                            var zzz2 = l03;
                            l03      = scrollviewer_1.ScrollableHeight - t03;
                            t03      = zzz2;
                        }
                    });


                    w03 += 50;
                    h03 += 50;

                    //避免圖片還沒完全載入
                    Thread.Sleep(30);


                    //複製物件
                    ImageMagick.IMagickImage ii = null;


                    try {
                        /*if (image_局部高清_50 != null && img.ActualWidth < int_img_w / 2) {
                         *  ii = image_局部高清_50.Clone();
                         * } else {*/
                        if (image_局部高清 == null)
                        {
                            continue;
                        }
                        ii = image_局部高清.Clone();
                        //}


                        //計算縮放比例
                        if (img.ActualWidth > img.ActualHeight)
                        {
                            d_縮放倍率 = img.ActualWidth / ii.Width;
                        }
                        else
                        {
                            d_縮放倍率 = img.ActualHeight / ii.Height;
                        }


                        bool_剪裁 = false;
                        if (d_縮放倍率 * int_img_w > 5000 || d_縮放倍率 * int_img_h > 5000)
                        {
                            bool_剪裁 = true;

                            //剪裁
                            ii.Crop(new MagickGeometry(
                                        (int)(l03 / d_縮放倍率),
                                        (int)(t03 / d_縮放倍率),
                                        (int)(w03 / d_縮放倍率),
                                        (int)(h03 / d_縮放倍率))
                                    );
                        }


                        //縮放
                        var mg    = new ImageMagick.MagickGeometry();
                        mg.Height = (int)(ii.Height * d_縮放倍率);
                        mg.Width  = (int)(ii.Width * d_縮放倍率);

                        DateTime time_start = DateTime.Now;//計時開始 取得目前時間


                        if (int_高品質成像模式 == 1 || int_高品質成像模式 == 4)
                        {
                            ii.Resize(mg);//縮放圖片-快
                            if (d_縮放倍率 < 1)
                            {
                                ii.UnsharpMask(0.8, 0.8);//銳化-快速
                            }
                            //System.Console.WriteLine($"111111111");
                        }

                        if (int_高品質成像模式 == 2)
                        {
                            ii.Resize(mg);//縮放圖片-快
                            if (d_縮放倍率 < 1)
                            {
                                ii.RemoveWriteMask();     //沒有獨立顯卡的電腦,必須用這個語法來延遲,避免圖片顯示不出來
                                ii.UnsharpMask(0.8, 0.8); //銳化-快速
                            }
                            //System.Console.WriteLine($"2222222");
                        }

                        if (int_高品質成像模式 == 3 || int_高品質成像模式 == 3)
                        {
                            ii.Scale(mg);//縮放圖片-慢
                            if (d_縮放倍率 < 1)
                            {
                                ii.Sharpen();//銳化-慢
                            }
                            //System.Console.WriteLine($"3333333");
                        }


                        DateTime time_end = DateTime.Now;                                                     //計時結束 取得目前時間
                        string result2    = ((TimeSpan)(time_end - time_start)).TotalMilliseconds.ToString(); //後面的時間減前面的時間後 轉型成TimeSpan即可印出時間差
                        System.Console.WriteLine("+++++++++++++++++++++++++++++++++++" + result2 + " 毫秒");


                        //ii.Sample(ii.Width,ii.Height);//品質差,速度極快
                        //ii.Extent(mg);//意義不明
                        //ii.Thumbnail(mg.Width, mg.Height);//某些情況下會很慢

                        //縮小圖片後進行銳化

                        /*if (d_縮放倍率 < 1) {
                         *  //ii.RemoveWriteMask();
                         *  //ii.UnsharpMask(0.8, 0.8);
                         *  //ii.UnsharpMask(0.25, 0.25,8,0.065);
                         * }*/


                        //System.Console.WriteLine($"mg {mg.Width}   ii {ii.Width}");

                        //避免已經切換到其他圖片
                        if (int_目前圖片位置 < 0 || int_目前圖片位置 >= ar_path.Count)
                        {
                            continue;
                        }
                        if (d_倍率 != img.ActualWidth || s_path != ar_path[int_目前圖片位置])
                        {
                            continue;
                        }
                        if (bool_啟動局部高清 == false)
                        {
                            s_path = "";
                            continue;
                        }


                        C_adapter.fun_UI執行緒(() => {
                            if (bool_剪裁)
                            {
                                img_局部高清.Margin = new Thickness(
                                    ((int)(l03 / d_縮放倍率)) * d_縮放倍率,
                                    ((int)(t03 / d_縮放倍率)) * d_縮放倍率,
                                    -((int)(l03 / d_縮放倍率)) * d_縮放倍率 - 5000,
                                    -((int)(t03 / d_縮放倍率)) * d_縮放倍率 - 5000
                                    );
                                img_局部高清.Width  = mg.Width;
                                img_局部高清.Height = mg.Height;
                                img_局部高清.Source = ii.ToBitmapSource();
                            }
                            else
                            {
                                img.Source = ii.ToBitmapSource();
                            }
                        });
                    } catch (Exception e) {
                        C_adapter.fun_UI執行緒(() => {
                            MessageBox.Show("局部高清 錯誤 \n" + e.ToString());
                        });
                    }


                    Thread.Sleep(1);



                    C_adapter.fun_UI執行緒(() => {
                        //避免已經切換到其他圖片
                        if (int_目前圖片位置 < 0 || int_目前圖片位置 >= ar_path.Count)
                        {
                            return;
                        }
                        if (d_倍率 != img.ActualWidth || s_path != ar_path[int_目前圖片位置])
                        {
                            return;
                        }
                        if (bool_啟動局部高清 == false)
                        {
                            s_path = "";
                            return;
                        }

                        if (bool_剪裁)
                        {
                            img_局部高清.Visibility = Visibility.Visible;
                            if (ii.IsOpaque == false)
                            {
                                img.Visibility = Visibility.Hidden;
                                //System.Console.WriteLine($"透明");
                            }
                            //System.Console.WriteLine($"剪裁");
                        }
                        else
                        {
                            //System.Console.WriteLine($"原圖");
                            img_局部高清.Visibility = Visibility.Collapsed;
                            img.Visibility      = Visibility.Visible;
                        }
                    });


                    ii.Dispose();
                }
            }).Start();
        }
Esempio n. 60
-1
        /// <summary>
        /// Combines the screenshots into one contiguous screenshot
        /// </summary>
        /// <param name="files">The files (images) to combine</param>
        /// <param name="e">For UX, an output progress message</param>
        public static void CombineScreenshot(FileSystemInfo[] files, WaitWindowEventArgs e)
        {
           

            string screenshotLocation = Path.Combine(Constants.CacheLocation, "temp.png");

            using (MagickImageCollection images = new MagickImageCollection())
            {
                // Add the first image
                var orderedFiles = files.OrderBy(f => f.CreationTime);
                foreach (FileSystemInfo file in orderedFiles)
                {
                    MagickImage first = new MagickImage(file.FullName);
                    e.Window.Message = "Obtaining Snapshots... Please Wait";
                    images.Add(first);
                }

                using (MagickImage result = images.AppendVertically())
                {
                    e.Window.Message = "Building Screenshot... Please Wait" + System.Environment.NewLine + "This can take a minute.";
                    try
                    {
                        result.Write(screenshotLocation);
                    } catch (MagickImageErrorException err)
                    {
                        Debug.WriteLine($"Error: {err}");
                    }
                   
                }
        
            }
        }