Exemplo n.º 1
0
        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);
            }
        }
Exemplo n.º 2
0
 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);
         }
     }
 }
Exemplo n.º 3
0
 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);
         }
     }
 }
Exemplo n.º 4
0
        public static void Main(string[] args)
        {
            Console.WriteLine("nQuant Version {0} .net color Quantizer. An adaptation of Xiaolin Wu's fast optimal color quantizer.", Assembly.GetExecutingAssembly().GetName().Version);
            Console.WriteLine("Copyright (C) 2011 Matt Wrock.");

            if (args.Length < 1)
            {
                PrintUsage();
                Environment.Exit(1);
            }
            var sourcePath = args[0];

            ProcessArgs(args);
            if (!File.Exists(sourcePath))
            {
                Console.WriteLine("The source file you specified does not exist.");
                Environment.Exit(1);
            }
            if (string.IsNullOrEmpty(targetPath))
            {
                var lastDot = sourcePath.LastIndexOf('.');
                if (lastDot == -1)
                {
                    lastDot = sourcePath.Length;
                }
                targetPath = sourcePath.Substring(0, lastDot) + "-quant.png";
            }

            Stopwatch stopwatch = Stopwatch.StartNew();
            var       quantizer = new WuQuantizer();

            using (var bitmap = new Bitmap(sourcePath))
            {
                try
                {
                    using (var quantized = quantizer.QuantizeImage(bitmap, alphaTransparency, alphaFader))
                    {
                        quantized.Save(targetPath, ImageFormat.Png);
                    }
                }
                catch (QuantizationException q)
                {
                    Console.WriteLine(q.Message);
                }
            }
            Console.WriteLine(@"Completed in {0:s\.fff} secs with peak memory usage of {1}.", stopwatch.Elapsed, Process.GetCurrentProcess().PeakWorkingSet64.ToString("#,#"));
        }
        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;
            }
        }
Exemplo n.º 6
0
        public static void Main(string[] args)
        {
            Console.WriteLine("nQuant Version {0} .net color Quantizer. An adaptation of Xiaolin Wu's fast optimal color quantizer.", Assembly.GetExecutingAssembly().GetName().Version);
            Console.WriteLine("Copyright (C) 2011 Matt Wrock.");

            if(args.Length < 1)
            {
                PrintUsage();
                Environment.Exit(1);
            }
            var sourcePath = args[0];
            ProcessArgs(args);
            if (!File.Exists(sourcePath))
            {
                Console.WriteLine("The source file you specified does not exist.");
                Environment.Exit(1);
            }
            if (string.IsNullOrEmpty(targetPath))
            {
                var lastDot = sourcePath.LastIndexOf('.');
                if (lastDot == -1)
                    lastDot = sourcePath.Length;
                targetPath = sourcePath.Substring(0, lastDot) + "-quant" + maxColors + ".png";
            }

            Stopwatch stopwatch = Stopwatch.StartNew();
            var quantizer = new WuQuantizer();
            using(var bitmap = new Bitmap(sourcePath))
            {
                try
                {
                    using (var quantized = quantizer.QuantizeImage(bitmap, alphaTransparency, alphaFader, maxColors))
                    {
                        quantized.Save(targetPath, ImageFormat.Png);
                    }
                }
                catch (QuantizationException q)
                {
                    Console.WriteLine(q.Message);
                }
            }
            Console.WriteLine(@"Completed in {0:s\.fff} secs with peak memory usage of {1}.", stopwatch.Elapsed, Process.GetCurrentProcess().PeakWorkingSet64.ToString("#,#"));
        }
Exemplo n.º 7
0
        public void QuantTest()
        {
            var opt = new WuQuantizer();
            var source = new Bitmap("c:\\requestreduce\\requestreduce.sampleweb\\vstest\\vstest.png");

            var image = opt.QuantizeImage(source, 10, 70);
            image.Dispose();

            opt = new WuQuantizer();
            var watch = new Stopwatch();
            watch.Start();
            image = opt.QuantizeImage(source, 10, 70);
            var ms = watch.ElapsedMilliseconds;

            image.Save("c:\\requestreduce\\requestreduce.sampleweb\\vstest\\vstest-quant2.png", ImageFormat.Png);

            image.Dispose();
            source.Dispose();
        }
Exemplo n.º 8
0
        /// <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);
        }
Exemplo n.º 9
0
        protected 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 != PixelFormat.Format32bppArgb)
            {
                Bitmap newImage = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppArgb);
                using (Graphics g = Graphics.FromImage(newImage))
                {
                    g.DrawImage(img, 0, 0, img.Width, img.Height);
                }
                img = newImage;
            }

            // Quantize the image
            WuQuantizer quantizer = new WuQuantizer();
            img = (Bitmap)quantizer.QuantizeImage(img, maxColors);

            // 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;
        }
