예제 #1
0
        private void ConvertToI4(Bitmap imageToConvert)
        {
            SetupCoder(imageToConvert);
            /* We will need to add a grayscale check in the future also */
            if (UniqueColors.Count > 16)
            {
                WuQuantizer quantizer = new WuQuantizer();
                imageToConvert = new Bitmap(quantizer.QuantizeImage(imageToConvert, 0, 0, new Histogram(), 16));
                SetupCoder(imageToConvert);
            }

            /* Set type, I 4-bit */
            Format       = GBI.G_IM_FMT_I;
            Size         = GBI.G_IM_SIZ_4b;
            n64ImageType = N64ImageType.i4;
            /* Generate texture buffer */
            Data    = new byte[(imageToConvert.Width * imageToConvert.Height) / 2];
            Palette = null;

            /* Loop through pixels, convert to I 4-bit, write to texture buffer */
            for (int i = 0, j = 0; i < Raw.Length; i += 8, j++)
            {
                Data[j] = (byte)(((Raw[i] / 16) << 4) | ((Raw[i + 4] / 16) & 0xF));
            }
        }
예제 #2
0
        private void ConvertToCi4(Bitmap imageToConvert)
        {
            /* Convert to CI */
            if (UniqueColors.Count > 16)
            {
                WuQuantizer quantizer = new WuQuantizer();
                imageToConvert = new Bitmap(quantizer.QuantizeImage(imageToConvert, 0, 0, new Histogram(), 16));
                SetupCoder(imageToConvert);
            }
            /* Set type, CI 4-bit */
            Format       = GBI.G_IM_FMT_CI;
            Size         = GBI.G_IM_SIZ_4b;
            n64ImageType = N64ImageType.ci4;
            /* Generate texture buffer */
            Data = new byte[(imageToConvert.Width * imageToConvert.Height) / 2];

            /* Generate 16-color RGBA5551 palette */
            Palette = GeneratePalette(UniqueColors, 16);

            /* Loop through pixels, get palette indexes, write to texture buffer */
            for (int i = 0, j = 0; i < Raw.Length; i += 8, j++)
            {
                ushort RGBA5551_1 = ToRGBA5551(Raw[i + 2], Raw[i + 1], Raw[i], Raw[i + 3]);
                ushort RGBA5551_2 = ToRGBA5551(Raw[i + 6], Raw[i + 5], Raw[i + 4], Raw[i + 7]);
                byte   Value      = (byte)(
                    ((GetPaletteIndex(Palette, RGBA5551_1)) << 4) |
                    ((GetPaletteIndex(Palette, RGBA5551_2) & 0xF)));
                Data[j] = Value;
            }
        }
예제 #3
0
        public void MyQuantiserTest(string fileName, string outName)
        {
            using Bitmap bitmap = new Bitmap(fileName);
            BitmapData bitmapData = bitmap.LockBits(
                new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.ReadWrite,
                PixelFormat.Format32bppArgb);
            IntPtr bitmapPtr = bitmapData.Scan0;

            int[] pixelDataArray = new int[bitmap.Width * bitmap.Height];
            Marshal.Copy(bitmapPtr, pixelDataArray, 0, bitmap.Width * bitmap.Height);
            bitmap.UnlockBits(bitmapData);
            byte[] indexedData;
            uint[] palette;

            (indexedData, palette) = WuQuantizer.QuantizeImage(pixelDataArray, 256);

            IntPtr newPtr = Marshal.AllocHGlobal(bitmap.Width * bitmap.Height);

            Marshal.Copy(indexedData, 0, newPtr, bitmap.Width * bitmap.Height);
            Bitmap       newBitmap    = new Bitmap(bitmap.Width, bitmap.Height, bitmap.Width, PixelFormat.Format8bppIndexed, newPtr);
            ColorPalette colorPalette = newBitmap.Palette;

            for (int i = 0; i < 256; i++)
            {
                colorPalette.Entries[i] = (i < palette.Length) ? Color.FromArgb((int)palette[i]) : Color.Transparent;
            }
            newBitmap.Palette = colorPalette;
            newBitmap.Save(outName, ImageFormat.Png);
            Marshal.FreeHGlobal(newPtr);
        }
