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. 2
0
 public ClipPath(string name, int width, int height)
 {
     //        ImageInfo info = new ImageInfo();
     //        info.setBackgroundColor(new PixelPacket(255,255,255,0));
     this.name = name;
     this.image = new MagickImage(width, height/*, info*/);
 }
		public void Test_FromIXPathNavigable()
		{
			using (MagickImage image = new MagickImage(Files.InvitationTif))
			{
				XmpProfile profile = image.GetXmpProfile();
				Assert.IsNotNull(profile);

				IXPathNavigable doc = profile.ToIXPathNavigable();

				ExceptionAssert.Throws<ArgumentNullException>(delegate()
				{
					XmpProfile.FromIXPathNavigable(null);
				});

				XmpProfile newProfile = XmpProfile.FromIXPathNavigable(doc);
				image.AddProfile(newProfile);

				doc = profile.ToIXPathNavigable();
				TestIXPathNavigable(doc);

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

				doc = profile.ToIXPathNavigable();
				TestIXPathNavigable(doc);

				Assert.AreEqual(profile, newProfile);
			}
		}
Esempio n. 4
0
 public Pattern(string name, int x, int y, int width, int height)
 {
     this.name = name;
     this.x = x;
     this.y = y;
     this.image = new MagickImage(width, height);
 }
		//===========================================================================================
		private static void Test_ToBitmap(MagickImage image, ImageFormat format)
		{
			using (Bitmap bmp = image.ToBitmap(format))
			{
				Assert.AreEqual(format, bmp.RawFormat);
			}
		}
		//===========================================================================================
		private static void Test_Pixel(MagickImage image, int x, int y, MagickColor color)
		{
			using (PixelCollection collection = image.GetReadOnlyPixels())
			{
				ColorAssert.AreEqual(color, collection.GetPixel(x, y));
			}
		}
		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(ExceptionTypes.Undefined, arguments.EventType);
					Assert.IsNotNull(arguments.Message);
					Assert.AreNotEqual(0, arguments.Message.Length);

					count++;
				};

				GraphicsMagickNET.Log += logDelegate;

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

				GraphicsMagickNET.SetLogEvents(ExceptionTypes.All);

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

				GraphicsMagickNET.Log -= logDelegate;
				count = 0;

				image.Flip();
				Assert.AreEqual(0, count);
			}
		}
Esempio n. 8
0
    private static void CheckTransparency(MagickImage image)
    {
      if (!image.HasAlpha)
        return;

      if (image.IsOpaque)
        image.HasAlpha = false;
    }
		//===========================================================================================
		private static EightBimValue Get8BimValue()
		{
			using (MagickImage image = new MagickImage(Files.FujiFilmFinePixS1ProJPG))
			{
				EightBimProfile profile = image.Get8BimProfile();
				return profile.Values.First();
			}
		}
		public void Test_IEnumerable()
		{
			using (MagickImage image = new MagickImage(Color.Red, 5, 10))
			{
				PixelCollection pixels = image.GetReadOnlyPixels();
				Assert.AreEqual(50, pixels.Count());
			}
		}
		//===========================================================================================
		private static IptcValue GetIptcValue()
		{
			using (MagickImage image = new MagickImage(Files.FujiFilmFinePixS1ProJPG))
			{
				IptcProfile profile = image.GetIptcProfile();
				return profile.Values.ElementAt(1);
			}
		}
		public void Test_Set()
		{
			using (MagickImage image = new MagickImage(Color.Red, 5, 10))
			{
				using (WritablePixelCollection pixels = image.GetWritablePixels())
				{
					ExceptionAssert.Throws<ArgumentNullException>(delegate()
					{
						pixels.Set((QuantumType[])null);
					});

					ExceptionAssert.Throws<ArgumentNullException>(delegate()
					{
						pixels.Set((Pixel)null);
					});

					ExceptionAssert.Throws<ArgumentNullException>(delegate()
					{
						pixels.Set((Pixel[])null);
					});

					Test_Set(pixels, new QuantumType[] { });
					Test_Set(pixels, new QuantumType[] { 0 });
					Test_Set(pixels, new QuantumType[] { 0, 0 });
					Test_Set(pixels, new QuantumType[] { 0, 0, 0 });

					pixels.Set(new QuantumType[] { 0, 0, 0, 0, 0 });
					Test_PixelColor(pixels, Color.Black);
					pixels.Write();
				}

				using (PixelCollection pixels = image.GetReadOnlyPixels())
				{
					Test_PixelColor(pixels, Color.Black);
				}

				using (WritablePixelCollection pixels = image.GetWritablePixels())
				{
					pixels.Set(new uint[] { 4294967295, 0, 0, 0, 0 });
					Test_PixelColor(pixels, Color.Red);
					pixels.Set(new ushort[] { 0, 0, 65535, 0, 0 });
					Test_PixelColor(pixels, Color.Blue);
					pixels.Set(new byte[] { 0, 255, 0, 0, 0 });
					Test_PixelColor(pixels, Color.Lime);
				}

				using (WritablePixelCollection pixels = image.GetWritablePixels())
				{
					for (int x = 0; x < pixels.Width; x++)
					{
						for (int y = 0; y < pixels.Height; y++)
						{
							pixels.Set(x, y, new QuantumType[] { 0, 0, 0, 0, 0 });
						}
					}
				}
			}
		}
Esempio n. 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DrawableComposite"/> class.
 /// </summary>
 /// <param name="x">The X coordinate.</param>
 /// <param name="y">The Y coordinate.</param>
 /// <param name="image">The image to draw.</param>
 public DrawableComposite(double x, double y, MagickImage image)
   : this(image)
 {
   X = x;
   Y = y;
   Width = _Image.Width;
   Height = _Image.Height;
   Compose = CompositeOperator.CopyAlpha;
 }
Esempio n. 14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DrawableComposite"/> class.
 /// </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 DrawableComposite(double x, double y, CompositeOperator compose, MagickImage image)
   : this(image)
 {
   X = x;
   Y = y;
   Width = _Image.Width;
   Height = _Image.Height;
   Compose = compose;
 }
		//===========================================================================================
		private static void Test_Clone(MagickImage first, MagickImage second)
		{
			Assert.AreEqual(first, second);
			second.Format = MagickFormat.Jp2;
			Assert.AreEqual(first.Format, MagickFormat.Png);
			Assert.AreEqual(second.Format, MagickFormat.Jp2);
			second.Dispose();
			Assert.AreEqual(first.Format, MagickFormat.Png);
		}
		//===========================================================================================
		private static ExifValue GetExifValue()
		{
			using (MagickImage image = new MagickImage(Files.FujiFilmFinePixS1ProJPG))
			{
				ExifProfile profile = image.GetExifProfile();
				Assert.IsNotNull(profile);

				return profile.Values.First();
			}
		}
		public void Test_GetValue()
		{
			using (MagickImage image = new MagickImage(Color.Red, 5, 10))
			{
				using (WritablePixelCollection pixels = image.GetWritablePixels())
				{
					Test_PixelColor(pixels, Color.Red);
				}
			}
		}
		public void Test_ICM()
		{
			using (MagickImage image = new MagickImage(Files.SnakewarePNG))
			{
				ColorProfile profile = image.GetColorProfile();
				Assert.IsNull(profile);

				image.AddProfile(new ImageProfile("icm", ColorProfile.SRGB.ToByteArray()));
				TestProfile(image.GetColorProfile(), "icc");
			}
		}
Esempio n. 19
0
    /// <summary>
    /// Initializes a new instance of the <see cref="DrawableComposite"/> class.
    /// </summary>
    /// <param name="offset">The offset from origin.</param>
    /// <param name="image">The image to draw.</param>
    public DrawableComposite(MagickGeometry offset, MagickImage image)
      : this(image)
    {
      Throw.IfNull(nameof(offset), offset);

      X = offset.X;
      Y = offset.Y;
      Width = offset.Width;
      Height = offset.Height;
      Compose = CompositeOperator.CopyAlpha;
    }
		public void Test_Dimensions()
		{
			using (MagickImage image = new MagickImage(Color.Red, 5, 10))
			{
				using (WritablePixelCollection pixels = image.GetWritablePixels())
				{
					Assert.AreEqual(5, pixels.Width);
					Assert.AreEqual(10, pixels.Height);
					Assert.AreEqual(5 * 10 * 5, pixels.GetValues().Length);
				}
			}
		}
		public void Test_Attribute()
		{
			using (MagickImage image = new MagickImage(Files.SnakewarePNG))
			{
				Assert.IsNull(image.GetAttribute("test"));

				image.SetAttribute("test", "");
				Assert.AreEqual(null, image.GetAttribute("test"));

				image.SetAttribute("test", "123");
				Assert.AreEqual("123", image.GetAttribute("test"));
			}
		}
Esempio n. 22
0
        public void MakeCards()
        {
            var deck = JsonConvert.DeserializeObject<Deck>(File.ReadAllText(@"C:\temp\testdeck.cm"));

            var cards = new List<MagickImage>();
            foreach (var card in deck.Cards) {
                var image = new MagickImage(new MagickColor("WhiteSmoke"), deck.Width, deck.Height);
                image.Density = new MagickGeometry(300, 300);
                image.Format = MagickFormat.Bmp;
                foreach (var element in deck.Elements) {
                    var data = card.ElementData[element.Key];
                    if (File.Exists(data)) {
                        using (var overlayImage = new MagickImage(data)) {
                            image.Composite(overlayImage, (int)element.Value.X, (int)element.Value.Y, CompositeOperator.Over);
                        }
                    } else {
                        using (var textImage = new MagickImage(MagickColor.Transparent, deck.Width, deck.Height)) {
                            textImage.Density = new MagickGeometry(300, 300);
                            textImage.Font = "Arial";
                            textImage.FontPointsize = 12;
                            textImage.FillColor = new MagickColor("Black");
                            var drawableText = new DrawableText(element.Value.X, element.Value.Y, data);
                            textImage.Draw(drawableText);
                            image.Composite(textImage, CompositeOperator.Over);
                        }
                    }
                }
                image.Write(string.Format(@"c:\temp\CardMaker\{0}.png", card.Name));
                cards.Add(image);

            }
            using (var doc = new Document()) {
                PdfWriter.GetInstance(doc, new FileStream(@"C:\temp\CardMaker\cards.pdf", FileMode.Create));
                doc.Open();
                var columns = (int)Math.Floor(doc.PageSize.Width / (deck.Width + 10));
                var table = new PdfPTable(columns) { WidthPercentage = 100, DefaultCell = { Border = 0, Padding = 5 } };

                foreach (var card in cards) {
                    var instance = Image.GetInstance(card.ToByteArray());
                    instance.SetDpi(300, 300);
                    var cell = new PdfPCell(instance) {
                        HorizontalAlignment = Element.ALIGN_CENTER,
                        Border = 0,
                        Padding = 5,
                    };
                    table.AddCell(cell);
                }
                table.CompleteRow();
                doc.Add(table);
            }
        }
Esempio n. 23
0
 public override double calculateWidth(MagickImage image)
 {
     if (image.getWidth() < this.getWidth() && image.getHeight() < this.getHeight())
     {
         return new Geometry(this.getWidth(),
                             this.getHeight(),
                             this.getX(),
                             this.getY()).calculateWidth(image);
     }
     else
     {
         return image.getWidth();
     }
 }
		public void Test_GetValue()
		{
			using (MagickImage image = new MagickImage(Color.Red, 5, 10))
			{
				using (PixelCollection pixels = image.GetReadOnlyPixels())
				{
					var values = pixels.GetValue(0, 0);
					Assert.AreEqual(5, values.Length);

					MagickColor color = new MagickColor(values[0], values[1], values[2], values[3]);
					ColorAssert.AreEqual(Color.Red, color);
				}
			}
		}
		//===========================================================================================
		private MagickImageInfo CreateMagickImageInfo(Color color, int width, int height)
		{
			using (MemoryStream memStream = new MemoryStream())
			{
				using (MagickImage image = new MagickImage(color, width, height))
				{
					image.Format = MagickFormat.Png;
					image.Write(memStream);
					memStream.Position = 0;

					return new MagickImageInfo(memStream);
				}
			}
		}
		public void Test_Image_Read()
		{
			using (MagickImage image = new MagickImage())
			{
				MagickReadSettings settings = new MagickReadSettings();
				settings.Density = new MagickGeometry(300, 300);

				image.Read(Files.SnakewarePNG, settings);

				Assert.AreEqual(300, image.Density.Width);

				settings = null;
				image.Read(Files.ImageMagickJPG, settings);
			}
		}
		public void Test_CreateReader()
		{
			using (MagickImage image = new MagickImage(Files.InvitationTif))
			{
				XmpProfile profile = image.GetXmpProfile();
				Assert.IsNotNull(profile);

				using (XmlReader reader = profile.CreateReader())
				{
					XmlDocument doc = new XmlDocument();
					doc.Load(reader);
					TestIXPathNavigable(doc);
				}
			}
		}
		public void Test_SetEncoding()
		{
			using (MagickImage image = new MagickImage(Files.FujiFilmFinePixS1ProJPG))
			{
				IptcProfile profile = image.GetIptcProfile();
				TestProfileValues(profile);

				ExceptionAssert.Throws<ArgumentNullException>(delegate()
				{
					profile.SetEncoding(null);
				});

				profile.SetEncoding(Encoding.UTF8);
				Assert.AreEqual(Encoding.UTF8, profile.Values.First().Encoding);
			}
		}
		public void Test_Values()
		{
			using (MagickImage image = new MagickImage(Files.EightBimTIF))
			{
				EightBimProfile profile = image.Get8BimProfile();
				TestProfileValues(profile);

				using (MagickImage emptyImage = new MagickImage(Files.ImageMagickJPG))
				{
					Assert.IsNull(emptyImage.Get8BimProfile());
					emptyImage.AddProfile(profile);

					profile = emptyImage.Get8BimProfile();
					TestProfileValues(profile);
				}
			}
		}
