Beispiel #1
0
        public static void GenerateImage(
            string imagePath = "test.png")
        {
            MagickReadSettings settings = new MagickReadSettings();

            // Set define that tells the jpeg coder that the output image will be 32x32
            settings.SetDefine(MagickFormat.Png, "size", "250x450");

            /// if (!File.Exists(imagePath))
            //     File.Create(imagePath);

            using (var magick =
                       new MagickImage())
            {
                magick.Settings.Font              = @"C:\Windows\Fonts\Another_.ttf";
                magick.Settings.FontPointsize     = 72;
                magick.Settings.BackgroundColor.A = 0;

                //var gravity = new DrawableGravity(Gravity.South);

                // magick.Draw(drawFont, size, stroke, drawableText);

                magick.Read("label:This is a test game name");

                //magick.Annotate("tetstst",Gravity.Center);

                //var metrics = magick.FontTypeMetrics("Test text");

                // magick.Border(2);
                //magick.Colorize(new MagickColor(System.Drawing.Color.Aqua), new Percentage(100));

                magick.Write("neh.png");
            }
        }
Beispiel #2
0
        public static MagickImage EllipticalGradient(MagickColor startColor, MagickColor endColor, int width, int height)
        {
            var start = startColor.ToString();
            var end   = endColor.ToString();

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

            readSettings.SetDefine("gradient:extent", "ellipse");
            return(new MagickImage($"radial-gradient:{start}-{end}", readSettings));
        }
Beispiel #3
0
        public static MagickImage Gradient(MagickColor startColor, MagickColor endColor, int width, int height, double angle = 0)
        {
            var start = startColor.ToString();
            var end   = endColor.ToString();

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

            readSettings.SetDefine("gradient:angle", angle.ToString());
            return(new MagickImage($"gradient:{start}-{end}", readSettings));
        }
        /// <summary>
        /// Utility method to make a thumbnail using the defined settings including format, width, height
        /// </summary>
        /// <param name="originalImage">A reference to the original image from which the thumbnail is being created, in MagickImage format</param>
        /// <param name="format">The format of the resulting thumbnail (defaults to jpeg)</param>
        /// <param name="width">The width of the resulting thumbnail image</param>
        /// <param name="height">The height of the resulting thumbnail image</param>
        /// <returns>A byte array of the new thumbnail image</returns>
        protected byte[] GetThumbnail(MagickImage originalImage, MagickFormat format, int width, int height)
        {
            MagickImage        smallThumbnailImage = null;
            MagickReadSettings settings            = new MagickReadSettings();

            settings.SetDefine(format, "size", width + "x" + height);
            using (MagickImage newImage = originalImage)
            {
                newImage.Format = format;
                newImage.Strip();
                newImage.Thumbnail(width, height);
                smallThumbnailImage = new MagickImage(newImage);
            }
            return(smallThumbnailImage.ToByteArray());
        }
Beispiel #5
0
        public override void Apply(MagickImage image)
        {
            var start = Start.ToString();
            var end   = End.ToString();

            var readSettings = new MagickReadSettings {
                Width  = image.Width,
                Height = image.Height
            };

            readSettings.SetDefine("gradient:angle", Angle.ToString());
            var gradient = new MagickImage($"gradient:{start}-{end}", readSettings);

            image.Composite(gradient, CompositeOperator.SrcOver);
        }
Beispiel #6
0
        public static void DefinesThatNeedToBeSetBeforeReadingAnImage()
        {
            MagickReadSettings settings = new MagickReadSettings();

            // Set define that tells the jpeg coder that the output image will be 32x32
            settings.SetDefine(MagickFormat.Jpeg, "size", "32x32");

            // Read image from file
            using (MagickImage image = new MagickImage(SampleFiles.SnakewareJpg))
            {
                // Create thumnail that is 32 pixels wide and 32 pixels high
                image.Thumbnail(32, 32);
                // Save image as tiff
                image.Write(SampleFiles.OutputDirectory + "Snakeware.tiff");
            }
        }