예제 #4
0
        public HttpResponseMessage Resize(string source, int width, int height)
        {
            var sourceExtension = Path.GetExtension(source);

            var httpResponseMessage = new HttpResponseMessage();

            Image image = Image.FromFile(HttpContext.Current.Server.MapPath(source));

            Image resizedImage = PhotoFileHelper.Resize(image, width, height);

            var memoryStream = new MemoryStream();

            var quantizer = new WuQuantizer();

            using (var bitmap = new Bitmap(resizedImage))
            {
                using (var quantized = quantizer.QuantizeImage(bitmap, 1, 1))
                {
                    quantized.Save(memoryStream, PhotoFileHelper.GetImageFormat(sourceExtension));
                }
            }

            httpResponseMessage.Content = new ByteArrayContent(memoryStream.ToArray());

            httpResponseMessage.Content.Headers.ContentType = PhotoFileHelper.GetMediaContentType(sourceExtension);

            httpResponseMessage.StatusCode = HttpStatusCode.OK;

            return(httpResponseMessage);
        }
예제 #5
0
파일: Program.cs 프로젝트: rgelb/To8BitPng
        /// <summary>
        /// Convert a PNG file to 8-bit color
        /// Note that it's responsibility of the caller to handle exceptions
        /// </summary>
        /// <exception cref="System.Exception">Catch all error for a number of scenarios</exception>
        /// <param name="filePath"></param>
        public static void To8BitPngByFile(string filePath, bool checkColorDepth = true)
        {
            if (checkColorDepth)
            {
                // check to see if the file is already 8 bit
                if (IsPng8BitColorDepth(filePath))
                {
                    // no need to convert - it's already 8 bit.
                    return;
                }
            }

            var   quantizer = new WuQuantizer();
            Image quantized = null;

            try
            {
                var bitmap = new Bitmap(filePath);
                quantized = quantizer.QuantizeImage(bitmap);

                // release the original bitmap so that it can be overwriten
                bitmap.Dispose();

                quantized.Save(filePath, ImageFormat.Png);
            } finally
            {
                if (quantized != null)
                {
                    quantized.Dispose();
                }
            }
        }
예제 #6
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("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);
        }
예제 #7
0
        private void OptimizePNG(ImageFile imageFile)
        {
            try
            {
                string tempFile          = Path.GetDirectoryName(imageFile.Path) + @"\temp-" + Path.GetFileName(imageFile.Path);
                int    alphaTransparency = 10;
                int    alphaFader        = 70;
                var    quantizer         = new WuQuantizer();
                using (var bitmap = new Bitmap(imageFile.Path))
                {
                    using (var quantized = quantizer.QuantizeImage(bitmap, alphaTransparency, alphaFader))
                    {
                        quantized.Save(tempFile, ImageFormat.Png);
                    }
                }
                File.Delete(imageFile.Path);
                File.Move(tempFile, imageFile.Path);

                imageFile.Status  = "OK";
                imageFile.NewSize = new FileInfo(imageFile.Path).Length;
                imageFile.Rate    = imageFile.OldSize - imageFile.NewSize;
                imageFile.Rate   /= imageFile.OldSize;
                imageFile.Rate   *= 100;
            } catch (Exception e)
            {
                imageFile.Status = e.Message;
            }
        }