Exemplo n.º 10
0
        private void button_ReadImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();                                           //创建事例
            string         dir = Environment.GetFolderPath(Environment.SpecialFolder.Templates); //指定初始目录

            dlg.InitialDirectory = dir;                                                          //指定初始目录
            dlg.Title            = "图表对话框";
            dlg.ShowReadOnly     = true;                                                         //以只读方式打开
            dlg.ShowHelp         = true;                                                         //显示帮助按钮            ///////
            dlg.Filter           = "图表.jpg|*.jpg|图表.tif|*.tif|图表.bmp|*.bmp|所有文件|*.*";            //文件过滤器,指定打开文件类型
            //dlg.ShowDialog();//打开对话框
            //BMP 文件(*.bmp) | *.bmp | JPEG 文件(*.jpg, *.jpeg) | *.jpg, *.jpeg | PNG 文件(*.png) | *.png | GIF 文件(*.gif) | *.gif | TIFF 文件(*.tiff, *.tif) | *.tiff
            //MessageBox.Show(dlg.Title);//打开消息
            //dlg.Multiselect = true;//是否允许一次打开多个文件
            dlg.Multiselect = false;     //是否允许一次打开多个文件
                                         // if (dlg.ShowDialog() == DialogResult.OK)
                                         //{
            if (dlg.CheckPathExists)     //检查路径是否存在
            {
                if (dlg.CheckFileExists) //检查文件是否存在
                {
                    // if (dlg.ValidateNames)//检查是否有效Win32文件名
                    //  {
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        string s = dlg.FileNames[0];
                        // foreach (string s in dlg.FileNames)
                        //{                                //string fileName = dlg.FileName;
                        //MessageBox.Show("打开文件:" + s);//打开消息对话框

                        bmDraw = new Bitmap(this.pictureBox_Image.Width, this.pictureBox_Image.Height);
                        Bitmap inputimage = (Bitmap)Image.FromFile(s);

                        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmDraw);

                        double scale_width  = Convert.ToDouble(bmDraw.Width) / inputimage.Width;
                        double scale_height = Convert.ToDouble(bmDraw.Height) / inputimage.Height;
                        double scale        = scale_width;
                        if (scale_width > scale_height)
                        {
                            scale = scale_height;
                        }

                        int       centerx   = bmDraw.Width / 2;
                        int       centery   = bmDraw.Height / 2;
                        int       newWidth  = Convert.ToInt32(inputimage.Width * scale / 2);
                        int       newHeight = Convert.ToInt32(inputimage.Height * scale / 2);
                        Rectangle rg        = new Rectangle(centerx - newWidth, centery - newHeight, newWidth * 2, newHeight * 2);
                        //将bm内rg所指定的区域绘制到bm1
                        g.DrawImage(inputimage, rg);
                        this.pictureBox_Image.Image = bmDraw;



                        var sourcePath = s;
                        if (!File.Exists(sourcePath))
                        {
                            Console.WriteLine("The source file you specified does not exist.");
                            Environment.Exit(1);
                        }

                        var lastDot    = sourcePath.LastIndexOf('.');
                        var targetPath = sourcePath.Insert(lastDot, "-quant");
                        //if(args.Length > 1)
                        //    targetPath = args[1];

                        var quantizer = new WuQuantizer();
                        // QuantizedPalette ColorPalette = new QuantizedPalette();
                        var    bitmap0 = new Bitmap(sourcePath);
                        Bitmap bitmap1 = ConvertTo32bpp(bitmap0);

                        using (var bitmap = bitmap1)
                        //using (var bitmap = new Bitmap(sourcePath))
                        {
                            using (var quantized = quantizer.QuantizeImage(bitmap))
                            {
                                QuantizedPalette palette = quantizer.palette;
                                //quantized.Save(targetPath, ImageFormat.Png);


                                inputimage   = new Bitmap(quantized);
                                scale_width  = Convert.ToDouble(bmDraw.Width) / inputimage.Width;
                                scale_height = Convert.ToDouble(bmDraw.Height) / inputimage.Height;
                                scale        = scale_width;
                                if (scale_width > scale_height)
                                {
                                    scale = scale_height;
                                }

                                centerx   = bmDraw.Width / 2;
                                centery   = bmDraw.Height / 2;
                                newWidth  = Convert.ToInt32(inputimage.Width * scale / 2);
                                newHeight = Convert.ToInt32(inputimage.Height * scale / 2);
                                rg        = new Rectangle(centerx - newWidth, centery - newHeight, newWidth * 2, newHeight * 2);
                                //将bm内rg所指定的区域绘制到bm1
                                g.DrawImage(inputimage, rg);
                                this.pictureBox_Image.Image = bmDraw;
                            }
                        }
                    }
                    // }
                }
            }
        }