Beispiel #7
0
        public static void GenerateLabel(string text     = "Super horse Bros.",
                                         string fontName = @"C:\Windows\Fonts\comicbd.ttf")
        {
            MagickReadSettings settings = new MagickReadSettings();

            settings.SetDefine(MagickFormat.Png, "size", "250x450");

            using (var magick =
                       new MagickImage())
            {
                //magick.Settings.Page = new MagickGeometry(400, 175);
                // magick.RePage();

                magick.Draw(new DrawableRectangle
                                (new System.Drawing.Rectangle()
                {
                    Width = 400, Height = 175
                }));
                magick.Colorize(new MagickColor(System.Drawing.Color.Aqua), new Percentage(100));
                // magick.Settings.FillColor = new MagickColor(System.Drawing.Color.DarkCyan);
                //magick.Settings.Font = fontName;
                // magick.Settings.FontPointsize = 72;

                // magick.Settings.StrokeWidth = 2;
                // magick.Settings.StrokeColor = new MagickColor(System.Drawing.Color.Chocolate);

                // magick.Settings.BackgroundColor.A = 0;
                //  magick.Settings.TextGravity = Gravity.Center;
                //  magick.Settings.StrokeAntiAlias = true;


                var clone = magick.Clone();
                // clone.Shadow(0,0,1,new Percentage(100),new MagickColor(System.Drawing.Color.Green));

                clone.RePage();
                clone.Trim();
                // var clone2 = clone.Clone();
                //clone2.Trim();


                clone.Write("preview.png");
            }
        }
Beispiel #8
0
        static public void DrawEnhancedText(
            this IMagickImage <byte> image, string text, Gravity gravity, int x, int y, MagickColor foreground,
            DrawableFont font, double fontPointSize, int maxWidth, bool ellipsize = true)
        {
            var settings = new MagickReadSettings()
            {
                BackgroundColor = MagickColors.Transparent,
                Width           = maxWidth,
                TextGravity     = gravity,
                TextAntiAlias   = false
            };

            //settings.SetDefine("pango:wrap", "char");
            if (ellipsize)
            {
                settings.SetDefine("pango:ellipsize", "end");
            }

            // Escape text for use in pango markup language
            // For some reason the text must be excaped twice otherwise it will not work
            text = SecurityElement.Escape(SecurityElement.Escape(text));

            using var textArea = new MagickImage($@"pango:<span
                size=""{fontPointSize * 1000}""
                font_family=""{ font.Family }""
                stretch=""{font.Stretch}""
                style=""{(font.Style == FontStyleType.Any ? FontStyleType.Normal : font.Style)}""
                weight=""{font.Weight}""
                foreground=""white""
                >{text}</span>", settings);

            using var colored = new MagickImage(foreground, textArea.Width, textArea.Height);
            colored.Alpha(AlphaOption.On);
            colored.Composite(textArea, CompositeOperator.Multiply, Channels.Alpha);

            image.Composite(colored, x, y, CompositeOperator.Over);
        }
Beispiel #9
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="useEmbeddedThumbnail">Return the embedded thumbnail if required size was not found.</param>
        /// <param name="useRawThumbnail">Return the RAW embedded thumbnail if found.</param>
        /// <param name="forceLoadFirstPage">Only load first page of the image</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 useEmbeddedThumbnail = false,
            bool useRawThumbnail      = true,
            bool forceLoadFirstPage   = 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,
                OutputColor           = DngOutputColor.AdobeRGB,
                ReadThumbnail         = 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 ".FAX":
                // 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;


            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 && useEmbeddedThumbnail)
                {
                    // Fetch the embedded thumbnail
                    using 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)
                    {
                        var imgColor = Helpers.GetColorProfile(colorProfileName);

                        if (imgColor != null)
                        {
                            imgM.TransformColorSpace(
                                //set default color profile to sRGB
                                imgColorProfile ?? ColorProfile.SRGB,
                                imgColor);
                        }
                    }
                }

                return(profile, imgColorProfile);
            }

            void ReadWithMagickImage()
            {
                var checkRotation = ext != ".HEIC";

                using var imgColl = new MagickImageCollection();

                // 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);

                    imgColl.Ping(allBytes, settings);
                }
                else
                {
                    imgColl.Ping(filename, settings);
                }


                if (imgColl.Count > 1 && forceLoadFirstPage is false)
                {
                    imgColl.Read(filename, settings);
                    foreach (var imgPageM in imgColl)
                    {
                        (exif, colorProfile) = PreprocesMagickImage((MagickImage)imgPageM, checkRotation);
                    }

                    bitmap = imgColl.ToBitmap();
                    return;
                }


                using var imgM = new MagickImage();
                if (useRawThumbnail is true)
                {
                    var profile = imgColl[0].GetProfile("dng:thumbnail");

                    try {
                        // try to get thumbnail
                        imgM.Read(profile?.GetData(), settings);
                    }
                    catch {
                        imgM.Read(filename, settings);
                    }
                }
                else
                {
                    imgM.Read(filename, settings);
                }


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


                imgM.Quality         = quality;
                (exif, colorProfile) = PreprocesMagickImage(imgM, checkRotation);

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

            #endregion


            return(new ImgData()
            {
                Image = bitmap,
                Exif = exif,
                ColorProfile = colorProfile,
            });
        }