예제 #8
0
        private void ConvertToCi8(Bitmap imageToConvert)
        {
            if (UniqueColors.Count > 256)
            {
                WuQuantizer quantizer = new WuQuantizer();
                imageToConvert = new Bitmap(quantizer.QuantizeImage(imageToConvert, 0, 0, new Histogram(), 256));
                SetupCoder(imageToConvert);
            }

            /* Set type, CI 8-bit */
            Format       = GBI.G_IM_FMT_CI;
            Size         = GBI.G_IM_SIZ_8b;
            n64ImageType = N64ImageType.ci8;

            /* Generate texture buffer
             * NFL BLitz requires CI8 to be padded to 8 bytes */
            int dataSize = (imageToConvert.Width * imageToConvert.Height);

            while (dataSize % 8 != 0)
            {
                dataSize++;
            }
            Data = new byte[dataSize];

            /* Generate 256-color RGBA5551 palette */
            Palette = GeneratePalette(UniqueColors, 256);

            /* Loop through pixels, get palette indexes, write to texture buffer */
            for (int i = 0, j = 0; i < Raw.Length; i += 4, j++)
            {
                ushort RGBA5551 = ToRGBA5551(Raw[i + 2], Raw[i + 1], Raw[i], Raw[i + 3]);
                Data[j] = (byte)GetPaletteIndex(Palette, RGBA5551);
            }
        }
예제 #9
0
        private Task OnPrePublishFile(ILocation outLoc, PrePublishFileArgs args)
        {
            var path = args.File.Location.ToPath();

            var opts = m_Settings.IgnoreMatchCase ? RegexOptions.IgnoreCase : RegexOptions.None;

            if (m_Settings.MatchPattern.Any(p => Regex.IsMatch(path, p, opts)))
            {
                var quantizer = new WuQuantizer();

                using (var inStr = new MemoryStream(args.File.Content))
                {
                    inStr.Seek(0, SeekOrigin.Begin);

                    using (var img = Image.FromStream(inStr))
                    {
                        using (var bmp = new Bitmap(img))
                        {
                            using (var outStr = new MemoryStream())
                            {
                                using (var quantized = quantizer.QuantizeImage(bmp))
                                {
                                    quantized.Save(outStr, img.RawFormat);
                                    outStr.Seek(0, SeekOrigin.Begin);
                                    args.File = new PluginFile(outStr.GetBuffer(), args.File.Location);
                                }
                            }
                        }
                    }
                }
            }

            return(Task.CompletedTask);
        }