Esempio n. 30
0
    private void DoLosslessCompress(FileInfo file)
    {
      using (MagickImage image = new MagickImage(file))
      {
        CheckFormat(image);

        image.Strip();
        image.SetDefine(MagickFormat.Png, "exclude-chunks", "all");
        image.SetDefine(MagickFormat.Png, "include-chunks", "tRNS,gAMA");
        CheckTransparency(image);

        Collection<FileInfo> tempFiles = new Collection<FileInfo>();

        try
        {
          FileInfo bestFile = null;

          foreach (int quality in GetQualityList())
          {
            FileInfo tempFile = new FileInfo(Path.GetTempFileName());
            tempFiles.Add(tempFile);

            image.Quality = quality;
            image.Write(tempFile);
            tempFile.Refresh();

            if (bestFile == null || bestFile.Length > tempFile.Length)
              bestFile = tempFile;
            else
              tempFile.Delete();
          }

          if (bestFile.Length < file.Length)
            bestFile.CopyTo(file.FullName, true);
        }
        finally
        {
          foreach (FileInfo tempFile in tempFiles)
          {
            if (tempFile.Exists)
              tempFile.Delete();
          }
        }
      }
    }
Esempio n. 31
0
        /// <summary>
        /// Showing New image with the new properties
        /// </summary>
        /// <param name="fileName">Original image location</param>
        /// <param name="colorSpace">ColourSpace Selected</param>
        /// <param name="Format">Image Type</param>
        /// <param name="pictureBox">Name of picture box used in form</param>
        /// <param name="Quality">Quality of image (int)</param>
        /// <param name="Width">Width of image</param>
        /// <param name="Height">Height of image</param>
        /// <param name="Size">New Size of image</param>
        public void ShowImage(string fileName, string colorSpace, string Format, PictureBox pictureBox, int Quality, int Width, int Height, out long Size)
        {
            ImageFormat imageFormat = null;
            using (MagickImage image = new MagickImage(fileName))
            {
                MagickGeometry size = new MagickGeometry(Width, Height);
                size.IgnoreAspectRatio = true;
                image.Quality = Quality;
                #region Colour and Format
                switch (colorSpace)
                {
                    case "CMY":
                        image.ColorSpace = ColorSpace.CMY;
                        break;
                    case "CMYK":
                        image.ColorSpace = ColorSpace.CMYK;
                        break;
                    case "Gray":
                        image.ColorSpace = ColorSpace.Gray;
                        break;
                    case "HCL":
                        image.ColorSpace = ColorSpace.HCL;
                        break;
                    case "HCLp":
                        image.ColorSpace = ColorSpace.HCLp;
                        break;
                    case "HSB":
                        image.ColorSpace = ColorSpace.HSB;
                        break;
                    case "HSI":
                        image.ColorSpace = ColorSpace.HSI;
                        break;
                    case "HSL":
                        image.ColorSpace = ColorSpace.HSL;
                        break;
                    case "HSV":
                        image.ColorSpace = ColorSpace.HSV;
                        break;
                    case "HWB":
                        image.ColorSpace = ColorSpace.HWB;
                        break;
                    case "Lab":
                        image.ColorSpace = ColorSpace.Lab;
                        break;
                    case "LCH":
                        image.ColorSpace = ColorSpace.LCH;
                        break;
                    case "LCHab":
                        image.ColorSpace = ColorSpace.LCHab;
                        break;
                    case "LCHuv":
                        image.ColorSpace = ColorSpace.LCHuv;
                        break;
                    case "Log":
                        image.ColorSpace = ColorSpace.Log;
                        break;
                    case "LMS":
                        image.ColorSpace = ColorSpace.LMS;
                        break;
                    case "Luv":
                        image.ColorSpace = ColorSpace.Luv;
                        break;
                    case "OHTA":
                        image.ColorSpace = ColorSpace.OHTA;
                        break;
                    case "Rec601YCbCr":
                        image.ColorSpace = ColorSpace.Rec601YCbCr;
                        break;
                    case "Rec709YCbCr":
                        image.ColorSpace = ColorSpace.Rec709YCbCr;
                        break;
                    case "RGB":
                        image.ColorSpace = ColorSpace.RGB;
                        break;
                    case "scRGB":
                        image.ColorSpace = ColorSpace.scRGB;
                        break;
                    case "sRGB":
                        image.ColorSpace = ColorSpace.sRGB;
                        break;
                    case "Transparent":
                        image.ColorSpace = ColorSpace.Transparent;
                        break;
                    case "XyY":
                        image.ColorSpace = ColorSpace.XyY;
                        break;
                    case "XYZ":
                        image.ColorSpace = ColorSpace.XYZ;
                        break;
                    case "YCbCr":
                        image.ColorSpace = ColorSpace.YCbCr;
                        break;
                    case "YCC":
                        image.ColorSpace = ColorSpace.YCC;
                        break;
                    case "YDbDr":
                        image.ColorSpace = ColorSpace.YDbDr;
                        break;
                    case "YIQ":
                        image.ColorSpace = ColorSpace.YIQ;
                        break;
                    case "YPbPr":
                        image.ColorSpace = ColorSpace.YPbPr;
                        break;
                    case "YUV":
                        image.ColorSpace = ColorSpace.YUV;
                        break;
                    case "LinearGRAY":
                        image.ColorSpace = ColorSpace.LinearGRAY;
                        break;
                    default:
                        image.ColorSpace = ColorSpace.Undefined;
                        break;
                }
                switch (Format)
                {
                    case "PNG":
                        image.Format = MagickFormat.Png;
                        imageFormat = ImageFormat.Png;

                        break;
                    case "GIF":
                        image.Format = MagickFormat.Gif;
                        imageFormat = ImageFormat.Gif;

                        break;
                    case "JPEG":
                        image.Format = MagickFormat.Jpeg;
                        imageFormat = ImageFormat.Jpeg;
                        ;
                        break;
                    case "BMP":
                        image.Format = MagickFormat.Bmp;
                        imageFormat = ImageFormat.Bmp;

                        break;
                    case "TIFF":
                        image.Format = MagickFormat.Tiff;
                        imageFormat = ImageFormat.Tiff;

                        break;
                    default:

                        break;
                }
                #endregion

                image.Resize(size);

                // In order for the compression to show I have to do it though the memory steam.
                MemoryStream memStream = new MemoryStream();
                image.Write(memStream);

                Bitmap bitmap = new Bitmap(memStream);

                pictureBox.Image = bitmap;

                Size = memStream.Length;

                image.Dispose();
            }
        }
Esempio n. 32
0
        /// <summary>
        /// Generate the profile card for a given user and returns the generated image path
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task <string> GenerateProfileCard(IUser user)
        {
            ulong  userId    = user.Id;
            uint   xpTotal   = _databaseService.GetUserXp(userId);
            uint   xpRank    = _databaseService.GetUserRank(userId);
            int    karma     = _databaseService.GetUserKarma(userId);
            uint   level     = _databaseService.GetUserLevel(userId);
            uint   karmaRank = _databaseService.GetUserKarmaRank(userId);
            double xpLow     = GetXpLow((int)level);
            double xpHigh    = GetXpHigh((int)level);

            uint xpShown    = (uint)(xpTotal - xpLow);
            uint maxXpShown = (uint)(xpHigh - xpLow);

            float percentage = (float)xpShown / maxXpShown;

            var   u        = user as IGuildUser;
            IRole mainRole = null;

            foreach (ulong id in u.RoleIds)
            {
                IRole role = u.Guild.GetRole(id);
                if (mainRole == null)
                {
                    mainRole = u.Guild.GetRole(id);
                }
                else if (role.Position > mainRole.Position)
                {
                    mainRole = role;
                }
            }

            using (MagickImageCollection profileCard = new MagickImageCollection())
            {
                SkinData    skin    = GetSkinData();
                ProfileData profile = new ProfileData
                {
                    Karma         = karma,
                    KarmaRank     = karmaRank,
                    Level         = level,
                    MainRoleColor = mainRole.Color,
                    MaxXpShown    = maxXpShown,
                    Nickname      = (user as IGuildUser).Nickname,
                    UserId        = userId,
                    Username      = user.Username,
                    XpHigh        = xpHigh,
                    XpLow         = xpLow,
                    XpPercentage  = percentage,
                    XpRank        = xpRank,
                    XpShown       = xpShown,
                    XpTotal       = xpTotal
                };

                MagickImage background = new MagickImage($"{_settings.ServerRootPath}/skins/{skin.Background}");

                string avatarUrl = user.GetAvatarUrl(ImageFormat.Auto, 256);
                if (string.IsNullOrEmpty(avatarUrl))
                {
                    profile.Picture = new MagickImage($"{_settings.ServerRootPath}/images/default.png");
                }
                else
                {
                    try
                    {
                        Stream stream;

                        using (var http = new HttpClient())
                        {
                            stream = await http.GetStreamAsync(new Uri(avatarUrl));
                        }

                        profile.Picture = new MagickImage(stream);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        profile.Picture = new MagickImage($"{_settings.ServerRootPath}/images/default.png");
                    }
                }

                profile.Picture.Resize((int)skin.AvatarSize, skin.AvatarSize);
                profileCard.Add(background);

                foreach (var layer in skin.Layers)
                {
                    if (layer.Image != null)
                    {
                        MagickImage image = layer.Image.ToLower() == "avatar"
                            ? profile.Picture
                            : new MagickImage($"{_settings.ServerRootPath}/skins/{layer.Image}");

                        background.Composite(image, (int)layer.StartX, (int)layer.StartY, CompositeOperator.Over);
                    }

                    MagickImage l = new MagickImage(MagickColors.Transparent, (int)layer.Width, (int)layer.Height);
                    foreach (var module in layer.Modules)
                    {
                        module.GetDrawables(profile).Draw(l);
                    }

                    background.Composite(l, (int)layer.StartX, (int)layer.StartY, CompositeOperator.Over);
                }

                using (IMagickImage result = profileCard.Mosaic())
                {
                    result.Write($"{_settings.ServerRootPath}/images/profiles/{user.Username}-profile.png");
                }
            }

            return($"{_settings.ServerRootPath}/images/profiles/{user.Username}-profile.png");
        }
