private static void Main(string[] args) { string source = args[0]; var bytes = File.ReadAllBytes(source); // First convert image to 32 bit, then reduce to 8bit using (var original = GetBitmapFromBytes(bytes)) using (var cloned32 = new Bitmap( original.Width, original.Height, PixelFormat.Format32bppPArgb)) { using (var graphics = Graphics.FromImage(cloned32)) { graphics.DrawImage( original, new Rectangle(0, 0, cloned32.Width, cloned32.Height)); } using (Image compressedImage = new WuQuantizer().QuantizeImage(cloned32)) { compressedImage.Save(args[1], ImageFormat.Png); } } }
public override void Compress(FileInfo oldImage, string oldBaseFolder, string newBaseFolder) { var quantizer = new WuQuantizer(); var imageFullPath = oldImage.FullName; using (Bitmap bmp1 = new Bitmap(imageFullPath)) { var bitMap = bmp1; if (bmp1.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppArgb) { ConvertTo32bppAndDisposeOriginal(ref bitMap); } using (var quantized = quantizer.QuantizeImage(bitMap)) { var newPath = GetNewPath(oldImage.FullName, oldBaseFolder, newBaseFolder); var newFolderPath = GetNewPath(oldImage.DirectoryName, oldBaseFolder, newBaseFolder); if (!Directory.Exists(newFolderPath)) { Directory.CreateDirectory(newFolderPath); } quantized.Save(newPath, ImageFormat.Png); } } Console.WriteLine($"PngCompressService: Compress Done {oldImage.Name}"); }
public void QuantizersDitherByDefault() { var werner = new WernerPaletteQuantizer(); var webSafe = new WebSafePaletteQuantizer(); var octree = new OctreeQuantizer(); var wu = new WuQuantizer(); Assert.NotNull(werner.Options.Dither); Assert.NotNull(webSafe.Options.Dither); Assert.NotNull(octree.Options.Dither); Assert.NotNull(wu.Options.Dither); using (IQuantizer <Rgba32> quantizer = werner.CreatePixelSpecificQuantizer <Rgba32>(this.Configuration)) { Assert.NotNull(quantizer.Options.Dither); } using (IQuantizer <Rgba32> quantizer = webSafe.CreatePixelSpecificQuantizer <Rgba32>(this.Configuration)) { Assert.NotNull(quantizer.Options.Dither); } using (IQuantizer <Rgba32> quantizer = octree.CreatePixelSpecificQuantizer <Rgba32>(this.Configuration)) { Assert.NotNull(quantizer.Options.Dither); } using (IQuantizer <Rgba32> quantizer = wu.CreatePixelSpecificQuantizer <Rgba32>(this.Configuration)) { Assert.NotNull(quantizer.Options.Dither); } }
/// <summary> /// Processes a single item. /// </summary> /// <param name="input">The input to process.</param> /// <returns>The output of the process.</returns> public override IAssetFile Process(IAssetFile input) { try { // Minify css var quantizer = new WuQuantizer(); using (var bitmap = new Bitmap(Bitmap.FromStream(input.Content.AsStream()))) { using (var quantized = quantizer.QuantizeImage(bitmap, 10, 70)) using (var output = new MemoryStream()) { // Save to the output stream quantized.Save(output, ImageFormat.Png); // Minified successfully Tracing.Info("PNG", "Optimized " + input.RelativeName); // Return processed output return(AssetOutputFile.Create(input, output)); } } } catch (Exception ex) { // We didn't manage to create anything Tracing.Error("PNG", ex); return(null); } }
public override IOptimizerResult Optimize(MediaStream stream) { var quantizer = new WuQuantizer(); var memoryStream = new MemoryStream(); using (var bitmap = new Bitmap(stream.Stream)) { var bitDepth = Image.GetPixelFormatSize(bitmap.PixelFormat); if (bitDepth != 32) { return(OptimizerFailureResult("the image you are attempting to quantize does not contain a 32 bit ARGB palette. This image has a bit depth of {0} with {1} colors".FormatWith(bitDepth, bitmap.Palette.Entries.Length))); } using (var quantized = quantizer.QuantizeImage(bitmap)) { quantized.Save(memoryStream, ImageFormat.Png); } // rewind the stream memoryStream.Seek(0, SeekOrigin.Begin); var result = new PngQuantOptimizerResult(); result.Success = true; result.SizeBefore = (int)stream.Length; result.SizeAfter = (int)memoryStream.Length; result.ResultStream = memoryStream; return(OptimizationSuccessful(result)); } }
/// <summary> /// This method pre-seeds the WuQuantizer in the AoT compiler for iOS. /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> private static void AotCompileWuQuantizer <TPixel>() where TPixel : unmanaged, IPixel <TPixel> { using (var test = new WuQuantizer <TPixel>(Configuration.Default, new WuQuantizer().Options)) { var frame = new ImageFrame <TPixel>(Configuration.Default, 1, 1); test.QuantizeFrame(frame, frame.Bounds()); } }
public void QuantizersDitherByDefault() { var palette = new PaletteQuantizer <Rgba32>(); var octree = new OctreeQuantizer <Rgba32>(); var wu = new WuQuantizer <Rgba32>(); Assert.True(palette.Dither); Assert.True(octree.Dither); Assert.True(wu.Dither); }
protected void CompressAndSave(System.Drawing.Image img, string path, string extension) { //try //{ // // If jpg is extension then remove png equivalent of it // // because if extension is same it'll be overridden // string delFilePath = path; // if (extension == ".png") // { // delFilePath = delFilePath.Substring(0, delFilePath.Length - 3) + "jpg"; // } // else // { // delFilePath = delFilePath.Substring(0, delFilePath.Length - 3) + "png"; // } // if (System.IO.File.Exists(delFilePath)) // { // System.IO.File.Delete(delFilePath); // } //} //catch { } if (extension == ".jpg" || extension == ".jpeg") { using (Bitmap bitmap = new Bitmap(img)) { ImageCodecInfo imageEncoder = null; imageEncoder = GetEncoder(ImageFormat.Jpeg); // Create an Encoder object based on the GUID // for the Quality parameter category. Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; // Create an EncoderParameters object. // An EncoderParameters object has an array of EncoderParameter // objects. In this case, there is only one // EncoderParameter object in the array. EncoderParameters encodingParams = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L); encodingParams.Param[0] = myEncoderParameter; bitmap.Save(path, imageEncoder, encodingParams); } } else { var quantizer = new WuQuantizer(); using (var bitmap = new Bitmap(img)) { using (var quantized = quantizer.QuantizeImage(bitmap)) //, alphaTransparency, alphaFader)) { quantized.Save(path, ImageFormat.Png); } } } }
/// <summary> /// 转换 PNG 格式的图片为 8 bit 格式的 PNG 图片,比改变图片的尺寸,但大量减少文件大小。质量有损失 /// </summary> /// <param name="sourceImageUrl"></param> /// <param name="targetImageUrl"></param> public static void ConvertPngTo8Bit(string sourceImageUrl, string targetImageUrl) { var quantizer = new WuQuantizer(); using (var bitmap = new Bitmap(sourceImageUrl)) { using (var quantized = quantizer.QuantizeImage(bitmap)) { quantized.Save(targetImageUrl, ImageFormat.Png); } } }
private unsafe byte[] BitmapToRawIndexed(Bitmap source, int maxColors, out byte[][] palette) { Bitmap img = source; byte[] destination = new byte[img.Width * img.Height]; // If this is not a 32-bit ARGB bitmap, convert it to one if (img.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppArgb) { Bitmap newImage = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(newImage)) { g.DrawImage(img, 0, 0, img.Width, img.Height); } img = newImage; } // Quantize the image WuQuantizer quantizer = new WuQuantizer(); m_palette = quantizer.CreatePalette(img, maxColors); img = (Bitmap)quantizer.QuantizeImage(img, m_palette); // Copy over the data to the destination. We need to use Stride in this case, as it may not // always be equal to Width. BitmapData bitmapData = img.LockBits(new Rectangle(0, 0, img.Width, img.Height), ImageLockMode.ReadOnly, img.PixelFormat); byte *pointer = (byte *)bitmapData.Scan0; for (int y = 0; y < bitmapData.Height; y++) { for (int x = 0; x < bitmapData.Width; x++) { destination[(y * img.Width) + x] = pointer[(y * bitmapData.Stride) + x]; } } img.UnlockBits(bitmapData); // Copy over the palette palette = new byte[maxColors][]; for (int i = 0; i < maxColors; i++) { palette[i] = new byte[4]; palette[i][3] = img.Palette.Entries[i].A; palette[i][2] = img.Palette.Entries[i].R; palette[i][1] = img.Palette.Entries[i].G; palette[i][0] = img.Palette.Entries[i].B; } return(destination); }
public void SinglePixelTransparent() { Configuration config = Configuration.Default; var quantizer = new WuQuantizer(false); using (var image = new Image <Rgba32>(config, 1, 1, default(Rgba32))) using (IQuantizedFrame <Rgba32> result = quantizer.CreateFrameQuantizer <Rgba32>(config).QuantizeFrame(image.Frames[0])) { Assert.Equal(1, result.Palette.Length); Assert.Equal(1, result.GetPixelSpan().Length); Assert.Equal(default, result.Palette.Span[0]);
/// <summary> /// Optimized and processes the .png image. /// /// </summary> /// <param name="path">Absolute path to image file.</param> /// <returns>The processed image stream.</returns> public Stream ShrinkPNG(string path) { using (var bitmap = (Bitmap)System.Drawing.Image.FromFile(path)) { const int alphaTransparency = 0; const int alphaFader = 0; var quantizer = new WuQuantizer(); var retMS = new MemoryStream(); using (var quantized = quantizer.QuantizeImage(bitmap, alphaTransparency, alphaFader)) { quantized.Save(retMS, ImageFormat.Png); } return(retMS); } }
static void Run(Options cfg) { Image originalImage; if (String.IsNullOrWhiteSpace(cfg.InputImage) || !System.IO.File.Exists(cfg.InputImage)) { originalImage = GenerateRandomBitmap(); } else { originalImage = Image.FromFile(cfg.InputImage); } Color c = Color.FromName(cfg.ColorName); if (c.ToArgb() == 0) { c = Color.HotPink; } var quantizer = new WuQuantizer(); using (Bitmap drawingBitmap = new Bitmap(originalImage.Width, originalImage.Height)) using (Graphics gfx = Graphics.FromImage(drawingBitmap)) using (Font fnt = new Font(cfg.FontName, cfg.FontSize)) using (Brush b = new SolidBrush(c)) { gfx.DrawImage(originalImage, 0, 0); SizeF sz = gfx.VisibleClipBounds.Size; gfx.TranslateTransform(sz.Width / 2, sz.Height / 2); gfx.RotateTransform(cfg.Angle); sz = gfx.MeasureString(cfg.Text, fnt); gfx.DrawString(cfg.Text, fnt, b, -(sz.Width / 2), -(sz.Height / 2)); gfx.ResetTransform(); if (cfg.UseQuantizer) { using (var q = quantizer.QuantizeImage(drawingBitmap)) { q.Save(cfg.OutImage); } } else { drawingBitmap.Save(cfg.OutImage); } } originalImage.Dispose(); }
/// <summary> /// /// </summary> /// <param name="bmp"></param> public static Bitmap ReduceColors(Bitmap bitmap, int colorCount) { if (bitmap.Width <= 16 && bitmap.Height <= 16) // no need { return(bitmap); } var quantizer = new WuQuantizer(); using (var quantized = quantizer.QuantizeImage(bitmap, 10, 70, colorCount)) { return(new Bitmap(quantized)); } }
private void ProcessTexture(Texture2D texture, string outputPath, bool compress) { if (thumbnailBackgroundTexture) { var texturePixels = texture.GetPixels(); var backgroundPixels = thumbnailBackgroundTexture.GetPixels(); for (var i = 0; i < texturePixels.Length; i++) { texturePixels[i] = Color.Lerp(backgroundPixels[i], texturePixels[i], texturePixels[i].a); } texture.SetPixels(texturePixels); } if (thumbnailForegroundTexture) { var texturePixels = texture.GetPixels(); var foregroundPixels = thumbnailForegroundTexture.GetPixels(); for (var i = 0; i < texturePixels.Length; i++) { texturePixels[i] = Color.Lerp(texturePixels[i], foregroundPixels[i], foregroundPixels[i].a); } texture.SetPixels(texturePixels); } if (compress) { var quantize = new WuQuantizer(); var bitmap = new Bitmap(128, 128); var index = 0; foreach (var pixel in texture.GetPixels()) { var x = index % 128; var y = 127 - index / 128; bitmap.SetPixel(x, y, System.Drawing.Color.FromArgb( Mathf.CeilToInt(Mathf.Clamp(pixel.a * 255, 0, 255)), Mathf.CeilToInt(Mathf.Clamp(pixel.r * 255, 0, 255)), Mathf.CeilToInt(Mathf.Clamp(pixel.g * 255, 0, 255)), Mathf.CeilToInt(Mathf.Clamp(pixel.b * 255, 0, 255)) )); index++; } var image = quantize.QuantizeImage(bitmap); image.Save(outputPath); } else { File.WriteAllBytes(outputPath, texture.EncodeToPNG()); } }
public void QuantizersDitherByDefault() { var palette = new PaletteQuantizer(); var octree = new OctreeQuantizer(); var wu = new WuQuantizer(); Assert.NotNull(palette.Diffuser); Assert.NotNull(octree.Diffuser); Assert.NotNull(wu.Diffuser); Assert.True(palette.CreateFrameQuantizer <Rgba32>().Dither); Assert.True(octree.CreateFrameQuantizer <Rgba32>().Dither); Assert.True(wu.CreateFrameQuantizer <Rgba32>().Dither); }
public static void SquishNewlyUploadedPNGs( Stream input, Stream output) { var quantizer = new WuQuantizer(); using (var bitmap = new Bitmap(input)) { using (var quantized = quantizer.QuantizeImage(bitmap)) { quantized.Save(output, ImageFormat.Png); } } }
public static void SquishNewlyUploadedPNGs( [BlobTrigger("processimageincloud/{name}")] Stream input, [Blob("processimageincloudoutput/{name}", FileAccess.Write)] Stream output) { var quantizer = new WuQuantizer(); using (var bitmap = new Bitmap(input)) { using (var quantized = quantizer.QuantizeImage(bitmap)) { quantized.Save(output, ImageFormat.Png); } } }
public void Load(Stream mystream, int SamplePercentage) { PalletPixelCount.Clear(); Image <Rgba32> image = Image.Load <Rgba32>(mystream); var quantizer = new WuQuantizer <Rgba32>(); var quantizationResults = quantizer.Quantize(image.Frames.RootFrame, PaletteCount); PalletPixelCount = quantizationResults.Pixels.GroupBy(P => P) .Select(group => new KeyValuePair <Rgba32, int>(quantizationResults.Palette[group.Key], group.Count())) .OrderByDescending(I => I.Value) .ToList(); }
public void To8BitPng(string path, Bitmap image) { try { var quantizer = new WuQuantizer(); using (var quantized = quantizer.QuantizeImage(image)) { quantized.Save(path, ImageFormat.Png); } } catch (Exception ex) { throw ex; } }
/// <summary> /// Encodes a bitmap into an indexed bitmap with a per-pixel palette color index using a specified number of colors in the palette. /// </summary> /// <param name="bitmap">The bitmap to encode.</param> /// <param name="paletteColorCount">The number of colors to be present in the palette.</param> /// <param name="indices">The per-pixel palette color indices.</param> /// <param name="palette">The <see cref="Color"/> array containing the palette colors of the indexed bitmap.</param> public static void QuantizeBitmap(Bitmap bitmap, int paletteColorCount, out byte[] indices, out Color[] palette) { int bitDepth = Image.GetPixelFormatSize(bitmap.PixelFormat); if (bitDepth != 32) { bitmap = ConvertTo32Bpp(bitmap); } WuQuantizer quantizer = new WuQuantizer(); Bitmap quantBitmap = (Bitmap)quantizer.QuantizeImage(bitmap, paletteColorCount, 0, 1); palette = GetPalette(quantBitmap, paletteColorCount); indices = GetIndices(quantBitmap); }
public void SinglePixelOpaque() { Configuration config = Configuration.Default; var quantizer = new WuQuantizer(false); using (var image = new Image <Rgba32>(config, 1, 1, Color.Black)) using (IQuantizedFrame <Rgba32> result = quantizer.CreateFrameQuantizer <Rgba32>(config).QuantizeFrame(image.Frames[0])) { Assert.Equal(1, result.Palette.Length); Assert.Equal(1, result.GetPixelSpan().Length); Assert.Equal(Color.Black, (Color)result.Palette.Span[0]); Assert.Equal(0, result.GetPixelSpan()[0]); } }
public Image Apply(Image sourceImage, Matrix matrix) { using (WuQuantizer quantizer = new WuQuantizer((Bitmap)sourceImage)) { int colorCount = quantizer.GetColorCount(); if (colorCount > Colors) { try { return(quantizer.GetQuantizedImage(Colors)); } catch (Exception e) { LOG.Warn("Error occurred while Quantizing the image, ignoring and using original. Error: ", e); } } } return(null); }
public static Bitmap Quantize(Image img) { WuQuantizer q = new WuQuantizer(); using (var bitmap = new Bitmap(img)) { using (var quantized = q.QuantizeImage(bitmap)) { using (MemoryStream _stream = new MemoryStream()) { quantized.Save(_stream, ImageFormat.Bmp); return(new Bitmap(_stream)); } } } }
//[Benchmark] public void WuQuantizer() { using (var bitmap = BitmapFactory.CreateEmpty(400, 400, PixelFormat.Format24bppRgb, Color.White)) { using (var graphics = Graphics.FromImage(bitmap)) using (var pen = new SolidBrush(Color.Blue)) { graphics.FillRectangle(pen, new Rectangle(30, 30, 340, 340)); } var quantizer = new WuQuantizer(bitmap); using (var quantizedImage = quantizer.GetQuantizedImage()) { quantizedImage.Save(@"quantized.png", ImageFormat.Png); } } }
public static Image2 Quantize(this Image2 source, Quantization mode = Quantization.Octree, int maxColors = 256) { IQuantizer quantizer; switch (mode){ case Quantization.Wu: quantizer = new WuQuantizer(); break; case Quantization.Palette: quantizer = new PaletteQuantizer(); break; default: quantizer = new OctreeQuantizer(); break; } return Quantize(source, quantizer, maxColors); }
public static async Task To8BitPng(string path, Bitmap image) { try { var quantizer = new WuQuantizer(); using (var quantized = quantizer.QuantizeImage(image)) { quantized.Save(path, ImageFormat.Png); } await Task.CompletedTask; } catch (Exception ex) { throw ex; } }
public void SinglePixelTransparent() { Configuration config = Configuration.Default; var quantizer = new WuQuantizer(new QuantizerOptions { Dither = null }); using var image = new Image <Rgba32>(config, 1, 1, default(Rgba32)); ImageFrame <Rgba32> frame = image.Frames.RootFrame; using IFrameQuantizer <Rgba32> frameQuantizer = quantizer.CreateFrameQuantizer <Rgba32>(config); using QuantizedFrame <Rgba32> result = frameQuantizer.QuantizeFrame(frame, frame.Bounds()); Assert.Equal(1, result.Palette.Length); Assert.Equal(1, result.GetPixelSpan().Length); Assert.Equal(default, result.Palette.Span[0]);
public void QuantizersDitherByDefault() { var werner = new WernerPaletteQuantizer(); var webSafe = new WebSafePaletteQuantizer(); var octree = new OctreeQuantizer(); var wu = new WuQuantizer(); Assert.NotNull(werner.Diffuser); Assert.NotNull(webSafe.Diffuser); Assert.NotNull(octree.Diffuser); Assert.NotNull(wu.Diffuser); Assert.True(werner.CreateFrameQuantizer <Rgba32>(this.Configuration).Dither); Assert.True(webSafe.CreateFrameQuantizer <Rgba32>(this.Configuration).Dither); Assert.True(octree.CreateFrameQuantizer <Rgba32>(this.Configuration).Dither); Assert.True(wu.CreateFrameQuantizer <Rgba32>(this.Configuration).Dither); }
public string Apply(string input_dir, string output_dir, string fn, int k, int tn) { try { string fn_only = Path.GetFileNameWithoutExtension(fn); //MeanShift Log.WriteLine("Meanshift in progress..."); MeanShiftMultiThreads mt = new MeanShiftMultiThreads(); string ms_path = output_dir + fn_only + "_ms.png"; mt.ApplyYIQMT(input_dir + fn, tn, 3, 3, ms_path); mt = null; GC.Collect(); Log.WriteLine("Meanshift finished"); // Median Cut Log.WriteLine("Median Cut in progress..."); int mc_colors = 256; string mc_path = output_dir + fn_only + "_mc" + mc_colors.ToString() + ".png"; using (Bitmap msimg = new Bitmap(output_dir + fn_only + "_ms.png")) { WuQuantizer wq = new WuQuantizer(); wq.QuantizeImage(msimg).Save(mc_path, ImageFormat.Png); } Log.WriteLine("Median Cut finished"); // KMeans Log.WriteLine("KMeans in progress..."); MyKMeans kmeans = new MyKMeans(); string kmeans_path = output_dir + fn_only + "_mc" + mc_colors + "_k" + k + ".png"; kmeans.Apply(k, mc_path, kmeans_path); kmeans = null; GC.Collect(); Log.WriteLine("KMeans finished"); return(kmeans_path); } catch (Exception e) { Log.WriteLine("ColorSegmentationWorker: " + e.Message); Log.WriteLine(e.Source); Log.WriteLine(e.StackTrace); throw; } }
public void WuQuantizerYieldsCorrectTransparentPixel <TPixel>(TestImageProvider <TPixel> provider, bool dither) where TPixel : struct, IPixel <TPixel> { using (Image <TPixel> image = provider.GetImage()) { Assert.True(image[0, 0].Equals(default(TPixel))); var quantizer = new WuQuantizer(dither); foreach (ImageFrame <TPixel> frame in image.Frames) { QuantizedFrame <TPixel> quantized = quantizer.CreateFrameQuantizer <TPixel>().QuantizeFrame(frame); int index = this.GetTransparentIndex(quantized); Assert.Equal(index, quantized.GetPixelSpan()[0]); } } }
public void EndToEndTest(string pngFileName) { const string testFilePath = "output_nquant.png"; if (File.Exists(testFilePath)) { File.Delete(testFilePath); } var sw = new Stopwatch(); var originalFilePath = Path.Combine(@"../../../samples", pngFileName); using (var bitmap = (Bitmap)Image.FromFile(originalFilePath)) { const int alphaTransparency = 0; const int alphaFader = 0; var quantizer = new WuQuantizer (); sw.Start (); using (var quantized = quantizer.QuantizeImage (bitmap, alphaTransparency, alphaFader)) quantized.Save (testFilePath, ImageFormat.Png); } Debug.WriteLine(string.Format("nQuant: {0} ms/image", sw.ElapsedMilliseconds)); Assert.True(File.Exists(testFilePath)); var fileLength = new FileInfo(testFilePath).Length; Assert.True(fileLength > 0); Assert.True(fileLength < new FileInfo(originalFilePath).Length); }