예제 #10
0
        public static List <Block> ApplyQuantization(List <Block> blocks)
        {
            WuQuantizer quantizer = new WuQuantizer();

            try
            {
                using (Bitmap bitmap = CreateBitmapFromColors(blocks))
                {
                    using (Image quantized = quantizer.QuantizeImage(bitmap))
                    {
                        Bitmap reducedBitmap = (Bitmap)quantized;
                        //Console.WriteLine(quantized.PixelFormat);
                        //Bitmap reducedBitmap = new Bitmap(quantized);
                        int width = reducedBitmap.Size.Width;
                        for (int i = 0; i < blocks.Count; i++)
                        {
                            int x = i % width;
                            int y = i / width;
                            blocks[i] = new Block(blocks[i].X, blocks[i].Y, blocks[i].Z,
                                                  reducedBitmap.GetPixel(x, y).ColorToUInt());
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            return(blocks);
        }
예제 #11
0
        private static void DownloadTile(Card card, FileInfo img)
        {
            Console.WriteLine($"Downloading missing image data for {card.Name} ({card.Id})");
            try
            {
                using (var wc = new WebClient())
                {
                    var    data = wc.DownloadData($"https://art.hearthstonejson.com/v1/tiles/{card.Id}.png");
                    Bitmap src;
                    using (var ms = new MemoryStream(data))
                        src = new Bitmap(new Bitmap(ms), 148, 34);
                    var crop   = new Rectangle(0, 0, 130, 34);
                    var target = new Bitmap(crop.Width, crop.Height);
                    using (var g = Graphics.FromImage(target))
                        g.DrawImage(src, crop, new Rectangle(src.Width - crop.Width - 4, 0, crop.Width, src.Height), GraphicsUnit.Pixel);

                    var quantizer = new WuQuantizer();
                    using (var quantized = quantizer.QuantizeImage(target, 0, 0))
                        quantized.Save(img.FullName, ImageFormat.Png);
                }
            }
            catch (WebException ex)
            {
                Console.WriteLine("Error! " + ex.Message);
            }
        }
예제 #12
0
        private void buttonConfirm_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog imageSave = new SaveFileDialog();

            imageSave.FileName   = "Compressed Image";
            imageSave.DefaultExt = ".png";
            imageSave.Filter     = "Image files (*.png)|*.png";
            if (imageSave.ShowDialog(this) == true)
            {
                labelStatus.Content    = "WORKING";
                labelStatus.Foreground = new SolidColorBrush(Colors.DarkCyan);
                try
                {
                    var quantizer = new WuQuantizer();
                    using (FileStream fs = new FileStream(imageLocation.Text, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan))
                        using (var bitmap = new Bitmap(fs))
                            using (var quantized = quantizer.QuantizeImage(bitmap))
                                using (FileStream ofs = new FileStream(imageSave.FileName, FileMode.Create, FileAccess.Write, FileShare.Read, 1024, FileOptions.WriteThrough))
                                {
                                    quantized.Save(ofs, ImageFormat.Png);
                                    ofs.Flush();
                                }
                    labelStatus.Content    = "FINISHED";
                    labelStatus.Foreground = new SolidColorBrush(Colors.Green);
                }
                catch (Exception ex)
                {
                    labelStatus.Content    = "FAILED";
                    labelStatus.Foreground = new SolidColorBrush(Colors.Red);
                    MessageBox.Show(this, ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
예제 #13
0
        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}");
        }
예제 #14
0
        /// <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);
            }
        }
예제 #15
0
        private static byte[] UseCastom(byte[] bytes)
        {
            Bitmap image          = ImageManager.ConvertByteToBitmap(bytes);
            string outputFileName = "nunit" + ".png";
            var    quantizer      = new WuQuantizer();

            try
            {
                var copy = new Bitmap(image);
                using (var quantized = quantizer.QuantizeImage(copy, 0, 1))
                {
                    quantized.Save(outputFileName, ImageFormat.Png);
                }
            }
            catch (QuantizationException ex)
            {
                Console.WriteLine(ex.Message);
                return(bytes);
            }

            byte[] outputBytes = ImageManager.ReadFromFileToByteArray(outputFileName);
            File.Delete(outputFileName);

            return(outputBytes);
        }
예제 #16
0
    private Bitmap SaveByReducingSize(Bitmap img1)
    {
        Bitmap res = null;

        try
        {
            ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Png);
            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
            EncoderParameters myEncoderParameters    = new EncoderParameters(1);
            EncoderParameter  myEncoderParameter     = new EncoderParameter(myEncoder, 20L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            var quantizer = new WuQuantizer();
            using (var quantized = quantizer.QuantizeImage(img1))
            {
                Stream stream = new MemoryStream();
                quantized.Save(stream, jgpEncoder, myEncoderParameters);
                res = (Bitmap)Image.FromStream(stream);
            }
            img1.Dispose();
            img1 = null;
        }
        catch (Exception exp)
        {
            Log("SaveByReducingSize", exp.Message, true, exp);
        }
        return(res);
    }
예제 #17
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));
            }
        }
        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);
                    }
                }
            }
        }
예제 #19
0
        /// <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);
                }
            }
        }
예제 #20
0
        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);
        }
예제 #21
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);
     }
 }
예제 #22
0
        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();
        }
예제 #23
0
        /// <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));
            }
        }
예제 #24
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);
                }
            }
        }
예제 #25
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);
                }
            }
        }
예제 #26
0
    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());
        }
    }
예제 #27
0
 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;
     }
 }
예제 #28
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);
        }
예제 #29
0
        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));
                    }
                }
            }
        }
예제 #30
0
        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;
            }
        }
예제 #31
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);
        }