Esempio n. 33
0
        /// <summary>
        /// Save a Copy of the new image
        /// </summary>
        /// <param name="pictureBox">Name of picture box used in form</param>
        /// <param name="colorSpace">ColourSpace Selected</param>
        /// <param name="fileName">Original image location</param>
        /// <param name="Format">Image Type</param>
        /// <param name="Quality">Quality of image (int)</param>
        /// <param name="Width">Width of image</param>
        /// <param name="Height">Height of image</param>
        /// <seealso cref="ImageActions.SavePdfImage(PictureBox, string)">
        /// This will Save the PDF as an image
        /// </seealso>
        public void SaveImage(PictureBox pictureBox, string colorSpace, string fileName, string Format, int Quality, int Width, int Height)
        {
            ImageFormat imageFormat = null;
            var save = new SaveFileDialog();
            using (MemoryStream memStream = new MemoryStream())
            {

                using (MagickImage image = new MagickImage(fileName))
                {
                    MagickGeometry size = new MagickGeometry(Width, Height);
                    size.IgnoreAspectRatio = true;
                    image.Quality = Quality;

                    #region Colour and Format
                    switch (colorSpace)
                    {
                        case "CMY":
                            image.ColorSpace = ColorSpace.CMY;
                            break;
                        case "CMYK":
                            image.ColorSpace = ColorSpace.CMYK;
                            break;
                        case "Gray":
                            image.ColorSpace = ColorSpace.Gray;
                            break;
                        case "HCL":
                            image.ColorSpace = ColorSpace.HCL;
                            break;
                        case "HCLp":
                            image.ColorSpace = ColorSpace.HCLp;
                            break;
                        case "HSB":
                            image.ColorSpace = ColorSpace.HSB;
                            break;
                        case "HSI":
                            image.ColorSpace = ColorSpace.HSI;
                            break;
                        case "HSL":
                            image.ColorSpace = ColorSpace.HSL;
                            break;
                        case "HSV":
                            image.ColorSpace = ColorSpace.HSV;
                            break;
                        case "HWB":
                            image.ColorSpace = ColorSpace.HWB;
                            break;
                        case "Lab":
                            image.ColorSpace = ColorSpace.Lab;
                            break;
                        case "LCH":
                            image.ColorSpace = ColorSpace.LCH;
                            break;
                        case "LCHab":
                            image.ColorSpace = ColorSpace.LCHab;
                            break;
                        case "LCHuv":
                            image.ColorSpace = ColorSpace.LCHuv;
                            break;
                        case "Log":
                            image.ColorSpace = ColorSpace.Log;
                            break;
                        case "LMS":
                            image.ColorSpace = ColorSpace.LMS;
                            break;
                        case "Luv":
                            image.ColorSpace = ColorSpace.Luv;
                            break;
                        case "OHTA":
                            image.ColorSpace = ColorSpace.OHTA;
                            break;
                        case "Rec601YCbCr":
                            image.ColorSpace = ColorSpace.Rec601YCbCr;
                            break;
                        case "Rec709YCbCr":
                            image.ColorSpace = ColorSpace.Rec709YCbCr;
                            break;
                        case "RGB":
                            image.ColorSpace = ColorSpace.RGB;
                            break;
                        case "scRGB":
                            image.ColorSpace = ColorSpace.scRGB;
                            break;
                        case "sRGB":
                            image.ColorSpace = ColorSpace.sRGB;
                            break;
                        case "Transparent":
                            image.ColorSpace = ColorSpace.Transparent;
                            break;
                        case "XyY":
                            image.ColorSpace = ColorSpace.XyY;
                            break;
                        case "XYZ":
                            image.ColorSpace = ColorSpace.XYZ;
                            break;
                        case "YCbCr":
                            image.ColorSpace = ColorSpace.YCbCr;
                            break;
                        case "YCC":
                            image.ColorSpace = ColorSpace.YCC;
                            break;
                        case "YDbDr":
                            image.ColorSpace = ColorSpace.YDbDr;
                            break;
                        case "YIQ":
                            image.ColorSpace = ColorSpace.YIQ;
                            break;
                        case "YPbPr":
                            image.ColorSpace = ColorSpace.YPbPr;
                            break;
                        case "YUV":
                            image.ColorSpace = ColorSpace.YUV;
                            break;
                        case "LinearGRAY":
                            image.ColorSpace = ColorSpace.LinearGRAY;
                            break;
                        default:
                            image.ColorSpace = ColorSpace.Undefined;
                            break;
                    }

                    switch (Format)
                    {
                        case "PNG":
                            image.Format = MagickFormat.Png;
                            imageFormat = ImageFormat.Png;
                            save.Filter = "Images|*.png;";
                            break;
                        case "GIF":
                            image.Format = MagickFormat.Gif;
                            imageFormat = ImageFormat.Gif;
                            save.Filter = "Images|*.gif;";
                            break;
                        case "JPEG":
                            image.Format = MagickFormat.Jpeg;
                            imageFormat = ImageFormat.Jpeg;
                            save.Filter = "Images|*.jpeg;";
                            break;
                        case "BMP":
                            image.Format = MagickFormat.Bmp;
                            imageFormat = ImageFormat.Bmp;
                            save.Filter = "Images|*.Bmp;";
                            break;
                        case "TIFF":
                            image.Format = MagickFormat.Tiff;
                            imageFormat = ImageFormat.Tiff;
                            save.Filter = "Images|*.Tiff;";
                            break;
                        default:

                            break;
                    }
                    #endregion
                    image.Resize(size);
                    image.Write(memStream);


                    Bitmap bitmap = new Bitmap(memStream);
                    if (save.ShowDialog() == DialogResult.OK)
                    {
                        pictureBox.Image = bitmap;

                        image.Write(save.FileName);

                        MessageBox.Show("Your image has been saved");
                    }
                    else
                    {
                        MessageBox.Show("There was an error");
                    }
                    image.Dispose();
                }
            }
        }
Esempio n. 34
0
        public MagickImage Build()
        {
            int         fold = fmt.ToPixels(12);
            MagickImage ret  = new(MagickColors.White,
                                   frontFormat.Width * 2 + spessore * 2 + fold + 2,
                                   frontFormat.Height + spessore * 2 + fold * 2 + 2);


            // Aggiunge le alette ai bordi della scatola
            MagickImage LeftBorderWithExtra = new(MagickColors.White,
                                                  borderFormat.Width, borderFormat.Height + fold * 2);
            Drawables draw = new();

            draw.StrokeColor(borderColor).StrokeWidth(1);
            draw = cap(draw, spessore, fold);
            draw.Draw(LeftBorderWithExtra);
            LeftBorderWithExtra.Rotate(180);
            draw.Draw(LeftBorderWithExtra);

            MagickImage RightBorderWithExtra = (MagickImage)LeftBorderWithExtra.Clone();

            LeftBorderWithExtra.Composite(leftImage, Gravity.Center);
            RightBorderWithExtra.Composite(rightImage, Gravity.Center);


            // Aggiungiamo coperchi e lembi di chiusura
            MagickImage BackWithTop = new(MagickColors.White,
                                          frontFormat.Width, frontFormat.Height + spessore + fold);

            draw = new();
            draw.StrokeColor(borderColor).StrokeWidth(1);
            cap(draw, frontFormat.Width, fold).Draw(BackWithTop);

            MagickImage FrontWithBottom = (MagickImage)BackWithTop.Clone();

            FrontWithBottom.Rotate(180);

            FrontWithBottom.Composite(frontImage, Gravity.North);
            FrontWithBottom.Composite(bottomImage, Gravity.South, new PointD(0, fold));
            BackWithTop.Composite(backImage, Gravity.South);
            topImage.Rotate(180);
            BackWithTop.Composite(topImage, Gravity.North, new PointD(0, fold));
            MagickImage frontTopImage = (MagickImage)frontImage.Clone();

            frontTopImage.Crop(frontFormat.Width - 2, fold, Gravity.North);
            frontTopImage.Rotate(180);
            BackWithTop.Composite(frontTopImage, Gravity.North, new PointD(0, 1));

            // Assembliamo le immagini
            ret.Composite(BackWithTop, Gravity.Northwest, new PointD(1, 0));
            ret.Composite(LeftBorderWithExtra, Gravity.West, new PointD(1 + frontFormat.Width, 0));
            ret.Composite(FrontWithBottom, Gravity.Southwest, new PointD(1 + frontFormat.Width + borderFormat.Width, 0));
            ret.Composite(RightBorderWithExtra, Gravity.West, new PointD(1 + frontFormat.Width * 2 + borderFormat.Width, 0));

            // Margini di taglio
            draw = new();
            draw.StrokeColor(borderColor).StrokeWidth(1);
            int bordertop    = spessore + fold;
            int borderbottom = bordertop + +frontFormat.Height;
            int marginright  = ret.Width - 1;

            draw.Line(0, bordertop - spessore, 0, borderbottom);
            draw.Line(marginright, bordertop, marginright, borderbottom);
            draw.Line(marginright - fold, bordertop, marginright, bordertop);
            draw.Line(marginright - fold, borderbottom, marginright, borderbottom);
            draw.Line(0, borderbottom, frontFormat.Width, borderbottom);
            draw.Line(marginright - fold - spessore, bordertop,
                      marginright - fold - spessore - frontFormat.Width, bordertop);
            draw.Draw(ret);

            return(ret);
        }
Esempio n. 35
0
        public void Test_Drawables_Exceptions()
        {
            ExceptionAssert.ThrowsArgumentException("coordinates", () =>
            {
                new DrawableBezier();
            });

            ExceptionAssert.ThrowsArgumentNullException("coordinates", () =>
            {
                new DrawableBezier(null);
            });

            ExceptionAssert.ThrowsArgumentException("coordinates", () =>
            {
                new DrawableBezier(new PointD[] { });
            });

            ExceptionAssert.ThrowsArgumentNullException("clipPath", () =>
            {
                new DrawableClipPath(null);
            });

            ExceptionAssert.ThrowsArgumentException("clipPath", () =>
            {
                new DrawableClipPath(string.Empty);
            });

            ExceptionAssert.ThrowsArgumentNullException("offset", () =>
            {
                new DrawableComposite(null, new MagickImage(Files.Builtin.Logo));
            });

            ExceptionAssert.ThrowsArgumentNullException("image", () =>
            {
                new DrawableComposite(new MagickGeometry(), null);
            });

            ExceptionAssert.ThrowsArgumentNullException("color", () =>
            {
                new DrawableFillColor(null);
            });

            ExceptionAssert.ThrowsArgumentNullException("family", () =>
            {
                new DrawableFont(null);
            });

            ExceptionAssert.ThrowsArgumentException("family", () =>
            {
                new DrawableFont(string.Empty);
            });

            ExceptionAssert.Throws <MagickDrawErrorException>(() =>
            {
                using (IMagickImage image = new MagickImage(Files.Builtin.Wizard))
                {
                    image.Draw(new DrawableFillPatternUrl("#fail"));
                }
            });

            ExceptionAssert.ThrowsArgumentException("coordinates", () =>
            {
                new DrawablePolygon(new PointD[] { new PointD(0, 0) });
            });

            ExceptionAssert.ThrowsArgumentException("coordinates", () =>
            {
                new DrawablePolyline(new PointD[] { new PointD(0, 0), new PointD(0, 0) });
            });

            ExceptionAssert.ThrowsArgumentNullException("color", () =>
            {
                new DrawableStrokeColor(null);
            });

            ExceptionAssert.ThrowsArgumentNullException("value", () =>
            {
                new DrawableText(0, 0, null);
            });

            ExceptionAssert.ThrowsArgumentException("value", () =>
            {
                new DrawableText(0, 0, string.Empty);
            });

            ExceptionAssert.ThrowsArgumentNullException("encoding", () =>
            {
                new DrawableTextEncoding(null);
            });
        }
Esempio n. 36
0
        public static MagickImage DecodeImage(ValveTextureFile vtf, int mip, int frame, int face, int zslice)
        {
            var dataLength  = vtf.GetHiResPixelDataLength(mip);
            var totalLength = dataLength + 128;

            if (_sPixelBuffer == null || _sPixelBuffer.Length < totalLength)
            {
                var powerOf2 = 256;
                while (powerOf2 < totalLength)
                {
                    powerOf2 <<= 1;
                }

                _sPixelBuffer = new byte[powerOf2];
            }

            var offset = 0;
            var width  = Math.Max(1, vtf.Header.Width >> mip);
            var height = Math.Max(1, vtf.Header.Height >> mip);

            var readSettings = new MagickReadSettings
            {
                Width  = width,
                Height = height
            };

            switch (vtf.Header.HiResFormat)
            {
            case TextureFormat.DXT1:
            case TextureFormat.DXT3:
            case TextureFormat.DXT5:
                readSettings.Format = MagickFormat.Dds;
                offset = WriteDdsHeader(vtf, mip, _sPixelBuffer);
                break;

            case TextureFormat.I8:
                readSettings.Format = MagickFormat.Gray;
                break;

            case TextureFormat.IA88:
                readSettings.Format       = MagickFormat.Gray;
                readSettings.PixelStorage = new PixelStorageSettings
                {
                    StorageType = StorageType.Char,
                    Mapping     = "PA"
                };
                break;

            case TextureFormat.BGR888:
                readSettings.PixelStorage = new PixelStorageSettings(StorageType.Char, "BGR");
                break;

            case TextureFormat.RGB888:
            case TextureFormat.RGB888_BLUESCREEN:
                readSettings.PixelStorage = new PixelStorageSettings(StorageType.Char, "RGB");
                break;

            case TextureFormat.ABGR8888:
                readSettings.PixelStorage = new PixelStorageSettings(StorageType.Char, "ABGR");
                break;

            case TextureFormat.BGRA8888:
                readSettings.PixelStorage = new PixelStorageSettings(StorageType.Char, "BGRA");
                break;

            case TextureFormat.RGBA8888:
                readSettings.PixelStorage = new PixelStorageSettings(StorageType.Char, "RGBA");
                break;

            default:
                throw new NotImplementedException();
            }

            vtf.GetHiResPixelData(mip, frame, face, zslice, _sPixelBuffer, offset);

            var img = new MagickImage(_sPixelBuffer, readSettings);

            if (img.Width != width || img.Height != height)
            {
                img.Resize(new MagickGeometry(width, height)
                {
                    IgnoreAspectRatio = true
                });
            }

            return(img);
        }