Beispiel #10
0
        public static void SphereSummary(string directory)
        {
            //Get all illuminated sphere images
            List <string> images = GetFilesWith(directory, "RZ*.tif");

            if (images.Count == 0)
            {
                MessageBox.Show($"No illuminted sphere images found in {directory}.", "No Images Found", MessageBoxButton.OK, MessageBoxImage.Warning); return;
            }
            //Get z-values from file names
            List <string> zValues = new List <string>();

            foreach (string image in images)
            {
                string zValue = System.IO.Path.GetFileName(image).Split("Y")[0];
                if (!zValues.Contains(zValue))
                {
                    zValues.Add(zValue);
                }
            }

            //MagickReadSettings to ignore null tag 37373 in tif images generated during rectification.
            var settings = new MagickReadSettings();

            settings.SetDefine("tiff:ignore-tags", "37373,37374");

            //Create summary folder
            string summaryFolder = $@"{System.IO.Path.GetDirectoryName(images[0])}\Summary";

            Directory.CreateDirectory(summaryFolder);

            //Init progress bar
            var pBar = new HelixTroubleshootingWPF.ProgressBar();

            pBar.Visibility = Visibility.Visible;
            pBar.Show();
            pBar.mainProgressBar.Visibility = Visibility.Visible;
            float progressTick = 100f / (float)zValues.Count;
            //Loop through zValues and combine all images that match
            int imgCount = 1;

            foreach (string zValue in zValues)
            {
                pBar.label.Dispatcher.Invoke(() => pBar.label.Text = $"Creating image ({imgCount}/{zValues.Count}): {zValue}.tif", DispatcherPriority.Background);
                pBar.label.Text = $"Creating image ({imgCount}/{zValues.Count}): {zValue}.tif";
                MagickImage summaryImage;
                //Pick first img to initialize summaryImg
                foreach (string image in images)
                {
                    if (image.Contains(zValue))
                    {
                        //Loop to add each image to summary via lighten operation
                        summaryImage = new MagickImage(image, settings);
                        foreach (string image2 in images)
                        {
                            //if (image2.Contains(zValue))
                            if (System.IO.Path.GetFileName(image2).Split("Y")[0] == zValue)
                            {
                                MagickImage magickImage2 = new MagickImage(image2, settings);
                                summaryImage.Composite(magickImage2, CompositeOperator.Lighten);
                                magickImage2.Dispose();
                            }
                        }
                        summaryImage.Write($@"{summaryFolder}\{zValue}.tif");
                        summaryImage.Dispose();
                        break;
                    }
                }
                //Tick progress
                pBar.mainProgressBar.Dispatcher.Invoke(() => pBar.mainProgressBar.Value += progressTick, DispatcherPriority.Background);
                imgCount++;
            }
            pBar.mainProgressBar.Value = 100;
            MessageBox.Show("Summary image processing complete", "Done", MessageBoxButton.OK, MessageBoxImage.Information);
            pBar.Visibility = Visibility.Hidden;
            pBar.Close();
        }
 //Constructors
 public HelixImage()
 {
     settings.SetDefine("tiff:ignore-tags", "37373,37374");
 }
