/// <summary> /// Returns BitmapSource at specified quality and pixel size /// </summary> /// <param name="file"></param> /// <param name="quality"></param> /// <param name="size"></param> /// <returns></returns> private static BitmapSource GetMagickImageThumb(string file, byte quality = 100, short size = 500) { BitmapSource pic; using MagickImage magick = new MagickImage { Quality = quality, ColorSpace = ColorSpace.Transparent }; try { magick.Read(file); magick.AdaptiveResize(size, size); } #if DEBUG catch (MagickException e) { Trace.WriteLine("GetMagickImage returned " + file + " null, \n" + e.Message); return(null); } #else catch (MagickException) { return(null); } #endif pic = magick.ToBitmapSource(); pic.Freeze(); return(pic); }
public static void Resize(string path, int width = 500, int height = 500) { using (MagickImage image = new MagickImage(path)) { image.AdaptiveResize(width, height); image.Write(path); } }
public void ShouldNotEnlargeTheImage() { using (IMagickImage image = new MagickImage(MagickColors.Black, 512, 1)) { image.AdaptiveResize(512, 512); Assert.AreEqual(1, image.Height); } }
private static void PNG2Texture(string input_name, string output_name) { byte[] dstTex = File.ReadAllBytes(output_name); PVR texture = new PVR(dstTex); if (texture.isTexture == false) { return; } ImageMagick.MagickImage im = new MagickImage(input_name); if ((im.Width != texture.header.Width) || im.Height != texture.header.Height) { Console.WriteLine("Error: texture is {0} x {1} ,but png bitmap is {2} x {3}.Exit.", texture.header.Width, texture.header.Height, im.Width, im.Height); return; } byte[] sourceData = im.GetPixels().ToByteArray(0, 0, im.Width, im.Height, "RGBA"); byte[] outputData; Console.WriteLine("Reading:{0}\n Width:{1}\n Height:{2}\n Format:{3}\n", input_name, im.Width, im.Height, texture.header.Format.ToString()); Console.WriteLine("Converting..."); outputData = texture.SetPixelBytes(sourceData); if (texture.header.MipMapCount > 1) { Console.WriteLine("Generating Mipmap..."); for (var m = 0; m <= 3; m++) { im.AdaptiveResize(im.Width / 2, im.Height / 2); Console.WriteLine("Generating ...{0}x{1}", im.Width, im.Height); sourceData = im.GetPixels().ToByteArray(0, 0, im.Width, im.Height, "RGBA"); byte[] dst; dst = texture.SetPixelBytes(sourceData); outputData = outputData.Concat(dst).ToArray(); } } if (outputData != null) { if (File.Exists(output_name)) { Console.WriteLine("Writing...{0}", output_name); using (FileStream fs = File.Open(output_name, FileMode.Open, FileAccess.ReadWrite)) { fs.Seek(texture.DataPosition, SeekOrigin.Begin); fs.Write(outputData, 0, outputData.Length); fs.Flush(); } Console.WriteLine("File Created..."); } else { Console.WriteLine("Error: file {0} not found", output_name); } } }
static void Main(string[] args) { if (Directory.Exists(rootDirectory + "\\imagecache")) { Directory.Delete(rootDirectory + "\\imagecache", true); } Regex pattern = new Regex("\\\\images\\\\"); foreach (string d in Directory.EnumerateDirectories($"{ rootDirectory }\\images\\", "*", SearchOption.TopDirectoryOnly)) { var jpg = Directory.EnumerateFiles(d, "*.jpg", SearchOption.AllDirectories).ToList(); var gif = Directory.EnumerateFiles(d, "*.gif", SearchOption.AllDirectories).ToList(); var png = Directory.EnumerateFiles(d, "*.png", SearchOption.AllDirectories).ToList(); var allImg = jpg.Union(gif).Union(png); foreach (string f in allImg) { string newpath = pattern.Replace(Path.GetDirectoryName(f), "\\imagecache\\", 1); string newfile = Path.GetFileNameWithoutExtension(f); Directory.CreateDirectory(newpath); using (MagickImage newImg = new MagickImage(f)) { newImg.Format = MagickFormat.Jpeg; decimal shrink = 1m; if (newImg.Width > 900) { shrink = 900m / Convert.ToDecimal(newImg.Width); } if (newImg.Height > 900) { shrink = Math.Min(900m / Convert.ToDecimal(newImg.Height), shrink); } newImg.Resize(Convert.ToInt32(newImg.Width * shrink), Convert.ToInt32(newImg.Height * shrink)); newImg.Write($"{newpath}\\{newfile}-w900.jpg"); if (newImg.Width > 100) { shrink = 100m / Convert.ToDecimal(newImg.Width); } if (newImg.Height > 100) { shrink = Math.Min(100m / Convert.ToDecimal(newImg.Height), shrink); } newImg.AdaptiveResize(Convert.ToInt32(newImg.Width * shrink), Convert.ToInt32(newImg.Height * shrink)); newImg.Write($"{newpath}\\{newfile}-w100.jpg"); } } } }
public void ShouldResizeTheImage() { using (IMagickImage image = new MagickImage(Files.MagickNETIconPNG)) { image.AdaptiveResize(100, 80); Assert.AreEqual(80, image.Width); Assert.AreEqual(80, image.Height); ColorAssert.AreEqual(new MagickColor("#347bbd"), image, 23, 42); ColorAssert.AreEqual(new MagickColor("#a8dff8"), image, 42, 42); } }
public byte[] OptimizeThumbnail(byte[] photo) { using (var image = new MagickImage(photo)) { image.Format = MagickFormat.Pjpeg; SetExifProfile(image); image.AdaptiveResize(AppSettings.ImageSizes.Thumb.Width, AppSettings.ImageSizes.Thumb.Height); return(image.ToByteArray()); } }
public void ShouldEnlargeTheImageWhenAspectRatioIsIgnored() { using (IMagickImage image = new MagickImage(MagickColors.Black, 512, 1)) { var geometry = new MagickGeometry(512, 512) { IgnoreAspectRatio = true, }; image.AdaptiveResize(geometry); Assert.AreEqual(512, image.Height); } }
public byte[] OptimizeImage(byte[] photo) { using (var image = new MagickImage(photo)) { // Set the format and write to a stream so ImageMagick won't detect the file type. // set image to progressive image.Format = MagickFormat.Pjpeg; SetExifProfile(image); image.AdaptiveResize(AppSettings.ImageSizes.Main.Width, AppSettings.ImageSizes.Main.Height); return(image.ToByteArray()); } }
static void Main(string[] args) { using (var image = new MagickImage(@"https://github.com/recurser/exif-orientation-examples/blob/master/Landscape_2.jpg?raw=true")) { // set default thumbnail to recommended size of 100px by 100px var thumbnailSize = 100; var resize = new MagickGeometry(); MagickGeometry crop = null; if (image.Height == image.Width) { // if aspect ratio is 1:1 just scale down to 100px resize.Width = thumbnailSize; } else { // resize to shorter dimension to 100px and then crop equal amounts off other dimension crop = new MagickGeometry(); if (image.Height < image.Width) { resize.Height = thumbnailSize; var resizedWidth = Convert.ToInt32((double)resize.Height / image.Height * image.Width); crop.Width = thumbnailSize; crop.X = (resizedWidth - thumbnailSize) / 2; } if (image.Width < image.Height) { resize.Width = thumbnailSize; var resizedHeight = Convert.ToInt32((double)resize.Width / image.Width * image.Height); crop.Height = thumbnailSize; crop.Y = (resizedHeight - thumbnailSize) / 2; } } // apply transformations image.AdaptiveResize(resize); if (crop != null) { image.Crop(crop); } // auto orient using exif data image.AutoOrient(); // make request using info from thumbnail_upload_request with buffer } }
public File GetAtanetPicture(IUnitOfWork unitOfWork) { using (var client = new WebClient()) { var url = this.GetPictureUrl(); var data = client.DownloadData(url); var fileName = System.IO.Path.GetFileName(url); using (var image = new MagickImage(data)) { image.Format = MagickFormat.Jpeg; var geometry = new MagickGeometry($"{ImageSize}x"); geometry.IgnoreAspectRatio = true; image.AdaptiveResize(geometry); image.Extent(ImageSize, ImageSize, Gravity.Center, MagickColor.FromRgb(255, 255, 255)); data = image.ToByteArray(); } return(this.fileCreationService.CreateImageFile(unitOfWork, data, fileName)); } }
private string CompresingImage(byte[] inputImage, int size, int height) { int _size = size; int _height = height; const int quality = 40; string outputImage = ""; if (inputImage == null) { return(outputImage); } using (var image = new MagickImage(inputImage)) { image.AdaptiveResize(_size, _height); image.Strip(); image.Quality = quality; outputImage = image.ToBase64(); } return(outputImage); }
private static void PNG2TEX(string input, string output, string resSPath = "./") { byte[] dstTex2D = File.ReadAllBytes(output); Texture2D texture; try { texture = new Texture2D(dstTex2D); if (!texture.isTexture2D) { return; } if (texture.format == TextureFormat.Alpha8 || texture.format == TextureFormat.ARGB4444 || texture.format == TextureFormat.RGBA4444 || texture.format == TextureFormat.RGBA32 || texture.format == TextureFormat.ARGB32 || texture.format == TextureFormat.RGB24 || texture.format == TextureFormat.RGB565 || texture.format == TextureFormat.ETC_RGB4 || texture.format == TextureFormat.ETC2_RGB || texture.format == TextureFormat.ETC2_RGBA8 || texture.format == TextureFormat.DXT5 || texture.format == TextureFormat.DXT1 || texture.format == TextureFormat.ASTC_RGBA_4x4 || texture.format == TextureFormat.ASTC_RGB_4x4) { ImageMagick.MagickImage im = new MagickImage(input); if ((im.Width != texture.width) || im.Height != texture.height) { //display error to user Console.WriteLine("Error: texture is {0} x {1} , but png bitmap is {2} x {3}.Exit.", texture.width, texture.height, im.Width, im.Height); return; } im.Flip(); byte[] sourceData = im.GetPixels().ToByteArray(0, 0, im.Width, im.Height, "RGBA"); byte[] outputData; Console.WriteLine("Reading:{0}\n Width:{1}\n Height:{2}\n Format:{3}\n", input, im.Width, im.Height, texture.format.ToString()); Console.WriteLine("Converting..."); TextureConverter.CompressTexture(texture.format, im.Width, im.Height, sourceData, out outputData); if (texture.bMipmap && texture.mipmapCount >= 3) { Console.WriteLine("Generating Mipmap..."); for (var m = 0; m <= 3; m++) { im.AdaptiveResize(im.Width / 2, im.Height / 2); Console.WriteLine("Generating ...{0}x{1}", im.Width, im.Height); sourceData = im.GetPixels().ToByteArray(0, 0, im.Width, im.Height, "RGBA"); byte[] dst; TextureConverter.CompressTexture(texture.format, im.Width, im.Height, sourceData, out dst); outputData = outputData.Concat(dst).ToArray(); } } if (outputData != null) { if ((outputData.Length > texture.textureSize)) { Console.WriteLine("Error: generated data size {0}> original texture size {1}. Exit.", outputData.Length, texture.textureSize); } if (texture.bHasResSData == true) { output = string.Format("{0}/{1}", resSPath, texture.resSName); } if (File.Exists(output)) { Console.WriteLine("Writing...{0}", output); using (FileStream fs = File.Open(output, FileMode.Open, FileAccess.ReadWrite)) { fs.Seek(texture.dataPos, SeekOrigin.Begin); fs.Write(outputData, 0, outputData.Length); fs.Flush(); } Console.WriteLine("File Created..."); } else { Console.WriteLine("Error: file {0} not found", output); } } else { Console.WriteLine("Error: generated data size {0}> original texture size {1}. Exit.", outputData.Length, texture.textureSize); } } } catch (Exception ex) { Console.WriteLine("Error:Not A valid Texture: {0}", ex.ToString()); } }
async Task DoImageMagickCommandForStillImage(CommandContext ctx, byte[] buffer, ImageEditMode mode) { MagickImage image; try { image = new MagickImage(buffer); } catch (MagickMissingDelegateErrorException) { await ctx.RespondAsync("Image format not recognised."); return; } int originalWidth = image.Width, originalHeight = image.Height; if (originalHeight * originalWidth > 2250000) { await ctx.RespondAsync($"Image exceeds maximum size of 2250000 pixels (Actual size: {originalHeight * originalWidth})"); return; } // Do magic double exceed = buffer.Length / 8388608d; double rescale = 1f; if (exceed > 1.0) { rescale = 1.0 / Math.Sqrt(exceed); } if (rescale < 1f) { if (rescale < 0.5f) { image.AdaptiveResize((int)(image.Width * rescale), (int)(image.Height * rescale)); } else { image.Resize((int)(image.Width * rescale), (int)(image.Height * rescale)); } } DoMagic(mode, image, originalWidth, originalHeight); using (Stream stream = new MemoryStream()) { if (mode == ImageEditMode.JPEG || mode == ImageEditMode.MoreJPEG || mode == ImageEditMode.MostJPEG) { image.Write(stream, MagickFormat.Jpeg); } else { image.Write(stream); } stream.Seek(0, SeekOrigin.Begin); if (mode == ImageEditMode.JPEG || mode == ImageEditMode.MoreJPEG || mode == ImageEditMode.MostJPEG) { await ctx.RespondWithFileAsync(stream, "magic.jpeg"); } else { await ctx.RespondWithFileAsync(stream, "magic.png"); } } }
public Image CreateCompleteMap(Descr_Strat ds, Descr_Region dr, SMFactions smf) { MagickImage regionMap = new MagickImage(dr.FilePathRegions); //use region map to map out regions MagickImage fullFactionMap = new MagickImage(radarMapLocation); // use radar map as a base var mag = new MagickGeometry(fullFactionMap.Width, fullFactionMap.Height); mag.FillArea = true; mag.IgnoreAspectRatio = true; regionMap.Alpha(AlphaOption.Remove); regionMap.AdaptiveResize(mag); var rpixels = regionMap.GetPixels(); foreach (Faction f in ds.factions) // loop through faction { var fpixels = fullFactionMap.GetPixels(); //set up both maps MagickImage factionMap = new MagickImage(radarMapLocation); factionMap.Alpha(AlphaOption.Remove); factionMap.AdaptiveResize(mag); using (IPixelCollection fmPixels = factionMap.GetPixels()) { foreach (Settlement s in f.settlements) //loop through settlements to get the regions { int[] regColour = dr.GetRGBValue(s.region); //get the colour of a region MagickColor regCol = MagickColor.FromRgb((byte)regColour[0], (byte)regColour[1], (byte)regColour[2]); Color facCol1 = smf.GetFactionColour(f.name, 0); //get the faction colour primary Color facCol2 = smf.GetFactionColour(f.name, 1); // secondary colour MagickColor priCol = MagickColor.FromRgb(facCol1.R, facCol1.G, facCol1.B); //convert the colours to magickcolour MagickColor secCol = MagickColor.FromRgb(facCol2.R, facCol2.G, facCol2.B); int channelsCount = fmPixels.Channels; for (int y = 0; y < factionMap.Height; y++) { List <ushort[]> regVert = new List <ushort[]>(); //create lists to store each pixel along the width of the image List <ushort[]> facVert = new List <ushort[]>(); if (y - 1 >= 0) { regVert.Add(rpixels.GetArea(0, y - 1, regionMap.Width, 1)); // get string of pixels across the image at current y value facVert.Add(fmPixels.GetArea(0, y - 1, factionMap.Width, 1)); } regVert.Add(rpixels.GetArea(0, y, regionMap.Width, 1)); facVert.Add(fmPixels.GetArea(0, y, factionMap.Width, 1)); if (y + 1 < regionMap.Height) { facVert.Add(fmPixels.GetArea(0, y + 1, factionMap.Width, 1)); regVert.Add(rpixels.GetArea(0, y + 1, regionMap.Width, 1)); } int i = 0; if (regVert.Count == 2) { i = 0; } else { i = 1; } for (int x = 0; x < regVert[i].Length; x += channelsCount) // traverse each pixel across the image at the current y value { MagickColor pixCol = new MagickColor(regVert[i][x], regVert[i][x + 1], regVert[i][x + 2]); //create magickcolour using MagickColor fCol = new MagickColor(facVert[i][x], facVert[i][x + 1], facVert[i][x + 2]); if (pixCol == regCol) //compare region colour { int bc = BorderCheck(x, i, regVert, regCol); //check if region is a border if (bc > 1 && bc < 4) { fpixels.SetPixel(x == 0 ? x : x / 3, y, Blend(secCol, fCol, 0.6)); ///divide x by 3 to account for the other channels fmPixels.SetPixel(x == 0 ? x : x / 3, y, Blend(secCol, fCol, 0.6)); } else { fpixels.SetPixel(x == 0 ? x : x / 3, y, Blend(priCol, fCol, 0.6)); fmPixels.SetPixel(x == 0 ? x : x / 3, y, Blend(priCol, fCol, 0.6)); } } } } } } Save(factionMap, f.name, saveLocation); } full_map = fullFactionMap; return(fullFactionMap.ToBitmap()); }
public FREObject ResizeImage(FREContext ctx, uint argc, FREObject[] argv) { // Read from file try { var newW = Convert.ToInt32(new FreObjectSharp(argv[1]).Value); var newH = Convert.ToInt32(new FreObjectSharp(argv[2]).Value); var array = new FREArray(new FreObjectSharp(argv[0]).RawValue); var list = array.ToArrayList(); using (MagickImageCollection collection = new MagickImageCollection()) { string outputDir = ""; int i = 0; foreach (String inputPath in list) { FileInfo input = new FileInfo(inputPath); outputDir = input.Directory.CreateSubdirectory("small").FullName; FileInfo output = new FileInfo(outputDir + @"\" + input.Name); try { using (MagickImage image = new MagickImage(input)) { MagickGeometry size = new MagickGeometry(newW, newH); //image.Resize(size); genera un ciclo infinito en v84 image.AdaptiveResize(size); // Save the result image.Write(output.FullName); collection.Add(output.FullName); collection[i].AnimationDelay = 200; } } // Catch any MagickException catch (MagickException exception) { // Write excepion raised when reading the invalid jpg to the console Trace("ERROR: " + exception); return(new FreException(exception).RawValue); } i++; } // Optionally reduce colors QuantizeSettings settings = new QuantizeSettings(); settings.Colors = 256; collection.Quantize(settings); // Optionally optimize the images (images should have the same size). collection.Optimize(); // Save gif collection.Write(outputDir + @"\output.gif"); return(new FreObjectSharp(outputDir + @"\output.gif").RawValue); } } catch (Exception e) { Trace("Exception " + e); } return(FREObject.Zero); }