Esempio n. 37
0
        public void LoadHistogram(FileItem item)
        {
            try
            {
                var fileInfo = item.FileInfo;
                if (fileInfo != null)
                {
                    if (fileInfo.IsLoading)
                    {
                        return;
                    }
                    fileInfo.IsLoading = true;
                }
                if (fileInfo == null || fileInfo.ExifTags == null || fileInfo.ExifTags.Items.Count == 0)
                {
                    GetMetadata(item);
                    fileInfo           = item.FileInfo;
                    fileInfo.IsLoading = true;
                }
                if (!File.Exists(item.SmallThumb))
                {
                    fileInfo.IsLoading = false;
                    return;
                }

                using (MagickImage image = new MagickImage(item.SmallThumb))
                {
                    var Blue      = new int[256];
                    var Green     = new int[256];
                    var Red       = new int[256];
                    var Luminance = new int[256];
                    Dictionary <MagickColor, int> h = image.Histogram();
                    foreach (var i in h)
                    {
                        byte R = i.Key.R;
                        byte G = i.Key.G;
                        byte B = i.Key.B;
                        Blue[B]  += i.Value;
                        Green[G] += i.Value;
                        Red[R]   += i.Value;
                        int lum = (R + R + R + B + G + G + G + G) >> 3;
                        Luminance[lum] += i.Value;
                    }
                    fileInfo.HistogramBlue      = Blue;
                    fileInfo.HistogramGreen     = Green;
                    fileInfo.HistogramRed       = Red;
                    fileInfo.HistogramLuminance = Luminance;
                    fileInfo.IsLoading          = false;
                    item.FileInfo = fileInfo;
                }
                item.SaveInfo();
                if (ServiceProvider.Settings.SelectedBitmap.FileItem == item)
                {
                    SetData(ServiceProvider.Settings.SelectedBitmap,
                            ServiceProvider.Settings.SelectedBitmap.FileItem);
                }
            }
            catch (Exception ex)
            {
                Log.Error("Unable to load histogram", ex);
            }

            //item.FileInfo.HistogramBlue = SmoothHistogram(item.FileInfo.HistogramBlue);
            //item.FileInfo.HistogramGreen = SmoothHistogram(item.FileInfo.HistogramGreen);
            //item.FileInfo.HistogramRed = SmoothHistogram(item.FileInfo.HistogramRed);
            //item.FileInfo.HistogramLuminance = SmoothHistogram(item.FileInfo.HistogramLuminance);
        }
Esempio n. 38
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="source"></param>
        /// <param name="target"></param>
        /// <param name="compose"></param>
        /// <returns></returns>
        private async Task <MagickImage> Compare(MagickImage source, MagickImage target, bool compose = false)
        {
            MagickImage result = null;
            await Dispatcher.InvokeAsync(async() =>
            {
                var st  = Stopwatch.StartNew();
                var tip = new List <string>();
                try
                {
                    if (source is MagickImage && target is MagickImage)
                    {
                        var fuzzy = Math.Min(Math.Max(ImageCompareFuzzy.Minimum, ImageCompareFuzzy.Value), ImageCompareFuzzy.Maximum);
                        if (source.ColorFuzz.ToDouble() != fuzzy)
                        {
                            source.ColorFuzz = new Percentage(fuzzy);
                        }
                        if (target.ColorFuzz.ToDouble() != fuzzy)
                        {
                            target.ColorFuzz = new Percentage(fuzzy);
                        }

                        if (compose)
                        {
                            using (MagickImage diff = new MagickImage(target.Clone()))
                            {
                                diff.Composite(source, CompositeMode, CompareImageChannels);
                                tip.Add($"{"ResultTipMode".T()} {CompositeMode.ToString()}");
                                result = new MagickImage(diff);
                                await Task.Delay(1);
                                DoEvents();
                            }
                        }
                        else
                        {
                            using (MagickImage diff = new MagickImage())
                            {
                                var setting = new CompareSettings()
                                {
                                    Metric         = ErrorMetricMode,
                                    HighlightColor = HighlightColor,
                                    LowlightColor  = LowlightColor,
                                    MasklightColor = MasklightColor
                                };
                                var distance = source.Compare(target, setting, diff, CompareImageChannels);
                                tip.Add($"{"ResultTipMode".T()} {ErrorMetricMode.ToString()}");
                                tip.Add($"{"ResultTipDifference".T()} {distance:F4}");
                                result = new MagickImage(diff);
                                //result.Comment = "NetCharm Created";
                                await Task.Delay(1);
                                DoEvents();
                            }
                        }
                    }
                }
                catch (Exception ex) { ex.ShowMessage(); }
                finally
                {
                    st.Stop();
                    tip.Add($"{"ResultTipElapsed".T()} {TimeSpan.FromTicks(st.ElapsedTicks).TotalSeconds:F4} s");
                    if (compose)
                    {
                        ImageCompose.ToolTip = tip.Count > 1 ? string.Join(Environment.NewLine, tip) : DefaultComposeToolTip;
                        ImageCompare.ToolTip = DefaultCompareToolTip;
                    }
                    else
                    {
                        ImageCompare.ToolTip = tip.Count > 1 ? string.Join(Environment.NewLine, tip) : DefaultCompareToolTip;
                        ImageCompose.ToolTip = DefaultComposeToolTip;
                    }
                }
            }, DispatcherPriority.Render);

            return(result);
        }
Esempio n. 39
0
 private void SaveImage(MagickImage image, string filePath)
 {
     image.Write(filePath);
 }
Esempio n. 40
0
        public override void Write(string filename)
        {
            FileInfo fileInfo = new FileInfo(filename);

            if (mtlExport.Count > 0)
            {
                string mtlFileName = Path.GetFileNameWithoutExtension(filename) + ".mtl";
                Export.Insert(3, "# Textures " + Environment.NewLine + "mtllib " + mtlFileName);

                using (StreamWriter writer = new StreamWriter(fileInfo.Directory + "\\" + mtlFileName))
                {
                    writer.WriteLine(string.Join(Environment.NewLine, mtlExport));
                }

                using (StreamWriter writer = new StreamWriter(fileInfo.Directory + "\\" + mtlFileName))
                {
                    writer.WriteLine(string.Join(Environment.NewLine, mtlExport));
                }
            }

            using (StreamWriter writer = new StreamWriter(filename))
            {
                writer.WriteLine(string.Join(Environment.NewLine, Export));
            }

            // Load textues
            if (textures.Count > 0)
            {
                List <string> textureLocations = new List <string>()
                {
                    "D:\\DAoC Extracted\\figures\\Mskins",
                    "D:\\DAoC Extracted\\figures\\skins",
                    "D:\\DAoC Extracted\\items\\pskins",
                    "D:\\Games\\Dark Age of Camelot\\zones\\Nifs",
                    "D:\\Games\\Dark Age of Camelot\\zones\\Dnifs",
                    "D:\\Games\\Dark Age of Camelot\\zones\\sky",
                    "D:\\Games\\Dark Age of Camelot\\zones\\TerrainTex",
                    "D:\\Games\\Dark Age of Camelot\\zones\\textures",
                    "D:\\Games\\Dark Age of Camelot\\zones\\trees",
                    "D:\\Games\\Dark Age of Camelot\\frontiers\\dnifs",
                    "D:\\Games\\Dark Age of Camelot\\frontiers\\items",
                    "D:\\Games\\Dark Age of Camelot\\frontiers\\NIFS",
                    "D:\\Games\\Dark Age of Camelot\\frontiers\\zones\\TerrainTex",
                    "D:\\Games\\Dark Age of Camelot\\frontiers\\zones\\textures",
                    "D:\\Games\\Dark Age of Camelot\\phousing\\nifs",
                    "D:\\Games\\Dark Age of Camelot\\phousing\\textures",
                    "D:\\Games\\Dark Age of Camelot\\pregame",
                    "D:\\Games\\Dark Age of Camelot\\Tutorial\\zones\\nifs",
                    "D:\\Games\\Dark Age of Camelot\\Tutorial\\zones\\terraintex",
                    "D:\\Games\\Dark Age of Camelot\\insignia",
                    "D:\\Games\\Dark Age of Camelot\\items",
                    "D:\\Games\\Dark Age of Camelot\\zones\\zone026\\nifs",
                    "D:\\Games\\Dark Age of Camelot\\zones\\zone050\\nifs",
                    "D:\\Games\\Dark Age of Camelot\\zones\\zone120\\nifs",
                    "D:\\Games\\Dark Age of Camelot\\zones\\zone209\\nifs",
                };


                foreach (string texture in textures)
                {
                    foreach (string loc in textureLocations)
                    {
                        DirectoryInfo dir   = new DirectoryInfo(loc);
                        var           files = dir.GetFiles(Path.GetFileNameWithoutExtension(texture) + ".*");

                        if (files.Length > 0)
                        {
                            string sourceFileName    = files.First().FullName;
                            string targetFileName    = fileInfo.Directory + "\\" + Path.GetFileNameWithoutExtension(sourceFileName) + ".tga";
                            string targetFileNamePng = fileInfo.Directory + "\\" + Path.GetFileNameWithoutExtension(sourceFileName) + ".png";

                            using (MagickImage image = new MagickImage(files.First().FullName))
                            {
                                image.Write(targetFileName.ToLower());
                                image.Write(targetFileNamePng.ToLower());
                            }
                            break;
                        }
                    }
                }
            }
        }
Esempio n. 41
0
        private Bitmap processImgForScanning(Bitmap imgInput)
        {
            using (MemoryStream memstream = new MemoryStream())
            {
                imgInput.Save(memstream, ImageFormat.Tiff);
                MagickImage img = new MagickImage(memstream.ToArray());


                if (sharpen)
                {
                    img.Sharpen((int)sharpenIntX.Value, (int)sharpenIntY.Value, Channels.All);
                }

                if (autoGamma)
                {
                    img.AutoGamma();
                }

                if (enhance)
                {
                    img.Enhance();
                }

                if (contrast)
                {
                    img.Contrast();
                }

                if (autoLevel)
                {
                    img.AutoLevel();
                }

                if (autoOrient)
                {
                    img.AutoOrient();
                }

                if (despeckle)
                {
                    img.Despeckle();
                }


                if (medianFilter)
                {
                    img.MedianFilter((int)medianInt.Value);
                }

                if (unsharpmask)
                {
                    img.Unsharpmask(6.8, 4, 4, 0);
                }

                if (wtThreshold)
                {
                    img.LinearStretch((float)0.9, 0.1);
                    //img.WhiteThreshold((int)wtThresInt.Value);
                    //img.ReduceNoise();
                    //img.Grayscale(PixelIntensityMethod.Brightness);
                }

                if (invert)
                {
                    img.Negate();
                }

                return(img.ToBitmap());
            }
        }
Esempio n. 42
0
 public override void Apply(MagickImage image)
 {
     image.Modulate(new Percentage(100), new Percentage(Saturation * 100), new Percentage(100));
 }
Esempio n. 43
0
        public void Test_Set()
        {
            using (IMagickImage image = new MagickImage(MagickColors.Red, 5, 10))
            {
                using (PixelCollection pixels = image.GetPixels())
                {
                    ExceptionAssert.Throws <ArgumentNullException>(delegate()
                    {
                        pixels.Set((QuantumType[])null);
                    });

                    ExceptionAssert.Throws <ArgumentNullException>(delegate()
                    {
                        pixels.Set((Pixel)null);
                    });

                    ExceptionAssert.Throws <ArgumentNullException>(delegate()
                    {
                        pixels.Set((Pixel[])null);
                    });

                    Assert.AreEqual(3, pixels.Channels);
                    Test_Set(pixels, new QuantumType[] { });
                    Test_Set(pixels, new QuantumType[] { 0 });
                    Test_Set(pixels, new QuantumType[] { 0, 0 });

                    pixels.Set(new QuantumType[] { 0, 0, 0 });
                    Test_PixelColor(pixels, MagickColors.Black);
                }

                using (PixelCollection pixels = image.GetPixels())
                {
                    Test_PixelColor(pixels, MagickColors.Black);
                }

                using (PixelCollection pixels = image.GetPixels())
                {
                    pixels.Set(new int[] { 100000, 0, 0 });
                    Test_PixelColor(pixels, MagickColors.Red);
                    pixels.Set(new byte[] { 0, 255, 0 });
                    Test_PixelColor(pixels, MagickColors.Lime);
                }

                using (PixelCollection pixels = image.GetPixels())
                {
                    pixels.SetArea(3, 3, 1, 1, new int[] { 100000, 0, 0 });
                    Test_PixelColor(pixels, 3, 3, MagickColors.Red);
                    pixels.SetArea(3, 3, 1, 1, new byte[] { 0, 255, 0 });
                    Test_PixelColor(pixels, 3, 3, MagickColors.Lime);
                }

                using (PixelCollection pixels = image.GetPixels())
                {
                    for (int x = 0; x < image.Width; x++)
                    {
                        for (int y = 0; y < image.Height; y++)
                        {
                            pixels.Set(x, y, new QuantumType[] { 0, 0, 0 });
                        }
                    }
                }
            }
        }