Exemplo n.º 11
0
 public void Save(string v)
 {
     stage.Unlock(true);
     WuQuantizer quantizer = new WuQuantizer();
     Image quantized = quantizer.QuantizeImage(bmp, 128, 0);
     quantized.Save(v, System.Drawing.Imaging.ImageFormat.Png);
 }
Exemplo n.º 12
0
        public RSImage(string filename, out Exception ex)
        {
            try
            {
                Bitmap bmp = new Bitmap(filename, true);
                if (bmp.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppArgb)
                    bmp.MakeTransparent(Color.Transparent); //force bmp to be 32-bit
                WuQuantizer q = new WuQuantizer();
                bmp = new Bitmap(q.QuantizeImage(bmp));
                QuantizedPalette p = q.Palette;
                Palette = new Color[p.Colors.Count];
                for (int i = 0; i < p.Colors.Count; i++)
                    Palette[i] = p.Colors[i];

                Pixels = new Color[bmp.Width * bmp.Height];
                for (int i = 0; i < bmp.Width * bmp.Height; i++)
                    Pixels[i] = bmp.GetPixel(i % bmp.Width, i / bmp.Width);
                WholeWidth = Width = bmp.Width;
                WholeHeight = Height = bmp.Height;
                XOffset = 0;
                YOffset = 0;

                ex = null;
            }
            catch (Exception e)
            {
                ex = e;
                Pixels = null;
            }
        }
Exemplo n.º 13
0
    public static SqlBoolean SaveToFolderByZoomXY8bpp(SqlBinary image, SqlString rootFolderPath, SqlInt32 Zoom, SqlInt32 X, SqlInt32 Y)
    {
        SqlBoolean result = false;
          using (MemoryStream ms = new MemoryStream())
          {
              ms.Write(image.Value, 0, image.Length);
              SetBeginPosition(ms);

              using (var bitmap = new Bitmap(ms))
              {
                  if (bitmap == null) throw new Exception("Не удалось инициализировать объект Bitmap из Stream");
                  var quantizer = new WuQuantizer();
                  if (quantizer == null) throw new Exception("Не удалось инициализировать объект WuQuantizer");
                  using (var quantized = quantizer.QuantizeImage(bitmap))
                  {
                      if (quantized == null) throw new Exception("Не удалось инициализировать объект Image с помощью экземпляра WuQuantizer");
                      //try
                      //{
                      string zoomFolder = string.Format(@"{0}/{1}", rootFolderPath, Zoom);
                      CheckFolderExistsCreate(zoomFolder);
                      string xFolder = string.Format(@"{0}/{1}", zoomFolder, X);
                      CheckFolderExistsCreate(xFolder);
                      quantized.Save(string.Format("{0}/{1}/{2}/{3}.png", rootFolderPath, Zoom, X, Y), ImageFormat.Png);

                      //using (MemoryStream msquant = new MemoryStream())
                      //{
                      //    quantized.Save(msquant, ImageFormat.Png);
                      //    SetBeginPosition(msquant);
                      //    using (Icon2TileRendering renderer = new Icon2TileRendering(msquant))
                      //    {
                      //        renderer.SaveToPngFile((string) rootFolderPath, Zoom.ToString(), X.ToString(), Y.ToString());
                      //        result = true;
                      //    }
                      //}
                      //Image i2 = new Bitmap(quantized);
                      //CheckFolder((string)rootFolderPath, Zoom.ToString(), X.ToString(), Y.ToString())
                      //;
                      //i2.Save(string.Format("{0}/{1}/{2}/{3}.png", rootFolderPath, Zoom, X, Y), ImageFormat.Png);

                          //var img = ImageToStreamToImage(quantized);
                          //img.Save(string.Format("{0}/{1}/{2}/{3}.png", rootFolderPath, Zoom, X, Y), ImageFormat.Png);
                          //quantized.Save(string.Format("{0}/{1}/{2}/{3}.png", rootFolderPath, Zoom, X, Y), ImageFormat.Png);
                      //}
                      //catch (System.Exception ex)
                      //{
                      //    throw new Exception(string.Format("SaveToFolderByZoomXY8bpp {0}", ex.Message));
                      //}

                  }
              }
          }
          // Put your code here
        return result;
    }