/// <summary> /// Getting the collection of processed images disasembled from the given GIF and reasembled back to new GIF. /// </summary> /// <param name="pngs"></param> private void MagickGif(List <string> pngs) { using (MagickImageCollection collection = new MagickImageCollection()) { for (int i = 0; i < pngs.Count; i++) { collection.Add(pngs[i]); collection[i].AnimationDelay = 10; } // Save gif collection.OptimizePlus(); collection.Write(Directory.GetCurrentDirectory() + @"\NewAnimated.gif"); tempGifs.RemoveRange(0, tempGifs.Count()); } }
public void ShouldReturnNullWhenMeasureErrorsIsFalse() { using (IMagickImageCollection collection = new MagickImageCollection()) { collection.Add(Files.FujiFilmFinePixS1ProJPG); QuantizeSettings settings = new QuantizeSettings { Colors = 1, MeasureErrors = false, }; MagickErrorInfo errorInfo = collection.Quantize(settings); Assert.IsNull(errorInfo); } }
public void Test_OptimizePlus() { using (MagickImageCollection collection = new MagickImageCollection()) { ExceptionAssert.Throws <InvalidOperationException>(delegate() { collection.OptimizePlus(); }); collection.Add(Files.RoseSparkleGIF); collection.Coalesce(); collection.OptimizePlus(); Assert.Inconclusive("Needs implementation."); } }
public void ShouldReturnNullWhenMeasureErrorsIsFalse() { using (var images = new MagickImageCollection()) { images.Add(Files.FujiFilmFinePixS1ProJPG); var settings = new QuantizeSettings { Colors = 1, MeasureErrors = false, }; var errorInfo = images.Quantize(settings); Assert.Null(errorInfo); } }
public void ShouldUseImageBackground() { using (IMagickImageCollection images = new MagickImageCollection()) { var image = new MagickImage(MagickColors.Red, 10, 10); image.Extent(110, 110, Gravity.Center, MagickColors.None); image.BackgroundColor = MagickColors.Moccasin; images.Add(image); using (IMagickImage result = images.Flatten()) { ColorAssert.AreEqual(MagickColors.Moccasin, result, 0, 0); } } }
/// <summary> /// Applies an embroidery effect to each color in an image. The image must have limited number /// of colors or only the top most frequent colors will be used. Each color will get the same /// pattern, but at different rotation angles. /// </summary> /// <param name="input">The image to execute the script on.</param> /// <returns>The resulting image.</returns> public IMagickImage Execute(IMagickImage input) { if (input == null) { throw new ArgumentNullException("input"); } CheckSettings(); using (var image = input.Clone()) { var colors = image.Histogram().OrderByDescending(kv => kv.Value).Select(kv => kv.Key).Take(NumberOfColors).ToArray(); RemapColors(image, colors); using (var pattern = CreatePattern(image.Width * 2, image.Height * 2)) { using (IMagickImage nearBlackWhite = ToNearBlackWhite(image)) { using (var images = new MagickImageCollection()) { double angle = (Pattern == EmbroideryPattern.Linear ? -45 : -90) + Angle; foreach (var color in colors) { bool useBevel = Bevel != 0 && color != colors.First(); using (var croppedPattern = CreateCroppedPattern(image, pattern, angle)) { using (var alpha = ExtractAlpha(image, color)) { var colorImage = CreateColor(alpha, croppedPattern, nearBlackWhite, useBevel); images.Add(colorImage); } } angle += Range / (double)colors.Length; } var result = images.Flatten(); result.Crop(input.Width, input.Height, Gravity.Center); return(result); } } } } }
public string Execute(IProgress <GifWriterProgress> progress = null) { if (!Directory.Exists(InputDir)) { throw new Exception($"Directory \"{InputDir}\" does not exist."); } var files = Directory.EnumerateFiles(InputDir, "*.jpg", SearchOption.TopDirectoryOnly).ToArray(); if (!files.Any()) { throw new Exception($"No files ending in \".jpg\" found in directory \"{InputDir}\""); } using (var collection = new MagickImageCollection()) { _totalProgressSteps = files.Length + 4; var steps = 0; foreach (var file in files) { Report(progress, ++steps, "Add File"); collection.Add(file); collection[0].AnimationDelay = FrameDelay; } QuantizeSettings settings = new QuantizeSettings { Colors = 256 }; Report(progress, ++steps, "Quantize"); collection.Quantize(settings); Report(progress, ++steps, "Optimize"); collection.Optimize(); Report(progress, ++steps, "Create Dir"); Directory.CreateDirectory(OutputDir); var filename = Path.Combine(OutputDir, $"out-{DateTime.UtcNow.ToString("yyyyMMddHHmmssfff")}.gif"); Report(progress, ++steps, "Write File"); collection.Write(filename); return(filename); } }
private void saveAsGifToolStripMenuItem_Click(object sender, EventArgs e) { String savedgif = null; saveFileDialog1.FileName = "animation.gif"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { savedgif = saveFileDialog1.FileName; String[] images = new String[arrayOfImages.Length]; String log = ""; int i = 0; String tmpDir = @"tmp\"; if (Directory.Exists(@"tmp\")) { } else { Directory.CreateDirectory(@"tmp\"); } using (ImageMagick.MagickImageCollection collection = new MagickImageCollection()) { foreach (PictureBox image in arrayOfImages) { Bitmap temp = (Bitmap)image.Image; String name = tmpDir + "img" + i + ".png"; temp.Save(name); images[i] = name; i += 1; } foreach (String s in images) { collection.Add(s); collection.Write(savedgif); log += s; } // MessageBox.Show(log); ImageWindow pos = new ImageWindow(wind, savedgif); } } }
static void AddItem(OSRSItem osrsItem, List <ModItemDataXML> itemDataList, List <ModItemTypeDataXML> itemTypeDataList, List <ItemXML> texturesList, MagickImageCollection imageCollection) { int dupes; if (itemDataList.Exists(e => e.ItemID.Equals(NormalizeItemName(osrsItem.Name), StringComparison.InvariantCultureIgnoreCase))) { dupes = itemDataList.Where(e => e.ItemID.StartsWith(NormalizeItemName(osrsItem.Name) + "_", StringComparison.InvariantCultureIgnoreCase)).Count() + 1; } else { dupes = 0; } string itemid; if (dupes > 0) { itemid = $"{NormalizeItemName(osrsItem.Name)}_{dupes + 1}"; } else { itemid = NormalizeItemName(osrsItem.Name); } if (!imageCached) { var img = new MagickImage(GetItemPathPng(osrsItem.Id)); img.Crop(0, 0, 32, 32); imageCollection.Add(img); texturesList.Add(new ItemXML { ItemID = itemid }); } var itemData = new ModItemDataXML(); var itemTypeData = new ModItemTypeDataXML(); foreach (Rule rule in rules) { if (rule.ShouldTransform(itemid, osrsItem)) { itemData = rule.TransformItemData(itemid, osrsItem, itemData); itemTypeData = rule.TransformItemTypeData(itemid, osrsItem, itemTypeData); } } itemDataList.Add(itemData); itemTypeDataList.Add(itemTypeData); }
public void Build() { string[] imgs = Directory.GetFiles(InputFolder, INPUT_IMGS); // only stitch the source images for now using var images = new MagickImageCollection(); foreach (var i in imgs) { var img = new MagickImage(i); img.Scale(Constants.SYNAPSE_WIDTH, Constants.SYNAPSE_HEIGHT); images.Add(img); } // stitch horizontally as demonstrated in the assignment example using var result = images.AppendHorizontally(); result.Write(OutputFile); }
public void ShouldUseSpecifiedBackground() { using (var images = new MagickImageCollection()) { var image = new MagickImage(MagickColors.Red, 10, 10); image.Extent(110, 110, Gravity.Center, MagickColors.None); image.BackgroundColor = MagickColors.Moccasin; images.Add(image); using (var result = images.Flatten(MagickColors.MistyRose)) { ColorAssert.Equal(MagickColors.MistyRose, result, 0, 0); Assert.Equal(MagickColors.Moccasin, image.BackgroundColor); } } }
public async Task <FileInfo> ConvertAsync(FileInfo fileInfo) { var webpFilePath = Constants.ConverterPath + fileInfo.Name; var gifFilePath = Constants.ConverterPath + fileInfo.Name.Replace( Constants.WebpExtension, Constants.GifExtension); var pngFilePath = Constants.ConverterPath + fileInfo.Name.Replace( Constants.WebpExtension, Constants.PngExtension); try { await Task.Run(() => { // Здесь я промежуточно конвертирую в .png, чтобы создать анимированную .gif, // т.к. Giphy не принимает статичные изображения using (var image = new MagickImage(webpFilePath)) { image.Write(pngFilePath); } using var collection = new MagickImageCollection { pngFilePath }; collection[0].AnimationDelay = 100; collection.Add(pngFilePath); collection[1].AnimationDelay = 100; collection[1].Flop(); collection.Optimize(); collection.Write(gifFilePath); }); var fileForReturnInfo = new FileInfo(fileInfo.Name.Replace(Constants.WebpExtension, Constants.GifExtension)); _logger.LogInformation($"File {fileInfo.Name} Converted Successfully"); return(fileForReturnInfo); } catch (Exception e) { throw new Exception($"File {fileInfo.Name} Converted Failed: {e.Message}"); } }
private static void RemapColors(IMagickImage image, IEnumerable <MagickColor> colors) { using (var images = new MagickImageCollection()) { foreach (var color in colors) { images.Add(new MagickImage(color, 1, 1)); } using (IMagickImage colorMap = images.AppendHorizontally()) { image.Map(colorMap, new QuantizeSettings() { DitherMethod = DitherMethod.No }); } } }
// TODO This library shouldn't be required. private void CreateTexture(MontageSettings montageSettings, string path, IEnumerable <byte[]> textures) { lock (textureExportLock) { using (MagickImageCollection stichedTexture = new MagickImageCollection()) { foreach (byte[] texture in textures) { stichedTexture.Add(new MagickImage(texture)); } using (MagickImage result = stichedTexture.Montage(montageSettings)) { result.Write(path); } } } }
private void AddFrameToCollection(Bitmap frame, MagickImageCollection collection) { using (MemoryStream ms = new MemoryStream()) { frame.Save(ms, ImageFormat.Png); ms.Position = 0; MagickImage mi = new MagickImage(ms, MagickFormat.Png) { AnimationDelay = 10, BackgroundColor = MagickColor.FromRgba(Properties.Settings.Default.TextBackground.R, Properties.Settings.Default.TextBackground.G, Properties.Settings.Default.TextBackground.B, Properties.Settings.Default.TextBackground.A), GifDisposeMethod = GifDisposeMethod.Background, AnimationTicksPerSecond = 200 }; collection.Add(mi); } }
/// <summary> /// Converts PC Oblivion normal map to PS3 variant. /// </summary> /// <param name="path">Path to source normal map.</param> /// <param name="outputPath">Where to save new normal map.</param> /// <returns>True or false if the function was able to convert.</returns> public static bool ConvertToPS3(string path, string outputPath) { if (!DirectDrawSurface.IsValid(path)) { Console.WriteLine("ERROR: Invalid DDS texture file."); return(false); } var normalMap = new MagickImage(path); if (normalMap.IsConvertedToPS3()) { Console.WriteLine("ERROR: Channels already converted."); return(false); } List <IMagickImage <ushort> > channelList = normalMap.Separate().ToList(); var newChannelCollection = new MagickImageCollection(); // Turns blue channel null for later usage, because blue channel is never used channelList[2].MakeNull(); // A8R8G8B8 and DXT3 (both support alpha) will convert to DXT5 if (normalMap.HasAlpha) { newChannelCollection.Add(channelList[3]); // ALPHA newChannelCollection.Add(channelList[1]); // GREEN newChannelCollection.Add(channelList[2]); // NULL newChannelCollection.Add(channelList[0]); // RED } else { newChannelCollection.Add(channelList[2]); // NULL newChannelCollection.Add(channelList[1]); // GREEN newChannelCollection.Add(channelList[0]); // RED } var convertedImage = new MagickImage(newChannelCollection.Combine()) { HasAlpha = normalMap.HasAlpha, Depth = normalMap.Depth }; convertedImage.Write(outputPath, MagickFormat.Dds); return(true); }
public static bool SaveImagesAsGif(IEnumerable <string> FilePaths, string OutPath, int Delay = 100) { Log.Verbose("Turning {0} files into {1}", FilePaths.Count(), OutPath); try { using (MagickImageCollection Collection = new MagickImageCollection()) { foreach (string File in FilePaths) { int Index = Collection.Count(); Collection.Add(File); Collection[Index].AnimationDelay = Delay; } // Optionally reduce colors /*QuantizeSettings settings = new QuantizeSettings(); * settings.Colors = 256; * Collection.Quantize(settings);*/ foreach (MagickImage image in Collection) { image.Resize(640, 0); } // Optionally optimize the images (images should have the same size). Collection.Optimize(); // Save gif Collection.Write(OutPath); Log.Verbose("Saved {0}", OutPath); } } catch (System.Exception Ex) { Log.Warning("SaveAsGif failed: {0}", Ex); return(false); } return(true); }
public void Test_Montage() { using (MagickImageCollection images = new MagickImageCollection()) { for (int i = 0; i < 9; i++) { images.Add(Files.Builtin.Logo); } MontageSettings ms = new MontageSettings(); ms.Geometry = new MagickGeometry(string.Format("{0}x{1}", 200, 200)); ms.TileGeometry = new MagickGeometry(string.Format("{0}x", 2)); using (MagickImage montageResult = images.Montage(ms)) { Assert.IsNotNull(montageResult); Assert.AreEqual(400, montageResult.Width); Assert.AreEqual(1000, montageResult.Height); } } }
public static MagickImage MergeImages(string[] imgs, bool vertically, bool deleteSourceImgs) { MagickImageCollection collection = new MagickImageCollection(); foreach (string img in imgs) { collection.Add(img); if (deleteSourceImgs) { File.Delete(img); } } if (!vertically) { return((MagickImage)collection.AppendHorizontally()); } else { return((MagickImage)collection.AppendVertically()); } }
public void Test_Morph() { using (IMagickImageCollection collection = new MagickImageCollection()) { ExceptionAssert.Throws <InvalidOperationException>(delegate() { collection.Morph(10); }); collection.Add(Files.Builtin.Logo); ExceptionAssert.Throws <InvalidOperationException>(delegate() { collection.Morph(10); }); collection.AddRange(Files.Builtin.Wizard); collection.Morph(4); Assert.AreEqual(6, collection.Count); } }
public void Test_Morph() { using (var collection = new MagickImageCollection()) { Assert.Throws <InvalidOperationException>(() => { collection.Morph(10); }); collection.Add(Files.Builtin.Logo); Assert.Throws <InvalidOperationException>(() => { collection.Morph(10); }); collection.AddRange(Files.Builtin.Wizard); collection.Morph(4); Assert.Equal(6, collection.Count); } }
public static String BuildSquareImg(List <List <AvactorInfo> > imggroup) { String result = String.Empty; if (imggroup == null || !imggroup.Any()) { return(result); } using (MagickImageCollection verticallyImages = new MagickImageCollection()) { foreach (var item in imggroup) { using (MagickImageCollection images = new MagickImageCollection()) { foreach (var hitem in item) { MagickImage first = new MagickImage(hitem.FilePath); first.Resize(hitem.Width, hitem.Heigh); if (hitem.IsResize) { first.BackgroundColor = new MagickColor(Color.Gray); } images.Add(first); } verticallyImages.Add(images.AppendHorizontally()); } } using (IMagickImage vresult = verticallyImages.AppendVertically()) { // Save the result result = Path.Combine(TempFolder, DateTime.Now.ToFileTime() + ".png"); vresult.Write(result); } } return(result); }
private void ExportAnimationGIFItem_Click(object sender, RoutedEventArgs e) { SaveFileDialog save = new SaveFileDialog(); save.Filter = "Animated GIF|*.gif"; if (save.ShowDialog() == true) { int padding = 2; //on each side int animationToExport = Convert.ToInt32(animationIndexUpDown.Value); Animation anim = ActiveBNSA.Animations[animationToExport]; Rectangle boundingBox = anim.CalculateAnimationBoundingBox(); boundingBox.Inflate(padding * 2, padding * 2); using (MagickImageCollection collection = new MagickImageCollection()) { foreach (BNSA_Unpacker.classes.Frame f in anim.Frames) { int animationDelay = Convert.ToInt32(f.FrameDelay * 1.6667); //1/60 in ms; MagickImage img = new MagickImage(DrawSprite(f, boundingBox)); collection.Add(img); collection.Last().AnimationDelay = animationDelay; } // Reduce colors (causes flicker) QuantizeSettings settings = new QuantizeSettings(); settings.Colors = 16; collection.Quantize(settings); collection.Coalesce(); // Optionally optimize the images (images should have the same size). //collection.Optimize(); //causes flicker //doing neither seems to cause both // Save gif collection.Write(save.FileName); } } }
public async Task radar() { var image = PictureService.GetPictureAsync("https://s.w-x.co/staticmaps/wu/wxtype/county_loc/tiw/animate.png").Result; image.Seek(0, SeekOrigin.Begin); MemoryStream outgoingImage = new MemoryStream(); using (var baseImage = new MagickImageCollection(image)) { using (var outputCollection = new MagickImageCollection()) { bool usedBaseOnce = false; baseImage.Coalesce(); foreach (var frame in baseImage) { outputCollection.Add(new MagickImage(frame)); } outputCollection.Write(outgoingImage, MagickFormat.Gif); } } outgoingImage.Seek(0, SeekOrigin.Begin); Context.Channel.SendFileAsync(outgoingImage, "radar.gif"); }
public static String BuildAppendVertically(List <String> imgs) { String filepath = String.Empty; using (MagickImageCollection images = new MagickImageCollection()) { // Add the first image foreach (var item in imgs) { MagickImage second = new MagickImage(item); images.Add(second); } using (IMagickImage result = images.AppendVertically()) { // Save the result filepath = Path.Combine(TempFolder, DateTime.Now.ToFileTime() + "Vertically.png"); result.Write(filepath); } } return(filepath); }
/** * Convert AI, EPS, PDF and PS file to any image file format */ public void ConvertToImage(string dest, MagickFormat format = MagickFormat.Jpg) { using (var images = new MagickImageCollection()) { foreach (var file in _files) { var image = new MagickImage(file) { Format = format, Depth = 8, }; images.Add(image); } foreach (var image in images) { var file = Path.GetFileNameWithoutExtension(new FileInfo(image.FileName).Name); image.Write(Path.Combine(dest, $"{file}.{format.ImageExt()}")); } images.Dispose(); } }
public void Create(List <Image> images, int delay, string folder, string path) { using (MagickImageCollection collection = new MagickImageCollection()) { for (var i = 0; i < images.Count; i++) { Console.SetCursorPosition(0, 1); Console.Write(new string(' ', Console.WindowWidth)); Console.SetCursorPosition(0, 1); Console.Write("Saving Frame " + i + " of " + images.Count); var img = new MagickImage((Bitmap)images[i]); collection.Add(img); collection[i].AnimationDelay = delay; } path = SanitizePath(path); try { collection.Optimize(); collection.Write(folder + path + ".gif"); } catch (Exception err) { } } }
public void MakeGifFromImages(string outputPath, List <Bitmap> images, List <int> animationDelays, int animationIterations = 0) { if (images.Count != animationDelays.Count) { throw new ArgumentException($"{nameof(images)} count is not equal to {nameof(animationDelays)} count."); } using (MagickImageCollection imageCollection = new MagickImageCollection()) { QuantizeSettings quantizeSettings = new QuantizeSettings(); quantizeSettings.Colors = 256; quantizeSettings.DitherMethod = DitherMethod.No; for (int i = 0; i < images.Count; i++) { OnProgress?.Invoke(i / (float)images.Count); imageCollection.Add(new MagickImage(images[i])); Console.Write($"{animationDelays[i]} "); imageCollection[imageCollection.Count - 1].AnimationDelay = animationDelays[i]; imageCollection[imageCollection.Count - 1].AnimationIterations = animationIterations; imageCollection[imageCollection.Count - 1].Format = MagickFormat.Gif; imageCollection[imageCollection.Count - 1].Quantize(quantizeSettings); } //imageCollection.Quantize(quantizeSettings); reduces gif size but reduces overall colors //imageCollection.Optimize(); does nothing imageCollection.Write(outputPath); //ImageMagick.ImageOptimizers.GifOptimizer gifOptimizer = new ImageMagick.ImageOptimizers.GifOptimizer(); does nothing //gifOptimizer.LosslessCompress(outputPath); } }
public void GenerateProfileCard() { using (MagickImageCollection profileCard = new MagickImageCollection()) { ProfileData profile = GetProfileData(); SkinData skin = GetSkinData(); MagickImage background = new MagickImage(skin.Background); profile.Picture.Resize(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(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("profileCard.png"); } } }
private MagickImageCollection CreateFrameCollection(IndexViewModel model) { string webRootPath = _hostingEnvironment.WebRootPath; MagickImageCollection collection = new MagickImageCollection(); foreach (var file in model.TheImages) { var image = new MagickImage(file.OpenReadStream()); image.AnimationDelay = model.Delay; //delay is 1000ms/1sec new Drawables() // Draw text on the image .FontPointSize(model.TextSize) .Font("Arial") .StrokeColor(new MagickColor("yellow")) .FillColor(MagickColors.Orange) .TextAlignment(TextAlignment.Left) .Text(20, 20 + model.TextSize, "GIMMEGIF") //Draw text on the image .FontPointSize(model.TextSize) .Font("Calibri") .StrokeColor(MagickColors.Black) .FillColor(MagickColors.White) .TextAlignment(TextAlignment.Right) .Text(image.Width - 20, image.Height - 20, model.Info) .Draw(image); collection.Add(image); } // Optionally reduce colors QuantizeSettings settings = new QuantizeSettings(); settings.Colors = 256; collection.Quantize(settings); collection.Optimize(); return(collection); }
public void Test_CopyTo() { using (MagickImageCollection collection = new MagickImageCollection()) { collection.Add(new MagickImage(Files.SnakewarePNG)); collection.Add(new MagickImage(Files.RoseSparkleGIF)); MagickImage[] images = new MagickImage[collection.Count]; collection.CopyTo(images, 0); Assert.AreEqual(collection[0], images[0]); Assert.AreNotEqual(collection[0], images[1]); collection.CopyTo(images, 1); Assert.AreEqual(collection[0], images[0]); Assert.AreEqual(collection[0], images[1]); images = new MagickImage[collection.Count + 1]; collection.CopyTo(images, 0); images = new MagickImage[1]; collection.CopyTo(images, 0); ExceptionAssert.Throws<ArgumentNullException>(delegate() { collection.CopyTo(null, -1); }); ExceptionAssert.Throws<ArgumentOutOfRangeException>(delegate() { collection.CopyTo(images, -1); }); } }
public void Test_Dispose() { MagickImage image = new MagickImage(Color.Red, 10, 10); MagickImageCollection collection = new MagickImageCollection(); collection.Add(image); collection.Dispose(); Assert.AreEqual(0, collection.Count); image.Wave(); }