Esempio n. 44
0
        public static void ApplyXmpRecipe(XmpRecipeContainer xmpRecipeContainer, MagickImage image)
        {
            foreach (IXmpRecipeAction action in xmpRecipeContainer.Actions)
            {
                if (action.GetType() == typeof(XmpRotate))
                {
                    XmpRotate xmpRotate = (XmpRotate)action;
                    image.VirtualPixelMethod = VirtualPixelMethod.Black;
                    image.Rotate(xmpRotate.Angle);
                }
                else if (action.GetType() == typeof(XmpResize))
                {
                    XmpResize xmpResize = (XmpResize)action;

                    if (image.Width > xmpResize.Width && image.Height > xmpResize.Height)
                    {
                        image.Resize(xmpResize.Width, xmpResize.Height);
                    }
                }
                else if (action.GetType() == typeof(XmpCrop))
                {
                    XmpCrop xmpCrop = (XmpCrop)action;

                    int intLeftPixel   = Convert.ToInt32(image.Width * xmpCrop.Left);
                    int intTopPixel    = Convert.ToInt32(image.Height * xmpCrop.Top);
                    int intRightPixel  = Convert.ToInt32(image.Width * xmpCrop.Right);
                    int intBottomPixel = Convert.ToInt32(image.Height * xmpCrop.Bottom);
                    int intWidth       = intRightPixel - intLeftPixel;
                    int intHeight      = intBottomPixel - intTopPixel;

                    MagickGeometry magickGeometry = new MagickGeometry(intLeftPixel, intTopPixel, intWidth, intHeight);
                    image.Crop(magickGeometry);
                }
                else if (action.GetType() == typeof(XmpFlip))
                {
                    XmpFlip xmpFlip = (XmpFlip)action;

                    if (xmpFlip.FlipVertical)
                    {
                        image.Flop();
                    }

                    if (xmpFlip.FlipHorizontal)
                    {
                        image.Flip();
                    }
                }
                else if (action.GetType() == typeof(XmpStraighten))
                {
                    XmpStraighten xmpStraighten = (XmpStraighten)action;
                    image.VirtualPixelMethod = VirtualPixelMethod.Black;

                    if (xmpStraighten.Crop)
                    {
                        //http://www.imagemagick.org/Usage/distorts/#rotate_methods

                        int    w   = image.Width;
                        int    h   = image.Height;
                        double aa  = xmpStraighten.Angle * Math.PI / 180;
                        double srt = (w * Math.Abs(Math.Sin(aa)) + h * Math.Abs(Math.Cos(aa))) / Math.Min(w, h);

                        image.Distort(DistortMethod.ScaleRotateTranslate, srt, xmpStraighten.Angle);
                    }
                    else
                    {
                        image.Rotate(xmpStraighten.Angle);
                    }
                }
            }
        }
Esempio n. 45
0
        /// <summary>
        /// Load image from file
        /// </summary>
        /// <param name="filename">Full path of image file</param>
        /// <param name="size">A custom size of image</param>
        /// <param name="colorProfileName">Name or Full path of color profile</param>
        /// <param name="isApplyColorProfileForAll">If FALSE, only the images with embedded profile will be applied</param>
        /// <param name="quality">Image quality</param>
        /// <param name="channel">MagickImage.Channel value</param>
        /// <param name="useEmbeddedThumbnails">Return the embedded thumbnail if required size was not found.</param>
        /// <returns>Bitmap</returns>
        public static ImgData Load(
            string filename,
            Size size = new Size(),
            string colorProfileName        = "sRGB",
            bool isApplyColorProfileForAll = false,
            int quality = 100,
            int channel = -1,
            bool useEmbeddedThumbnails = false
            )
        {
            Bitmap        bitmap       = null;
            IExifProfile  exif         = null;
            IColorProfile colorProfile = null;

            var ext      = Path.GetExtension(filename).ToUpperInvariant();
            var settings = new MagickReadSettings();

            #region Settings
            if (ext == ".SVG")
            {
                settings.BackgroundColor = MagickColors.Transparent;
                settings.SetDefine("svg:xml-parse-huge", "true");
            }

            if (size.Width > 0 && size.Height > 0)
            {
                settings.Width  = size.Width;
                settings.Height = size.Height;
            }


            // Fixed #708: length and filesize do not match
            settings.SetDefines(new BmpReadDefines {
                IgnoreFileSize = true,
            });

            // Fix RAW color
            settings.SetDefines(new DngReadDefines()
            {
                UseCameraWhitebalance = true,
            });

            #endregion


            #region Read image data
            switch (ext)
            {
            case ".TXT":     // base64 string
            case ".B64":
                var base64Content = string.Empty;
                using (var fs = new StreamReader(filename)) {
                    base64Content = fs.ReadToEnd();
                }

                bitmap = ConvertBase64ToBitmap(base64Content);
                break;

            case ".GIF":
            case ".TIF":
                // Note: Using FileStream is much faster than using MagickImageCollection

                try {
                    bitmap = ConvertFileToBitmap(filename);
                }
                catch {
                    // #637: falls over with certain images, fallback to MagickImage
                    ReadWithMagickImage();
                }
                break;

            case ".ICO":
            case ".WEBP":
            case ".PDF":
                using (var imgColl = new MagickImageCollection(filename, settings)) {
                    bitmap = imgColl.ToBitmap();
                }
                break;

            default:
                ReadWithMagickImage();

                break;
            }
            #endregion


            #region Internal Functions

            // Preprocess magick image
            (IExifProfile, IColorProfile) PreprocesMagickImage(MagickImage imgM, bool checkRotation = true)
            {
                imgM.Quality = quality;

                IColorProfile imgColorProfile = null;
                IExifProfile  profile         = null;

                try {
                    // get the color profile of image
                    imgColorProfile = imgM.GetColorProfile();

                    // Get Exif information
                    profile = imgM.GetExifProfile();
                }
                catch { }

                // Use embedded thumbnails if specified
                if (profile != null && useEmbeddedThumbnails)
                {
                    // Fetch the embedded thumbnail
                    var thumbM = profile.CreateThumbnail();
                    if (thumbM != null)
                    {
                        bitmap = thumbM.ToBitmap();
                    }
                }

                // Revert to source image if an embedded thumbnail with required size was not found.
                if (bitmap == null)
                {
                    if (profile != null && checkRotation)
                    {
                        // Get Orientation Flag
                        var exifRotationTag = profile.GetValue(ExifTag.Orientation);

                        if (exifRotationTag != null)
                        {
                            if (int.TryParse(exifRotationTag.Value.ToString(), out var orientationFlag))
                            {
                                var orientationDegree = Helpers.GetOrientationDegree(orientationFlag);
                                if (orientationDegree != 0)
                                {
                                    //Rotate image accordingly
                                    imgM.Rotate(orientationDegree);
                                }
                            }
                        }
                    }

                    // if always apply color profile
                    // or only apply color profile if there is an embedded profile
                    if (isApplyColorProfileForAll || imgColorProfile != null)
                    {
                        if (imgColorProfile != null)
                        {
                            // correct the image color space
                            imgM.ColorSpace = imgColorProfile.ColorSpace;
                        }
                        else
                        {
                            // set default color profile and color space
                            imgM.SetProfile(ColorProfile.SRGB);
                            imgM.ColorSpace = ColorProfile.SRGB.ColorSpace;
                        }

                        var imgColor = Helpers.GetColorProfile(colorProfileName);
                        if (imgColor != null)
                        {
                            imgM.SetProfile(imgColor);
                            imgM.ColorSpace = imgColor.ColorSpace;
                        }
                    }
                }

                return(profile, imgColorProfile);
            }

            // Separate color channel
            MagickImage ApplyColorChannel(MagickImage imgM)
            {
                if (channel != -1)
                {
                    var magickChannel = (Channels)channel;
                    var channelImgM   = (MagickImage)imgM.Separate(magickChannel).First();

                    if (imgM.HasAlpha && magickChannel != Channels.Alpha)
                    {
                        using var alpha = imgM.Separate(Channels.Alpha).First();
                        channelImgM.Composite(alpha, CompositeOperator.CopyAlpha);
                    }

                    return(channelImgM);
                }

                return(imgM);
            }

            void ReadWithMagickImage()
            {
                MagickImage imgM;

                // Issue #530: ImageMagick falls over if the file path is longer than the (old) windows limit of 260 characters. Workaround is to read the file bytes, but that requires using the "long path name" prefix to succeed.
                if (filename.Length > 260)
                {
                    var newFilename = Helpers.PrefixLongPath(filename);
                    var allBytes    = File.ReadAllBytes(newFilename);

                    imgM = new MagickImage(allBytes, settings);
                }
                else
                {
                    imgM = new MagickImage(filename, settings);
                }


                // Issue #679: fix targa display with Magick.NET 7.15.x
                if (ext == ".TGA")
                {
                    imgM.AutoOrient();
                }


                var checkRotation = ext != ".HEIC";

                (exif, colorProfile) = PreprocesMagickImage(imgM, checkRotation);

                using (var channelImgM = ApplyColorChannel(imgM)) {
                    bitmap = channelImgM.ToBitmap();
                }

                imgM.Dispose();
            }

            #endregion


            return(new ImgData()
            {
                Image = bitmap,
                Exif = exif,
                ColorProfile = colorProfile,
            });
        }
 public static void StandardResize(ref MagickImage mi, MagickGeometry geo)
 {
     geo.IgnoreAspectRatio = true;
     mi.Scale(geo);
     mi.RePage();
 }
Esempio n. 47
0
        /// <summary>
        /// Converts base64 string to Bitmap.
        /// </summary>
        /// <param name="content">Base64 string</param>
        /// <returns></returns>
        public static Bitmap ConvertBase64ToBitmap(string content)
        {
            var(mimeType, rawData) = ConvertBase64ToBytes(content);
            if (string.IsNullOrEmpty(mimeType))
            {
                return(null);
            }

            #region Settings
            var settings = new MagickReadSettings();
            switch (mimeType)
            {
            case "image/bmp":
                settings.Format = MagickFormat.Bmp;
                break;

            case "image/gif":
                settings.Format = MagickFormat.Gif;
                break;

            case "image/tiff":
                settings.Format = MagickFormat.Tiff;
                break;

            case "image/jpeg":
                settings.Format = MagickFormat.Jpeg;
                break;

            case "image/svg+xml":
                settings.BackgroundColor = MagickColors.Transparent;
                settings.Format          = MagickFormat.Svg;
                break;

            case "image/x-icon":
                settings.Format = MagickFormat.Ico;
                break;

            case "image/x-portable-anymap":
                settings.Format = MagickFormat.Pnm;
                break;

            case "image/x-portable-bitmap":
                settings.Format = MagickFormat.Pbm;
                break;

            case "image/x-portable-graymap":
                settings.Format = MagickFormat.Pgm;
                break;

            case "image/x-portable-pixmap":
                settings.Format = MagickFormat.Ppm;
                break;

            case "image/x-xbitmap":
                settings.Format = MagickFormat.Xbm;
                break;

            case "image/x-xpixmap":
                settings.Format = MagickFormat.Xpm;
                break;

            case "image/x-cmu-raster":
                settings.Format = MagickFormat.Ras;
                break;
            }
            #endregion

            Bitmap bmp = null;

            switch (settings.Format)
            {
            case MagickFormat.Gif:
            case MagickFormat.Gif87:
            case MagickFormat.Tif:
            case MagickFormat.Tiff64:
            case MagickFormat.Tiff:
            case MagickFormat.Ico:
            case MagickFormat.Icon:
                bmp = new Bitmap(new MemoryStream(rawData)
                {
                    Position = 0
                }, true);

                break;

            default:
                using (var imgM = new MagickImage(rawData, settings)) {
                    bmp = imgM.ToBitmap();
                }
                break;
            }

            return(bmp);
        }