Beispiel #12
0
        private void AddEmote(string emoteName, Library.ILibraryInternal library, string url)
        {
            if (loadedEmotes.Contains(emoteName))
            {
                return;
            }

            string encodedEmoteName = Utility.EncodeStringForFileName(emoteName);

            byte[] data = null;

            if (Library.FolderExists(TWITCH_CACHE_PATH))
            {
                var qualifiedFilename = string.Format("{0}{1}", TWITCH_CACHE_PATH, encodedEmoteName);
                if (Library.FileExists(qualifiedFilename))
                {
                    data = File.ReadAllBytes(Library.GetFilename(qualifiedFilename));
                }
            }
            MemoryStream imageStream = new MemoryStream();

            if (data == null)
            {
                data = client.DownloadData(url);
                var folder = Library.GetFolderName(TWITCH_CACHE_PATH);

                MagickReadSettings settings = new MagickReadSettings();
                settings.ColorSpace = ColorSpace.sRGB;
                settings.SetDefine(MagickFormat.Png, "format", "png8");

                MagickImageInfo mImageInfo = new MagickImageInfo(data);

                if (mImageInfo.Format != MagickFormat.Gif)
                {
                    using (MagickImage mImage = new MagickImage(data, settings))
                    {
                        mImage.Write(imageStream);
                        imageStream.Position = 0;
                    }
                }
                else
                {
                    using (MagickImageCollection mImages = new MagickImageCollection(data, settings))
                    {
                        //Background is PepePls
                        //SourPls is None
                        var width  = mImages.Max(x => x.Page.Width);
                        var height = mImages.Max(y => y.Page.Height);
                        FramePacker.FrameDisposal frameDisposal;

                        switch (mImages[0].GifDisposeMethod)
                        {
                        case GifDisposeMethod.None:
                            frameDisposal = FramePacker.FrameDisposal.Composite;
                            break;

                        case GifDisposeMethod.Undefined:
                        case GifDisposeMethod.Background:
                        case GifDisposeMethod.Previous:
                        default:
                            frameDisposal = FramePacker.FrameDisposal.Replace;
                            break;
                        }

                        var packedImage = FramePacker.PackListOfImagesToMemStream(
                            mImages.Select(imageFrame => new FramePacker.Frame
                        {
                            Image  = imageFrame.ToBitmap(ImageFormat.Png),
                            X      = imageFrame.Page.X,
                            Y      = imageFrame.Page.Y,
                            Width  = imageFrame.BaseWidth,
                            Height = imageFrame.BaseHeight
                        }).ToArray(),
                            imageStream,
                            width,
                            height,
                            frameDisposal
                            );

                        packedImage.FPS = 1 / ((float)mImages.Select(x => x.AnimationDelay).Average() / 100.0f);

                        JsonWriter.Save(packedImage, string.Format("{0}{1}", TWITCH_CACHE_PATH, encodedEmoteName), true);
                        //mImages[0].Write(imageStream);
                        imageStream.Position = 0;
                    }
                }

                File.WriteAllBytes(string.Format("{0}/{1}", folder, encodedEmoteName), data = imageStream.ToArray());
            }

            library.AddTexture(string.Format("twitch//{0}", emoteName), imageStream);
            loadedEmotes.Add(emoteName);
        }