Esempio n. 48
0
        /// <summary>
        /// Create a sprite image from a list of images and the CSS to render each image.
        /// </summary>
        /// <param name="images">The list of images to include in the sprite.</param>
        /// <param name="placeholderImages">The list of custom placeholder images.</param>
        /// <param name="spriteSettings">The settings to use when creating the sprite.</param>
        public void CreateSprite(IReadOnlyCollection<ISpriteImage> images, IReadOnlyCollection<ISpriteImage> placeholderImages, SpriteSettings spriteSettings)
        {
            if (images == null)
            {
                throw new ArgumentNullException(nameof(images));
            }

            if (images.GroupBy(x => x.Key).Any(x => x.Skip(1).Any()))
            {
                throw new ArgumentException("The list of keys must be unique.", nameof(images));
            }

            if (placeholderImages == null || !placeholderImages.Any())
            {
                placeholderImages = DefaultPlaceholderImages;
            }

            if (placeholderImages.GroupBy(x => x.Key).Any(x => x.Skip(1).Any()))
            {
                throw new ArgumentException("The list of keys must be unique.", nameof(placeholderImages));
            }

            if (spriteSettings == null)
            {
                throw new ArgumentNullException(nameof(spriteSettings));
            }

            var spritePlaceholderImages = new List<SpritePlaceholderImage>();

            using (var spriteImages = new MagickImageCollection())
            {
                var css = new StringBuilder();
                var nextSpriteImageTop = 0;                

                foreach (ISpriteImage image in images)
                {
                    var hasImageBeenAddedToSprite = false;
                    int selectedImageHeight;
                    int selectedImageTop;
                    int selectedImageWidth;
                    var selectedHoverImageHeight = 0;
                    var selectedHoverImageTop = 0;
                    var selectedHoverImageWidth = 0;

                    MagickImage imageForSprite = ImageToMagickImage(image);

                    if (imageForSprite != null)
                    {
                        spriteImages.Add(imageForSprite);
                        hasImageBeenAddedToSprite = true;
                        selectedImageTop = nextSpriteImageTop;
                        selectedImageHeight = imageForSprite.Height;
                        selectedImageWidth = imageForSprite.Width;
                    }
                    else
                    {
                        string selectedPlaceholderImageKey = placeholderImages.Any(x => x.Key == image.PlaceholderImageKey) ? image.PlaceholderImageKey : placeholderImages.First().Key;
                        ISpriteImage selectedPlaceholderImage = placeholderImages.FirstOrDefault(x => x.Key == selectedPlaceholderImageKey);
                        imageForSprite = ImageToMagickImage(selectedPlaceholderImage);

                        SpritePlaceholderImage spritePlaceholderImage = spritePlaceholderImages.FirstOrDefault(x => x.Key == selectedPlaceholderImageKey && x.Width == imageForSprite.Width && x.Height == imageForSprite.Height);

                        if (spritePlaceholderImage == null)
                        {
                            spritePlaceholderImage = new SpritePlaceholderImage(selectedPlaceholderImageKey, nextSpriteImageTop, imageForSprite.Height, imageForSprite.Width);
                            spritePlaceholderImages.Add(spritePlaceholderImage);

                            spriteImages.Add(imageForSprite);
                            hasImageBeenAddedToSprite = true;
                        }

                        selectedImageTop = spritePlaceholderImage.Top;
                        selectedImageHeight = spritePlaceholderImage.Height;
                        selectedImageWidth = spritePlaceholderImage.Width;
                    }

                    string selectedImageTopText = selectedImageTop != 0 ? $"-{selectedImageTop}px" : "0";
                    css.Append($"#{image.Key}{{height:{selectedImageHeight}px;width:{selectedImageWidth}px;background:url('{spriteSettings.SpriteUrl}') 0 {selectedImageTopText};}}");

                    if (hasImageBeenAddedToSprite)
                    {
                        nextSpriteImageTop += selectedImageHeight;
                    }

                    if (image.HoverImage != null)
                    {
                        MagickImage hoverImageForSprite = ImageToMagickImage(image.HoverImage, imageForSprite);

                        if (hoverImageForSprite != null)
                        {
                            spriteImages.Add(hoverImageForSprite);
                            hasImageBeenAddedToSprite = true;
                            selectedHoverImageTop = nextSpriteImageTop;
                            selectedHoverImageHeight = hoverImageForSprite.Height;
                            selectedHoverImageWidth = hoverImageForSprite.Width;
                        }

                        string selectedHoverImageTopText = selectedHoverImageTop != 0 ? $"-{selectedHoverImageTop}px" : "0";
                        css.Append($"#{image.Key}:hover{{height:{selectedHoverImageHeight}px;width:{selectedHoverImageWidth}px;background:url('{spriteSettings.SpriteUrl}') 0 {selectedHoverImageTopText};}}");

                        if (hasImageBeenAddedToSprite)
                        {
                            nextSpriteImageTop += selectedHoverImageHeight;
                        }
                    }
                }

                _imageProcessor.CreateSprite(spriteImages, spriteSettings.SpriteFilename);
                _cssProcessor.CreateCss(css.ToString(), spriteSettings.CssFilename);
            }
        }
Esempio n. 49
0
        public void ApplyFilters(IList <Filter> filters, IList <string> files, string destinationFolder, string sourceFolder)
        {
            var processed = 0;

            Parallel.ForEach(files, new ParallelOptions {
                MaxDegreeOfParallelism = Environment.ProcessorCount - 1
            }, file =>
            {
                var frames = new List <string>();
                try
                {
                    using (var tiffImage = System.Drawing.Image.FromFile(file))
                    {
                        var pageCount = tiffImage.GetFrameCount(FrameDimension.Page);
                        for (var j = 0; j < pageCount; j++)
                        {
                            tiffImage.SelectActiveFrame(FrameDimension.Page, j);
                            using (var bitmap = new Bitmap(tiffImage))
                            {
                                var image = new MagickImage(bitmap);

                                image         = filters.Aggregate(image, (current, filter) => filter.ApplyFilter(current));
                                image.Density = new Density(tiffImage.HorizontalResolution,
                                                            tiffImage.VerticalResolution);

                                var tempPath = Path.GetTempFileName();
                                frames.Add(tempPath);
                                image.Write(tempPath);
                                image.Dispose();
                            }
                        }
                        var relativePath = file.Replace(sourceFolder, "");
                        if (relativePath.StartsWith(@"\"))
                        {
                            relativePath = relativePath.Substring(1, relativePath.Length - 1);
                        }

                        var savePath = Path.Combine(destinationFolder, relativePath);
                        if (savePath.Contains(@"\"))
                        {
                            var directory = new DirectoryInfo(savePath.Substring(0, savePath.LastIndexOf(@"\", StringComparison.Ordinal)));
                            if (!directory.Exists)
                            {
                                directory.Create();
                            }
                        }
                        Save(savePath, frames);
                        lock (Mutex)
                        {
                            processed++;
                        }
                        ProgressChanged(this, new ProgressChangedEventArgument
                        {
                            Current = processed,
                            Total   = files.Count,
                            Message = new ChangedEventMessage($"Processed '{file}' ({savePath})", EnumMessageType.Informational)
                        });
                    }
                }
                catch (Exception ex)
                {
                    lock (Mutex)
                    {
                        processed++;
                    }
                    ProgressChanged(this, new ProgressChangedEventArgument
                    {
                        Current = processed,
                        Total   = files.Count,
                        Message = new ChangedEventMessage($"Unable to process '{file}' ({ex.Message})", EnumMessageType.Error)
                    });
                }
                finally
                {
                    Clean(frames);
                }
            });
        }
Esempio n. 50
0
        public static void Main(string[] args)
        {
            DirectoryInfo inputDirectory = new DirectoryInfo(@"D:\Published photos");

            foreach (FileInfo file in _outputDirectory.EnumerateFiles())
            {
                file.Delete();
            }
            foreach (DirectoryInfo dir in _outputDirectory.EnumerateDirectories())
            {
                dir.Delete(true);
            }

            int maxImageDimension = 2560;

            var galleries = new List <Gallery>();

            foreach (DirectoryInfo galleryDir in inputDirectory.EnumerateDirectories())
            {
                Gallery gallery = new Gallery();

                var galleryConfig = galleryDir.GetFiles("gallery.yaml").FirstOrDefault();
                if (galleryConfig != null)
                {
                    using (StreamReader config = galleryConfig.OpenText())
                    {
                        var deserializer = new DeserializerBuilder()
                                           .WithNamingConvention(new CamelCaseNamingConvention())
                                           .Build();

                        gallery = deserializer.Deserialize <Gallery>(config);
                        galleries.Add(gallery);
                    }
                }

                _outputDirectory.CreateSubdirectory(gallery.Uri);

                foreach (FileInfo photoFile in galleryDir.EnumerateFiles())
                {
                    if (photoFile.Extension.ToLower() != ".jpg" && photoFile.Extension.ToLower() != ".jpeg")
                    {
                        continue;
                    }

                    Console.WriteLine($"Processing photo {photoFile.FullName}");
                    try
                    {
                        using (MagickImage image = new MagickImage(photoFile))
                        {
                            var photograph = new Photograph()
                            {
                                FileName = photoFile.Name
                            };
                            photograph.ParseMetadata(image.GetExifProfile());

                            gallery.Photographs.Add(photograph);

                            string filePath = Path.Combine(_outputDirectory.FullName, gallery.Uri, photoFile.Name);
                            ProcessImage(image, maxImageDimension, filePath);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                }
            }

            MakeIndex(galleries);

            foreach (var gallery in galleries)
            {
                MakeGallery(gallery);
            }
        }
Esempio n. 51
0
        public void GenerateCache(FileItem fileItem)
        {
            bool deleteFile = false;

            if (fileItem == null)
            {
                return;
            }
            if (!File.Exists(fileItem.FileName))
            {
                return;
            }

            if ((File.Exists(fileItem.LargeThumb) && File.Exists(fileItem.SmallThumb)) && File.Exists(fileItem.InfoFile))
            {
                return;
            }

            if (fileItem.Loading)
            {
                return;
            }

            fileItem.Loading = true;

            PhotoUtils.WaitForFile(fileItem.FileName);
            string filename = fileItem.FileName;

            if (fileItem.IsMovie)
            {
                try
                {
                    string ffmpeg_exe = Path.Combine(Settings.ApplicationFolder, "ffmpeg.exe");
                    if (File.Exists(ffmpeg_exe))
                    {
                        string thumb = Path.Combine(Path.GetDirectoryName(fileItem.FileName),
                                                    Path.GetFileNameWithoutExtension(fileItem.FileName) + ".thumb.jpg");
                        PhotoUtils.RunAndWait(ffmpeg_exe, String.Format("-i \"{0}\" -ss 00:00:01.000 -f image2 -vframes 1 \"{1}\"", fileItem.FileName, thumb));
                        if (File.Exists(thumb))
                        {
                            deleteFile = true;
                            filename   = thumb;
                        }
                    }
                }
                catch (Exception exception)
                {
                    Log.Error("Error get video thumb", exception);
                }
            }
            if (fileItem.IsRaw)
            {
                try
                {
                    string dcraw_exe = Path.Combine(Settings.ApplicationFolder, "dcraw.exe");
                    if (File.Exists(dcraw_exe))
                    {
                        string thumb = Path.Combine(Path.GetTempPath(),
                                                    Path.GetFileNameWithoutExtension(fileItem.FileName) + ".thumb.jpg");
                        PhotoUtils.RunAndWait(dcraw_exe,
                                              string.Format(" -e -O \"{0}\" \"{1}\"", thumb, fileItem.FileName));
                        if (File.Exists(thumb))
                        {
                            deleteFile = true;
                            filename   = thumb;
                        }
                    }
                }
                catch (Exception exception)
                {
                    Log.Error("Error get dcraw thumb", exception);
                }
            }

            GetMetadata(fileItem);
            try
            {
                using (MagickImage image = new MagickImage(filename))
                {
                    fileItem.FileInfo.SetSize(image.Width, image.Height);

                    double dw = (double)LargeThumbSize / image.Width;
                    image.FilterType = FilterType.Box;
                    image.Thumbnail((int)(image.Width * dw), (int)(image.Height * dw));

                    image.UnsharpMask(1, 1, 0.5, 0.1);

                    PhotoUtils.CreateFolder(fileItem.LargeThumb);
                    image.Write(fileItem.LargeThumb);
                    fileItem.IsLoaded = true;
                    fileItem.Loading  = false;

                    dw = (double)SmallThumbSize / image.Width;
                    image.Thumbnail((int)(image.Width * dw), (int)(image.Height * dw));

                    image.UnsharpMask(1, 1, 0.5, 0.1);

                    PhotoUtils.CreateFolder(fileItem.SmallThumb);
                    image.Write(fileItem.SmallThumb);

                    fileItem.Thumbnail = LoadImage(fileItem.SmallThumb);
                }
                fileItem.SaveInfo();
                SetImageInfo(fileItem);
                if (deleteFile)
                {
                    File.Delete(filename);
                }
                OnMetaDataUpdated(fileItem);
            }
            catch (Exception exception)
            {
                Log.Error("Error generating cache " + fileItem.FileName, exception);
            }
            fileItem.Loading = false;
        }
Esempio n. 52
0
        /// <summary>
        /// Load image from file
        /// </summary>
        /// <param name="path">Full path  of image file</param>
        /// <param name="size">A custom size of image</param>
        /// <param name="colorProfileName">Name or Full path of color profile</param>
        /// <param name="isApplyColorProfileForAll">If FALSE, only the images with embedded profile will be applied</param>
        /// <returns></returns>
        public static Bitmap Load(string path, Size size = new Size(), string colorProfileName = "sRGB", bool isApplyColorProfileForAll = false)
        {
            var    ext = Path.GetExtension(path).ToLower();
            Bitmap bmp = null;

            switch (ext)
            {
            case ".gif":
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    var ms = new MemoryStream();
                    fs.CopyTo(ms);
                    ms.Position = 0;

                    bmp = new Bitmap(ms, true);
                }
                break;

            case ".ico":
                bmp = ReadIconFile(path);
                break;

            default:
                try
                {
                    bmp = GetBitmapFromFile();

                    if (bmp == null)
                    {
                        bmp = GetBitmapFromWic();
                    }
                }
                catch (Exception)
                {
                    bmp = GetBitmapFromWic();
                }
                break;
            }

            Bitmap GetBitmapFromFile()
            {
                Bitmap bmpData  = null;
                var    settings = new MagickReadSettings();

                if (ext.CompareTo(".svg") == 0)
                {
                    settings.BackgroundColor = MagickColors.Transparent;
                }

                if (size.Width > 0 && size.Height > 0)
                {
                    settings.Width  = size.Width;
                    settings.Height = size.Height;
                }

                //using (var magicColl = new MagickImageCollection())
                //{
                //    magicColl.Read(new FileInfo(path), settings);

                //    if (magicColl.Count > 0)
                //    {
                //        magicColl[0].Quality = 100;
                //        magicColl[0].AddProfile(ColorProfile.SRGB);

                //        bmp = BitmapBooster.BitmapFromSource(magicColl[0].ToBitmapSource());
                //    }
                //}

                using (var magicImg = new MagickImage(path, settings))
                {
                    magicImg.Quality = 100;

                    //Get Exif information
                    var profile = magicImg.GetExifProfile();
                    if (profile != null)
                    {
                        //Get Orieantation Flag
                        var exifTag = profile.GetValue(ExifTag.Orientation);

                        if (exifTag != null)
                        {
                            int orientationFlag = int.Parse(profile.GetValue(ExifTag.Orientation).Value.ToString());

                            var orientationDegree = GetOrientationDegree(orientationFlag);
                            if (orientationDegree != 0)
                            {
                                //Rotate image accordingly
                                magicImg.Rotate(orientationDegree);
                            }
                        }
                    }


                    // get the color profile of image
                    var imgColorProfile = magicImg.GetColorProfile();


                    // if always apply color profile
                    // or only apply color profile if there is an embedded profile
                    if (isApplyColorProfileForAll || imgColorProfile != null)
                    {
                        if (imgColorProfile != null)
                        {
                            // correct the image color space
                            magicImg.ColorSpace = imgColorProfile.ColorSpace;
                        }
                        else
                        {
                            // set default color profile and color space
                            magicImg.AddProfile(ColorProfile.SRGB);
                            magicImg.ColorSpace = ColorProfile.SRGB.ColorSpace;
                        }

                        var colorProfile = GetColorProfileFromString(colorProfileName);
                        if (colorProfile != null)
                        {
                            magicImg.AddProfile(colorProfile);
                            magicImg.ColorSpace = colorProfile.ColorSpace;
                        }
                    }


                    //get bitmap
                    bmpData = magicImg.ToBitmap();
                }

                return(bmpData);
            }

            Bitmap GetBitmapFromWic()
            {
                Bitmap bmpData = null;

                var src = LoadImage(path);

                bmpData = BitmapFromSource(src);

                return(bmpData);
            }

            return(bmp);
        }
        public string OptimizeImage(IFormFile inputImage, int endHeight, int endWidth)
        {
            double aspectRatioCoeff = endHeight / endWidth;
            var    imageName        = Guid.NewGuid() + ".jpg";
            var    inputFileName    = Path.Combine(hostingEnvironment.WebRootPath, "images/") + imageName;

            using (var initialImageStream = new MemoryStream())
            {
                inputImage.CopyTo(initialImageStream);

                //Compress
                initialImageStream.Position = 0;
                var optimizer = new ImageMagick.ImageOptimizer();
                optimizer.LosslessCompress(initialImageStream);
                initialImageStream.Position = 0;

                //Resize
                using (MagickImage image = new MagickImage(initialImageStream))
                {
                    double tempWidth  = 0;
                    double tempHeight = 0;

                    double imgHeight   = image.Height;
                    double imgWidth    = image.Width;
                    double aspectRatio = imgHeight / imgWidth;

                    var scale = Math.Max(endWidth / imgWidth, endHeight / imgHeight);

                    tempWidth  = imgWidth * scale;
                    tempHeight = imgHeight * scale;

                    int resultedSize = (int)Math.Max(tempWidth, tempHeight);

                    MagickGeometry size = new MagickGeometry(resultedSize)
                    {
                        IgnoreAspectRatio = false
                    };

                    image.Resize(size);
                    var resizedImageByteArr = image.ToByteArray();

                    using (var finalImageStream = new MemoryStream(resizedImageByteArr))
                    {
                        //Crop
                        var cropRect = new Rectangle(0, 0, endWidth, endHeight);
                        using (Bitmap src = new Bitmap(finalImageStream))
                        {
                            using (Bitmap target = new Bitmap(cropRect.Width, cropRect.Height))
                            {
                                var      result = new Rectangle(0, 0, target.Width, target.Height);
                                Graphics g      = Graphics.FromImage(target);
                                g.DrawImage(src, result, cropRect, GraphicsUnit.Pixel);

                                target.Save(inputFileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                            }
                        }
                    }
                }
            }
            return(imageName);
        }
Esempio n. 54
0
        private void btnImageCompare_Click(object sender, EventArgs e)
        {
            string pictureDirectory = DirectoryHelper.PictureDirectory;

            if (string.IsNullOrWhiteSpace(pictureDirectory))
            {
                MessageBox.Show("Can't find picture directory, this form can't work!");
                return;
            }

            string OrginalFile = Path.Combine(pictureDirectory, "Original.jpg");

            MagickImage orgImage = null;
            MagickImage dupImage = null;

            DirectoryInfo di = new DirectoryInfo(pictureDirectory);
            Dictionary <string, double> imageCompareData = new Dictionary <string, double>();

            foreach (FileInfo fi in di.EnumerateFiles())
            {
                string filePath = fi.FullName;
                string fileName = fi.Name;
                if (filePath == OrginalFile)
                {
                    continue;
                }

                bool ispHashSelected         = cbCompareAlgorithm.Text == "pHash";
                bool isBhattacharyyaSelected = cbCompareAlgorithm.Text == "Bhattacharyya";

                if (ispHashSelected)
                {
                    var percentage = ImageHashing.Similarity(OrginalFile, filePath);
                    percentage = Math.Round(percentage, 3);
                    imageCompareData.Add(fileName, percentage);
                }
                else if (isBhattacharyyaSelected)
                {
                    Image img1       = Image.FromFile(OrginalFile);
                    Image img2       = Image.FromFile(filePath);
                    var   percentage = Bhattacharyya.BhattacharyyaDifference(img1, img2);
                    percentage = (1 - percentage) * 100;
                    percentage = Math.Round(percentage, 3);
                    imageCompareData.Add(fileName, percentage);
                }
                else
                {
                    orgImage = new MagickImage(OrginalFile);
                    int         imageAlgoIndex = cbCompareAlgorithm.SelectedIndex;
                    ErrorMetric imageAlgo      = (ErrorMetric)imageAlgoIndex;

                    dupImage = new MagickImage(filePath);
                    var percentage = orgImage.Compare(dupImage, imageAlgo);
                    percentage = Math.Round(percentage, 3);
                    imageCompareData.Add(fileName, percentage);
                }
            }

            var bl = new DictionaryBindingList <string, double>(imageCompareData);

            dataGridView1.DataSource = bl;

            if (orgImage != null)
            {
                orgImage.Dispose();
            }
            if (dupImage != null)
            {
                dupImage.Dispose();
            }
        }
Esempio n. 55
0
        /// <summary>
        /// Load image from file
        /// </summary>
        /// <param name="filename">Full path of image file</param>
        /// <param name="size">A custom size of image</param>
        /// <param name="colorProfileName">Name or Full path of color profile</param>
        /// <param name="isApplyColorProfileForAll">If FALSE, only the images with embedded profile will be applied</param>
        /// <param name="quality">Image quality</param>
        /// <param name="channel">MagickImage.Channel value</param>
        /// <param name="useEmbeddedThumbnails">Return the embedded thumbnail if required size was not found.</param>
        /// <returns>Bitmap</returns>
        public static Bitmap Load(
            string filename,
            Size size = new Size(),
            string colorProfileName        = "sRGB",
            bool isApplyColorProfileForAll = false,
            int quality = 100,
            int channel = -1,
            bool useEmbeddedThumbnails = false
            )
        {
            Bitmap bitmap   = null;
            var    ext      = Path.GetExtension(filename).ToUpperInvariant();
            var    settings = new MagickReadSettings();

            #region Settings
            if (ext == ".SVG")
            {
                settings.BackgroundColor = MagickColors.Transparent;
            }

            if (size.Width > 0 && size.Height > 0)
            {
                settings.Width  = size.Width;
                settings.Height = size.Height;
            }
            #endregion


            #region Read image data
            switch (ext)
            {
            case ".GIF":
                // Note: Using FileStream is much faster than using MagickImageCollection
                using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
                {
                    var ms = new MemoryStream();
                    fs.CopyTo(ms);
                    ms.Position = 0;

                    bitmap = new Bitmap(ms, true);
                }
                break;

            case ".ICO":
            case ".TIF":
            case ".WEBP":
                try
                {
                    using (var imgColl = new MagickImageCollection(filename, settings))
                    {
                        bitmap = imgColl.ToBitmap();
                    }
                }
                catch
                {
                    // Issue #637: MagickImageCollection falls over with certain images, fallback to MagickImage
                    ReadWithMagickImage();
                }
                break;

            default:
                ReadWithMagickImage();

                break;
            }
            #endregion


            #region Internal Functions

            // Preprocess magick image
            void PreprocesMagickImage(MagickImage imgM, bool checkRotation = true)
            {
                imgM.Quality = quality;


                // Get Exif information
                var profile = imgM.GetExifProfile();

                // Use embedded thumbnails if specified
                if (profile != null && useEmbeddedThumbnails)
                {
                    // Fetch the embedded thumbnail
                    var thumbM = profile.CreateThumbnail();
                    if (thumbM != null)
                    {
                        bitmap = thumbM.ToBitmap();
                    }
                }


                // Revert to source image if an embedded thumbnail with required size was not found.
                if (bitmap == null)
                {
                    if (profile != null && checkRotation)
                    {
                        // Get Orientation Flag
                        var exifRotationTag = profile.GetValue(ExifTag.Orientation);

                        if (exifRotationTag != null)
                        {
                            if (int.TryParse(exifRotationTag.Value.ToString(), out var orientationFlag))
                            {
                                var orientationDegree = Helpers.GetOrientationDegree(orientationFlag);
                                if (orientationDegree != 0)
                                {
                                    //Rotate image accordingly
                                    imgM.Rotate(orientationDegree);
                                }
                            }
                        }
                    }


                    // get the color profile of image
                    var imgColorProfile = imgM.GetColorProfile();


                    // if always apply color profile
                    // or only apply color profile if there is an embedded profile
                    if (isApplyColorProfileForAll || imgColorProfile != null)
                    {
                        if (imgColorProfile != null)
                        {
                            // correct the image color space
                            imgM.ColorSpace = imgColorProfile.ColorSpace;
                        }
                        else
                        {
                            // set default color profile and color space
                            imgM.AddProfile(ColorProfile.SRGB);
                            imgM.ColorSpace = ColorProfile.SRGB.ColorSpace;
                        }

                        var colorProfile = Helpers.GetColorProfile(colorProfileName);
                        if (colorProfile != null)
                        {
                            imgM.AddProfile(colorProfile);
                            imgM.ColorSpace = colorProfile.ColorSpace;
                        }
                    }
                }
            }

            // Separate color channel
            MagickImage ApplyColorChannel(MagickImage imgM)
            {
                // separate color channel
                if (channel != -1)
                {
                    var magickChannel = (Channels)channel;
                    var channelImgM   = (MagickImage)imgM.Separate(magickChannel).First();

                    if (imgM.HasAlpha && magickChannel != Channels.Alpha)
                    {
                        using (var alpha = imgM.Separate(Channels.Alpha).First())
                        {
                            channelImgM.Composite(alpha, CompositeOperator.CopyAlpha);
                        }
                    }


                    return(channelImgM);
                }

                return(imgM);
            }

            void ReadWithMagickImage()
            {
                // Issue #530: ImageMagick falls over if the file path is longer than the (old)
                // windows limit of 260 characters. Workaround is to read the file bytes, but
                // that requires using the "long path name" prefix to succeed.

                //filename = Helpers.PrefixLongPath(filename);
                //var allBytes = File.ReadAllBytes(filename);

                // TODO: there is a bug of using bytes[]:
                // https://github.com/dlemstra/Magick.NET/issues/538
                using (var imgM = new MagickImage(filename, settings))
                {
                    var checkRotation = ext != ".HEIC";
                    PreprocesMagickImage(imgM, checkRotation);

                    using (var channelImgM = ApplyColorChannel(imgM))
                    {
                        bitmap = channelImgM.ToBitmap();
                    }
                }
            }

            #endregion


            return(bitmap);
        }
Esempio n. 56
0
 public void ShouldNotThrowExceptionWhenSettingsIsNull()
 {
     using (var image = new MagickImage(Files.CirclePNG, (MagickReadSettings)null))
     {
     }
 }
Esempio n. 57
0
        /// <summary> Handles the process if no CLI parse errors.</summary>
        /// <param name="opts">The opts.</param>
        /// <returns></returns>
        private static int RunOptionsAndReturnExitCode(Options opts)
        {
            Console.WriteLine("Searching for image perceptual similarities...");
            var defaultColor = Console.ForegroundColor;

            try
            {
                var files = Directory.EnumerateFiles(opts.SourceFolder, "*.*", SearchOption.AllDirectories)
                            .Where(s => s.EndsWith(".jpg") || s.EndsWith(".jpeg") || s.EndsWith(".png") || s.EndsWith(".bmp") || s.EndsWith(".gif") || s.EndsWith(".tif") || s.EndsWith(".tiff"));

                var imageHasher = new ImageHashes(new ImageMagickTransformer());
                foreach (var file in files)
                {
                    var currentImage = new MagickImage(file);
                    var currentSize  = currentImage.Width * currentImage.Height;

                    Console.WriteLine("{0} ({1}x{2})", file, currentImage.Width, currentImage.Height);
                    var currentHash = imageHasher.CalculateDifferenceHash64(file);

                    var sim = 0f;
                    foreach (var hash in _hashList)
                    {
                        sim = ImageHashes.CompareHashes(hash.Key, currentHash);
                        if (sim >= opts.Threshold)
                        {
                            var existingImage = new MagickImage(hash.Value);
                            var existingSize  = existingImage.Width * existingImage.Height;

                            if (currentImage > existingImage)
                            {
                                Console.ForegroundColor = ConsoleColor.Magenta;
                                Console.WriteLine("\t=> Found ! (sim = {0}) {1} ({2}x{3})", sim, hash.Value, existingImage.Width, existingImage.Height);
                                Console.ForegroundColor = defaultColor;

                                File.Move(file, opts.DestinationFolder.TrimEnd('\\') + "\\" + Path.GetFileName(file));
                            }
                            else if (currentImage == existingImage)
                            {
                                Console.ForegroundColor = ConsoleColor.Green;
                                Console.WriteLine("\t=> Found ! (sim = {0}) {1} ({2}x{3})", sim, hash.Value, existingImage.Width, existingImage.Height);
                                Console.ForegroundColor = defaultColor;

                                File.Move(file, opts.DestinationFolder.TrimEnd('\\') + "\\" + Path.GetFileName(file));
                            }
                            else
                            {
                                Console.ForegroundColor = ConsoleColor.Yellow;
                                Console.WriteLine("\t=> Found ! (sim = {0}) {1} ({2}x{3})", sim, hash.Value, existingImage.Width, existingImage.Height);
                                Console.ForegroundColor = defaultColor;

                                File.Move(hash.Value, opts.DestinationFolder.TrimEnd('\\') + "\\" + Path.GetFileName(hash.Value));
                            }
                            break;
                        }
                    }

                    if (sim != 1)
                    {
                        _hashList.Add(currentHash, file);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error : " + ex.Message);
                Console.ForegroundColor = defaultColor;
                return(1);
            }

            return(0);
        }
Esempio n. 58
0
        public Perceptron Renderizar(ExemploCollection exemplos, int resX, int resY, string filename)
        {
            if (Entradas != 2)
            {
                throw new FormatException("Só é possível gerar o gráfico com um perceptron de duas entradas");
            }
            Console.WriteLine("Gerando gráfico...");
            MagickColor
                activeC       = MagickColor.FromRgb(72, 187, 133),
                inactiveC     = MagickColor.FromRgb(240, 106, 133),
                pointActive   = MagickColor.FromRgb(0, 255, 0),
                pointInactive = MagickColor.FromRgb(255, 0, 0);

            ushort[]
            active = new ushort[] { activeC.R, activeC.G, activeC.B },
            inactive      = new ushort[] { inactiveC.R, inactiveC.G, inactiveC.B };
            using var img = new MagickImage(MagickColor.FromRgb(0, 0, 0), resX, resY);
            var pxls = img.GetPixelsUnsafe();
            var draw = new Drawables();

            double[] praTestar = new double[Entradas];
            for (int x = 0; x < img.Width; x++)
            {
                praTestar[0] = ((double)x).Map(0, img.Width, 0, 1);
                for (int y = 0; y < img.Height; y++)
                {
                    praTestar[1] = ((double)y).Map(0, img.Height, 1, 0);
                    pxls.SetPixel(x, y, Testar(praTestar) ? active : inactive);
                }
            }

            var pointSize = Math.Min(img.Width, img.Height) / 25;

            int acertos = 0;

            for (int i = 0; i < exemplos.Count; i++)
            {
                var rad = i < QuantTreinamento ? pointSize / 3 : pointSize / 10;
                if (Testar(exemplos[i]) == exemplos[i].Saída)
                {
                    acertos++;
                }
                draw.FillColor(exemplos[i].Saída ? pointActive : pointInactive)
                .Ellipse(exemplos[i].Entradas[0].Map(0, exemplos.Máximos[0], 0, img.Width), exemplos[i].Entradas[1].Map(0, exemplos.Máximos[1], img.Height, 0), rad, rad, 0, 360);
            }

            var margin = 15;

            draw.FillColor(MagickColor.FromRgb(0, 0, 0))
            .Font("Consolas")
            .FontPointSize(pointSize)
            .TextAlignment(TextAlignment.Left)
            .Text(margin, img.Height - margin, "0")
            .Text(margin, margin + pointSize, exemplos.Máximos[1].ToString())
            .Text(margin, img.Height / 2, exemplos.Títulos[1])
            .TextAlignment(TextAlignment.Right)
            .Text(img.Width - margin, img.Height - margin, exemplos.Máximos[0].ToString())
            .TextAlignment(TextAlignment.Center)
            .Text(img.Width / 2, img.Height - margin, exemplos.Títulos[0])
            .Text(img.Width / 2, margin + pointSize, $"{Math.Floor(PropTreinamento * 100)}% de treinamento; {Math.Floor(((float)acertos / exemplos.Count) * 100)}% de acertos")
            .FillColor(MagickColor.FromRgb(255, 255, 255))
            .Line(margin / 2, 0, margin / 2, img.Height)
            .Line(0, img.Height - margin / 2, img.Width, img.Height - margin / 2)
            .Draw(img);
            img.Write(filename);
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Process.Start("explorer", filename);
            }
            Console.WriteLine($"Gráfico gerado e salvo no arquivo {filename}");
            return(this);
        }
Esempio n. 59
0
        public void Test_Drawables()
        {
            PointD[] coordinates = new PointD[3];
            coordinates[0] = new PointD(0, 0);
            coordinates[1] = new PointD(50, 50);
            coordinates[2] = new PointD(99, 99);

            using (IMagickImage image = new MagickImage(MagickColors.Transparent, 100, 100))
            {
                image.Draw(new DrawableAffine(0, 0, 1, 1, 2, 2));
                image.Draw(new DrawableAlpha(0, 0, PaintMethod.Floodfill));
                image.Draw(new DrawableArc(0, 0, 10, 10, 45, 90));

                var bezier = new DrawableBezier(coordinates.ToList());
                Assert.AreEqual(3, bezier.Coordinates.Count());
                image.Draw(bezier);

                image.Draw(new DrawableBorderColor(MagickColors.Fuchsia));
                image.Draw(new DrawableCircle(0, 0, 50, 50));
                image.Draw(new DrawableClipPath("foo"));
                image.Draw(new DrawableClipRule(FillRule.Nonzero));
                image.Draw(new DrawableClipUnits(ClipPathUnit.UserSpaceOnUse));
                image.Draw(new DrawableColor(0, 0, PaintMethod.Floodfill));

                using (IMagickImage compositeImage = new MagickImage(new MagickColor("red"), 50, 50))
                {
                    image.Draw(new DrawableComposite(0, 0, compositeImage));
                    image.Draw(new DrawableComposite(0, 0, CompositeOperator.Over, compositeImage));
                    image.Draw(new DrawableComposite(new MagickGeometry(50, 50, 10, 10), compositeImage));
                    image.Draw(new DrawableComposite(new MagickGeometry(50, 50, 10, 10), CompositeOperator.Over, compositeImage));
                }

                image.Draw(new DrawableDensity(97));
                image.Draw(new DrawableEllipse(10, 10, 4, 4, 0, 360));
                image.Draw(new DrawableFillColor(MagickColors.Red));
                image.Draw(new DrawableFillOpacity(new Percentage(50)));
                image.Draw(new DrawableFillRule(FillRule.EvenOdd));
                image.Draw(new DrawableFont("Arial.ttf"));
                image.Draw(new DrawableFont("Arial"));
                image.Draw(new DrawableGravity(Gravity.Center));
                image.Draw(new DrawableLine(20, 20, 40, 40));
                image.Draw(new DrawablePoint(60, 60));
                image.Draw(new DrawableFontPointSize(5));
                image.Draw(new DrawablePolygon(coordinates));
                image.Draw(new DrawablePolygon(coordinates.ToList()));
                image.Draw(new DrawablePolyline(coordinates));
                image.Draw(new DrawablePolyline(coordinates.ToList()));
                image.Draw(new DrawableRectangle(30, 30, 70, 70));
                image.Draw(new DrawableRotation(180));
                image.Draw(new DrawableRoundRectangle(50, 50, 30, 30, 70, 70));
                image.Draw(new DrawableScaling(15, 15));
                image.Draw(new DrawableSkewX(90));
                image.Draw(new DrawableSkewY(90));
                image.Draw(new DrawableStrokeAntialias(true));
                image.Draw(new DrawableStrokeColor(MagickColors.Purple));
                image.Draw(new DrawableStrokeDashArray(new double[2] {
                    10, 20
                }));
                image.Draw(new DrawableStrokeDashOffset(2));
                image.Draw(new DrawableStrokeLineCap(LineCap.Square));
                image.Draw(new DrawableStrokeLineJoin(LineJoin.Bevel));
                image.Draw(new DrawableStrokeMiterLimit(5));
                image.Draw(new DrawableStrokeOpacity(new Percentage(80)));
                image.Draw(new DrawableStrokeWidth(4));
                image.Draw(new DrawableText(0, 60, "test"));
                image.Draw(new DrawableTextAlignment(TextAlignment.Center));
                image.Draw(new DrawableTextAntialias(true));
                image.Draw(new DrawableTextDecoration(TextDecoration.LineThrough));
                image.Draw(new DrawableTextDirection(TextDirection.RightToLeft));
                image.Draw(new DrawableTextEncoding(Encoding.ASCII));
                image.Draw(new DrawableTextInterlineSpacing(4));
                image.Draw(new DrawableTextInterwordSpacing(6));
                image.Draw(new DrawableTextKerning(2));
                image.Draw(new DrawableTextUnderColor(MagickColors.Yellow));
                image.Draw(new DrawableTranslation(65, 65));
                image.Draw(new DrawableViewbox(0, 0, 100, 100));

                image.Draw(new DrawablePushClipPath("#1"), new DrawablePopClipPath());
                image.Draw(new DrawablePushGraphicContext(), new DrawablePopGraphicContext());
                image.Draw(new DrawablePushPattern("test", 30, 30, 10, 10), new DrawablePopPattern(), new DrawableFillPatternUrl("#test"), new DrawableStrokePatternUrl("#test"));
            }
        }
Esempio n. 60
0
        public MagickImage Draw()
        {
            MainForm.ProgressStart("Rendering background ...");

            // Check which terrain file is used
            string texMpk = string.Format("{0}\\tex{1}.mpk", this.textureZoneDataDirectory, this.textureZoneId);
            string lodMpk = string.Format("{0}\\lod{1}.mpk", this.textureZoneDataDirectory, this.textureZoneId);

            // Get the tile dimension
            double tileWidth    = 512.0;
            string tileTemplate = "";

            MPAK mpak = new MPAK();

            if (File.Exists(texMpk))
            {
                mpak.Load(texMpk);

                if (mpak.Files.Where(f => f.Name.ToLower() == "tex00-00.dds").Count() > 0)
                {
                    tileTemplate += "tex0{0}-0{1}.dds";
                    tileWidth     = 512.0;
                }
            }

            if (string.IsNullOrEmpty(tileTemplate))
            {
                mpak.Load(lodMpk);

                if (mpak.Files.Where(f => f.Name.ToLower() == "lod00-00.dds").Count() > 0)
                {
                    tileTemplate += "lod0{0}-0{1}.dds";
                    tileWidth     = 256.0;
                }
            }

            if (string.IsNullOrEmpty(tileTemplate))
            {
                MainForm.Log(string.Format("Zone {0}: No background textures found!", zoneConfiguration.ZoneId), MainForm.LogLevel.error);
                return(null);
            }

            // original size
            double orginalWidth = tileWidth * 8;
            double resizeFactor = (double)zoneConfiguration.TargetMapSize / (double)orginalWidth; // 0 - 1

            MagickImage map = new MagickImage(Color.Transparent, zoneConfiguration.TargetMapSize, zoneConfiguration.TargetMapSize);

            int lastWidth = 0;
            int x         = 0;

            for (int col = 0; col <= 7; col++)
            {
                int y = 0;
                for (int row = 0; row <= 7; row++)
                {
                    string filename = string.Format(tileTemplate, col, row);

                    using (MagickImage mapTile = new MagickImage(mpak.GetFile(filename).Data))
                    {
                        int newSize = Convert.ToInt32(mapTile.Width * resizeFactor);
                        mapTile.Resize(newSize, newSize);

                        map.Composite(mapTile, x, y, CompositeOperator.SrcOver);

                        // Calculate new y
                        y        += mapTile.Height;
                        lastWidth = mapTile.Height;
                    }
                }

                x += lastWidth;

                int percent = 100 * col / 8;
                MainForm.ProgressUpdate(percent);
            }

            MainForm.ProgressStartMarquee("Merging ...");

            // Remove rounding fails
            map.Trim();

            // Flip if set
            if (this.flipX)
            {
                map.Flop();
            }
            if (this.flipY)
            {
                map.Flip();
            }

            // Sharpen (tested a lot, seems to be the best values)
            map.Sharpen(4, 3);

            MainForm.ProgressReset();

            return(map);
        }