Пример #1
0
        public void OctreeQuantizerCanCreateFrameQuantizer()
        {
            var quantizer = new OctreeQuantizer();
            IQuantizer <Rgba32> frameQuantizer = quantizer.CreatePixelSpecificQuantizer <Rgba32>(Configuration.Default);

            Assert.NotNull(frameQuantizer);
            Assert.NotNull(frameQuantizer.Options);
            Assert.Equal(QuantizerConstants.DefaultDither, frameQuantizer.Options.Dither);
            frameQuantizer.Dispose();

            quantizer = new OctreeQuantizer(new QuantizerOptions {
                Dither = null
            });
            frameQuantizer = quantizer.CreatePixelSpecificQuantizer <Rgba32>(Configuration.Default);

            Assert.NotNull(frameQuantizer);
            Assert.Null(frameQuantizer.Options.Dither);
            frameQuantizer.Dispose();

            quantizer = new OctreeQuantizer(new QuantizerOptions {
                Dither = KnownDitherings.Atkinson
            });
            frameQuantizer = quantizer.CreatePixelSpecificQuantizer <Rgba32>(Configuration.Default);
            Assert.NotNull(frameQuantizer);
            Assert.Equal(KnownDitherings.Atkinson, frameQuantizer.Options.Dither);
            frameQuantizer.Dispose();
        }
Пример #2
0
        /// <summary>
        /// Takes a Surface and quantizes it down to an 8-bit bitmap.
        /// </summary>
        /// <param name="quantizeMe">The Surface to quantize.</param>
        /// <param name="ditherAmount">How strong should dithering be applied. 0 for no dithering, 8 for full dithering. 7 is generally a good default to use.</param>
        /// <param name="maxColors">The maximum number of colors to use. This may range from 2 to 256.</param>
        /// <param name="enableTransparency">If true, then one color slot will be reserved for transparency. Any color with an alpha value less than 255 will be transparent in the output.</param>
        /// <param name="progressCallback">The progress callback delegate.</param>
        /// <returns>An 8-bit Bitmap that is the same size as quantizeMe.</returns>
        protected Bitmap Quantize(Surface quantizeMe, int ditherAmount, int maxColors, bool enableTransparency, ProgressEventHandler progressCallback)
        {
            if (ditherAmount < 0 || ditherAmount > 8)
            {
                throw new ArgumentOutOfRangeException(
                          "ditherAmount",
                          ditherAmount,
                          "Out of bounds. Must be in the range [0, 8]");
            }

            if (maxColors < 2 || maxColors > 256)
            {
                throw new ArgumentOutOfRangeException(
                          "maxColors",
                          maxColors,
                          "Out of bounds. Must be in the range [2, 256]");
            }

            // TODO: detect if transparency is needed? or take another argument

            using (Bitmap bitmap = quantizeMe.CreateAliasedBitmap(quantizeMe.Bounds, true))
            {
                OctreeQuantizer quantizer = new OctreeQuantizer(maxColors, enableTransparency);
                quantizer.DitherLevel = ditherAmount;
                Bitmap quantized = quantizer.Quantize(bitmap, progressCallback);
                return(quantized);
            }
        }
Пример #3
0
        /// <summary>
        /// Takes a Surface and quantizes it down to an 8-bit bitmap.
        /// </summary>
        /// <param name="quantizeMe">The Surface to quantize.</param>
        /// <param name="ditherAmount">How strong should dithering be applied. 0 for no dithering, 8 for full dithering.</param>
        /// <param name="maxColors">The maximum number of colors to use. This may range from 2 to 255.</param>
        /// <param name="progressCallback">The progress callback delegate.</param>
        /// <returns>An 8-bit Bitmap that is the same size as quantizeMe.</returns>
        protected Bitmap Quantize(Surface quantizeMe, int ditherAmount, int maxColors, ProgressEventHandler progressCallback)
        {
            if (ditherAmount < 0 || ditherAmount > 8)
            {
                throw new ArgumentOutOfRangeException(
                          "ditherAmount",
                          ditherAmount,
                          "Out of bounds. Must be in the range [0, 8]");
            }

            if (maxColors < 2 || maxColors > 255)
            {
                throw new ArgumentOutOfRangeException(
                          "maxColors",
                          maxColors,
                          "Out of bounds. Must be in the range [2, 255]");
            }

            using (Bitmap bitmap = quantizeMe.CreateAliasedBitmap(quantizeMe.Bounds, true))
            {
                OctreeQuantizer quantizer = new OctreeQuantizer(maxColors, 8);
                quantizer.DitherLevel = ditherAmount;
                Bitmap quantized = quantizer.Quantize(bitmap, progressCallback);
                return(quantized);
            }
        }
Пример #4
0
        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);
            }
        }
Пример #5
0
        public void OctreeQuantizerConstructor()
        {
            var expected = new QuantizerOptions {
                MaxColors = 128
            };
            var quantizer = new OctreeQuantizer(expected);

            Assert.Equal(expected.MaxColors, quantizer.Options.MaxColors);
            Assert.Equal(QuantizerConstants.DefaultDither, quantizer.Options.Dither);

            expected = new QuantizerOptions {
                Dither = null
            };
            quantizer = new OctreeQuantizer(expected);
            Assert.Equal(QuantizerConstants.MaxColors, quantizer.Options.MaxColors);
            Assert.Null(quantizer.Options.Dither);

            expected = new QuantizerOptions {
                Dither = KnownDitherings.Atkinson
            };
            quantizer = new OctreeQuantizer(expected);
            Assert.Equal(QuantizerConstants.MaxColors, quantizer.Options.MaxColors);
            Assert.Equal(KnownDitherings.Atkinson, quantizer.Options.Dither);

            expected = new QuantizerOptions {
                Dither = KnownDitherings.Atkinson, MaxColors = 0
            };
            quantizer = new OctreeQuantizer(expected);
            Assert.Equal(QuantizerConstants.MinColors, quantizer.Options.MaxColors);
            Assert.Equal(KnownDitherings.Atkinson, quantizer.Options.Dither);
        }
 private void RenderImage(Image image, Stream outStream)
 {
     try
     {
         if (this.ContentType == ImageFormat.Gif)
         {
             var quantizer = new OctreeQuantizer(255, 8);
             using (var quantized = quantizer.Quantize(image))
             {
                 quantized.Save(outStream, ImageFormat.Gif);
             }
         }
         else
         {
             var eps = new EncoderParameters(1)
             {
                 Param = { [0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, this.ImageCompression) },
             };
             var ici = GetEncoderInfo(GetImageMimeType(this.ContentType));
             image?.Save(outStream, ici, eps);
         }
     }
     finally
     {
         image?.Dispose();
     }
 }
Пример #7
0
        private void ReadPixels(string path)
        {
            var image     = path.SourceFrom();
            var pixelUtil = new PixelUtil(image);

            pixelUtil.LockBits();

            //if (QuantizationType == ColorQuantizationType.Grayscale)
            //{
            //    var quantizer = new GrayscaleQuantizer { MaxColors = MaximumNumberColor };
            //    IndexedPixels = quantizer.Quantize(pixelUtil.Pixels);
            //    ColorTable = quantizer.ColorTable;
            //}
            //else
            //{
            var quantizer = new OctreeQuantizer {
                MaxColors = MaximumNumberColor
            };

            IndexedPixels = quantizer.Quantize(pixelUtil.Pixels);
            ColorTable    = quantizer.ColorTable;
            //}

            pixelUtil.UnlockBits();
        }
Пример #8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="File"/> class.
 /// </summary>
 public File()
 {
     Frames    = new List <Frame>();
     Quantizer = new OctreeQuantizer {
         TransparencyThreshold = TransparencyThreshold
     };
     BitDepth = (int)Math.Ceiling(Math.Log(Quality, 2));
 }
Пример #9
0
 /// <summary>
 /// This method doesn't actually do anything but serves an important purpose...
 /// If you are running ImageSharp on iOS and try to call SaveAsGif, it will throw an exception:
 /// "Attempting to JIT compile method... OctreeFrameQuantizer.ConstructPalette... while running in aot-only mode."
 /// The reason this happens is the SaveAsGif method makes heavy use of generics, which are too confusing for the AoT
 /// compiler used on Xamarin.iOS. It spins up the JIT compiler to try and figure it out, but that is an illegal op on
 /// iOS so it bombs out.
 /// If you are getting the above error, you need to call this method, which will pre-seed the AoT compiler with the
 /// necessary methods to complete the SaveAsGif call. That's it, otherwise you should NEVER need this method!!!
 /// </summary>
 /// <typeparam name="TPixel">The pixel format.</typeparam>
 private static void AotCompileOctreeQuantizer <TPixel>()
     where TPixel : unmanaged, IPixel <TPixel>
 {
     using (var test = new OctreeQuantizer <TPixel>(Configuration.Default, new OctreeQuantizer().Options))
     {
         var frame = new ImageFrame <TPixel>(Configuration.Default, 1, 1);
         test.QuantizeFrame(frame, frame.Bounds());
     }
 }
Пример #10
0
        void RenderLoop()
        {
            renderer = MakeRenderer();
            using (MemoryStream ms = new MemoryStream()) {
                // loop terminates with the rest of the program (this is a background thread)
                while (true)
                {
                    // wait (block) until a map is available for drawing
                    RenderTask task = inQueue.WaitDequeue();
                    try {
                        // render the map
                        IsoCatResult result = renderer.Draw(task.Map);
                        task.Map = null;

                        // crop image (if needed)
                        Image image;
                        if (p.Uncropped)
                        {
                            image = result.Bitmap;
                        }
                        else
                        {
                            image = result.Bitmap.Clone(result.CropRectangle, result.Bitmap.PixelFormat);
                            result.Bitmap.Dispose();
                        }

                        // encode image
                        if (p.ExportFormat.Equals(ImageFormat.Jpeg))
                        {
                            EncoderParameters encoderParams = new EncoderParameters();
                            encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, p.JpegQuality);
                            image.Save(ms, p.ImageEncoder, encoderParams);
                        }
                        else if (p.ExportFormat.Equals(ImageFormat.Gif))
                        {
                            OctreeQuantizer q = new OctreeQuantizer(255, 8);
                            image = q.Quantize(image);
                            image.Save(ms, p.ExportFormat);
                        }
                        else
                        {
                            image.Save(ms, p.ExportFormat);
                        }
                        image.Dispose();

                        // store result as a byte[]
                        task.Result = ms.ToArray();
                    } catch (Exception ex) {
                        task.Exception = ex;
                    }

                    // send stack to the results queue
                    outQueue.Enqueue(task);
                    ms.SetLength(0);
                }
            }
        }
Пример #11
0
        public BuildInGifEncoder(string fileName, int width, int height)
            : base(fileName, width, height)
        {
            bWriter   = new BinaryWriter(File.Create(fileName));
            mStream   = new MemoryStream();
            quantizer = new OctreeQuantizer(255, 8);

            WriteHeader();
        }
Пример #12
0
        /// <summary>
        /// 把图像保存到GIF文件
        /// </summary>
        /// <param name="original">要保持的图片对象</param>
        /// <param name="fileName">保存的文件完整路径</param>
        /// <param name="maxColor">最大色彩,2-255</param>
        /// <param name="maxColors">最大色度,1-8</param>
        /// <param name="ditherAmount">位深,0-8</param>
        public static void SaveToGif(Bitmap original, string fileName, int maxColor, int maxColors, int ditherAmount)
        {
            OctreeQuantizer gifQuantizer = new OctreeQuantizer(maxColor, maxColors);

            gifQuantizer.DitherLevel = ditherAmount;
            Bitmap current = gifQuantizer.Quantize(original);

            current.Save(fileName, ImageFormat.Gif);
            current.Dispose();
        }
Пример #13
0
		/// <summary>
		/// Writes the specified images to the output stream
		/// </summary>
		/// <param name="images">The images.</param>
		/// <param name="imageStream"></param>
		/// <param name="outputFormat">The output format.</param>
		/// <param name="quality">The quality.</param>
		public void Write(IEnumerable<System.Drawing.Image> images, System.IO.Stream imageStream, ImageFormatType outputFormat, long quality)
		{
			if (images.Count() > 0)
			{
				OctreeQuantizer quantizer = new OctreeQuantizer(this.ColourDepth - 1, 8);

				Bitmap quantized = quantizer.Quantize(images.First());
				quantized.Save(imageStream, ImageFormat.Gif);
			}
		}
Пример #14
0
        /// <summary>
        /// Writes the specified images to the output stream
        /// </summary>
        /// <param name="images">The images.</param>
        /// <param name="imageStream"></param>
        /// <param name="outputFormat">The output format.</param>
        /// <param name="quality">The quality.</param>
        public void Write(IEnumerable <System.Drawing.Image> images, System.IO.Stream imageStream, ImageFormatType outputFormat, long quality)
        {
            if (images.Count() > 0)
            {
                OctreeQuantizer quantizer = new OctreeQuantizer(this.ColourDepth - 1, 8);

                Bitmap quantized = quantizer.Quantize(images.First());
                quantized.Save(imageStream, ImageFormat.Gif);
            }
        }
Пример #15
0
        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);
        }
Пример #16
0
                internal OctreeNode(int level, OctreeQuantizer parent)
                {
                    this.parent = parent;
                    Debug.Assert(level < parent.bpp);

                    if (level >= 0)
                    {
                        parent.levels[level].Add(this);
                    }
                }
        public void Save(Stream stream)
        {
            var myGraphics = GraphicsConstructer((Bitmap)SourceImage);
            var quantizer  = new OctreeQuantizer(255, 8);
            var quantized  = quantizer.Quantize(SourceImage);

            quantized.Save(stream, ImageFormat.Gif);

            // clean up...
            quantized.Dispose();
            myGraphics.Dispose();
        }
Пример #18
0
        /// <summary>
        /// Converts Bitmap images to XPM data for use with ScintillaNet.
        /// Warning: images with more than (around) 50 colors will generate incorrect XPM
        /// tColor: specified transparent color in format: "#00FF00".
        /// </summary>
        static public string ConvertToXPM(Bitmap bmp, string tColor)
        {
            StringBuilder sb     = new StringBuilder();
            ArrayList     colors = new ArrayList();
            ArrayList     chars  = new ArrayList();

            OctreeQuantizer quantizer  = new OctreeQuantizer(50, 8, ColorTranslator.FromHtml(tColor));
            Bitmap          reducedBmp = quantizer.Quantize(bmp);

            int width  = reducedBmp.Width;
            int height = reducedBmp.Height;
            int index;

            sb.Append("/* XPM */static char * xmp_data[] = {\"").Append(width).Append(" ").Append(height).Append(" ? 1\"");
            int    colorsIndex = sb.Length;
            string col;
            char   c;

            for (int y = 0; y < height; y++)
            {
                sb.Append(",\"");
                for (int x = 0; x < width; x++)
                {
                    col   = ColorTranslator.ToHtml(reducedBmp.GetPixel(x, y));
                    index = colors.IndexOf(col);
                    if (index < 0)
                    {
                        index = colors.Add(col) + 65;
                        if (index > 90)
                        {
                            index += 6;
                        }
                        c = Encoding.ASCII.GetChars(new byte[] { (byte)(index & 0xff) })[0];
                        chars.Add(c);
                        sb.Insert(colorsIndex, ",\"" + c + " c " + col + "\"");
                        colorsIndex += 14;
                    }
                    else
                    {
                        c = (char)chars[index];
                    }
                    sb.Append(c);
                }
                sb.Append("\"");
            }
            sb.Append("};");
            string result     = sb.ToString();
            int    p          = result.IndexOf("?");
            string finalColor = result.Substring(0, p) + colors.Count + result.Substring(p + 1).Replace(tColor.ToUpper(), "None");

            return(finalColor);
        }
Пример #19
0
 public void Save(Stream stream, ImageFormat format)
 {
     if (format == ImageFormat.Gif)
     {
         var quantizer = new OctreeQuantizer(255, 8);
         var gif       = quantizer.Quantize(Control);
         gif.Save(stream, format.ToSD());
     }
     else
     {
         Control.Save(stream, format.ToSD());
     }
 }
Пример #20
0
 public void Save(Stream stream, ImageFormat format)
 {
     if (format == ImageFormat.Gif)
     {
         var quantizer = new OctreeQuantizer(255, 8);
         var yummygif  = quantizer.Quantize(Control);
         yummygif.Save(stream, Generator.Convert(format));
     }
     else
     {
         Control.Save(stream, Generator.Convert(format));
     }
 }
Пример #21
0
        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);
        }
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="processor">
        /// The processor.
        /// </param>
        /// <param name="factory">
        /// The factory.
        /// </param>
        private static void ApplyProcessor(Func <ImageFactory, Image> processor, ImageFactory factory)
        {
            ImageInfo imageInfo = factory.Image.GetImageInfo(factory.ImageFormat);

            if (imageInfo.IsAnimated)
            {
                OctreeQuantizer quantizer = new OctreeQuantizer(255, 8);

                // We don't dispose of the memory stream as that is disposed when a new image is created and doing so
                // beforehand will cause an exception.
                MemoryStream stream = new MemoryStream();
                using (GifEncoder encoder = new GifEncoder(stream, null, null, imageInfo.LoopCount))
                {
                    foreach (GifFrame frame in imageInfo.GifFrames)
                    {
                        factory.Update(frame.Image);
                        frame.Image = quantizer.Quantize(processor.Invoke(factory));
                        encoder.AddFrame(frame);
                    }
                }

                stream.Position = 0;
                factory.Update(Image.FromStream(stream));
            }
            else
            {
                factory.Update(processor.Invoke(factory));
            }

            // Set the property item information from any Exif metadata.
            // We do this here so that they can be changed between processor methods.
            if (factory.PreserveExifData)
            {
                foreach (KeyValuePair <int, PropertyItem> propertItem in factory.ExifPropertyItems)
                {
                    try
                    {
                        factory.Image.SetPropertyItem(propertItem.Value);
                    }
                    // ReSharper disable once EmptyGeneralCatchClause
                    catch
                    {
                        // Do nothing. The image format does not handle EXIF data.
                        // TODO: empty catch is fierce code smell.
                    }
                }
            }
        }
Пример #23
0
 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);
 }
Пример #24
0
 public void MaxColoursTooSmall()
 {
     ReportStart();
     try
     {
         _oq = new OctreeQuantizer(0, 8);
     }
     catch (ArgumentOutOfRangeException ex)
     {
         string message = "The number of colours should be between 1 and 255";
         StringAssert.Contains(message, ex.Message);
         Assert.AreEqual("maxColours", ex.ParamName);
         Assert.AreEqual(0, ex.ActualValue);
         ReportEnd();
         throw;
     }
 }
Пример #25
0
        /// <summary>
        /// Writes an image to the file name specified
        /// </summary>
        /// <param name="originalImage">Image to write</param>
        /// <param name="fileName">File to write to</param>
        /// <param name="desiredWidth">Desired width of the image</param>
        /// <param name="desiredHeight">Desired height of the image</param>
        /// <param name="maintainAspectRatio">If <b>true</b> aspect ratio is maintained while resizing</param>
        /// <param name="quality">Quality of the image in percent</param>
        public static void WriteImageFile(Image originalImage, string fileName, int desiredWidth, int desiredHeight, bool maintainAspectRatio, int quality)
        {
            //GET RESIZE DIMENSIONS
            int resizeWidth, resizeHeight;

            FileHelper.GetResizeInfo(originalImage.Width, originalImage.Height, desiredWidth, desiredHeight, maintainAspectRatio, out resizeWidth, out resizeHeight);
            //GENERATE IMAGE OF APPROPRIATE SIZE
            using (System.Drawing.Image resizedImage = GetResizedImage(originalImage, resizeWidth, resizeHeight))
            {
                if (resizedImage != null)
                {
                    string extension = Path.GetExtension(fileName).ToLowerInvariant();
                    switch (extension)
                    {
                    case ".png":
                        resizedImage.Save(fileName, ImageFormat.Png);
                        break;

                    case ".gif":
                        if (Misc.HasUnmanagedCodePermission())
                        {
                            //QUANTIZE GIF IMAGES
                            OctreeQuantizer quantizer = new OctreeQuantizer(255, 8);
                            using (Image quantized = quantizer.Quantize(resizedImage))
                            {
                                quantized.Save(fileName, ImageFormat.Gif);
                                quantized.Dispose();
                            }
                        }
                        else
                        {
                            resizedImage.Save(fileName, ImageFormat.Gif);
                        }
                        break;

                    case ".bmp":
                        resizedImage.Save(fileName, ImageFormat.Bmp);
                        break;

                    default:
                        SaveJPGWithCompressionSetting(resizedImage, fileName, (long)quality);
                        break;
                    }
                }
            }
        }
Пример #26
0
        /// <summary>
        /// 把图像保存到Png文件
        /// </summary>
        /// <param name="original">要保持的图片对象</param>
        /// <param name="fileName">保存的文件完整路径</param>
        /// <param name="maxColor">最大色彩,2-255</param>
        /// <param name="maxColors">最大色度,1-8</param>
        /// <param name="ditherAmount">平滑,0-8</param>
        public static void SaveToPng(Bitmap original, string fileName, int maxColor, int maxColors, int ditherAmount)
        {
            Color color = original.GetPixel(0, 0);

            if (color.ToArgb() == 0 && color.Name == "0")
            {
                OctreeQuantizer quantizer = new OctreeQuantizer(maxColor, maxColors);
                quantizer.DitherLevel = ditherAmount;
                Bitmap            target    = quantizer.Quantize(original);
                ImageCodecInfo[]  codes     = ImageCodecInfo.GetImageEncoders();
                EncoderParameters encParam  = new EncoderParameters(1);
                EncoderParameter  interlace = new EncoderParameter(Encoder.ScanMethod, (byte)(EncoderValue.ScanMethodInterlaced));
                encParam.Param[0] = interlace;
                target.Save(fileName, codes[4], encParam);
                target.Dispose();
            }
            else
            {
                string          obit      = original.PixelFormat.ToString();
                string          _path     = fileName.Substring(0, fileName.LastIndexOf("."));
                string          tmpGif    = _path + ".gif";
                string          tmpBmp    = _path + ".bmp";
                OctreeQuantizer quantizer = new OctreeQuantizer(maxColor, maxColors);
                quantizer.DitherLevel = ditherAmount;
                Bitmap bm_gif = quantizer.Quantize(original);
                bm_gif.Save(tmpGif, ImageFormat.Gif);
                bm_gif.Dispose();

                File.Copy(tmpGif, fileName, true);
                File.Delete(tmpGif);

                Image image = Image.FromFile(fileName);
                image.Save(tmpBmp, ImageFormat.Bmp);
                image.Dispose();

                ImageCodecInfo[]  codes     = ImageCodecInfo.GetImageEncoders();
                EncoderParameters encParam  = new EncoderParameters(1);
                EncoderParameter  interlace = new EncoderParameter(Encoder.ScanMethod, (byte)(EncoderValue.ScanMethodInterlaced));
                encParam.Param[0] = interlace;
                Image img = Image.FromFile(tmpBmp);
                File.Delete(fileName);
                img.Save(fileName, codes[4], encParam);
                img.Dispose();
                File.Delete(tmpBmp);
            }
        }
Пример #27
0
        //The methods shows how to use FlexCelImgExport the "hard way", without using SaveAsImage.
        //For normal operation you should only need to call SaveAsImage, but you could use the code here
        //if you need to customize the ImgExport output, or if you need to get all the images as different files.
        private void CreateImg(Stream OutStream, FlexCelImgExport ImgExport, ImageFormat ImgFormat, ImageColorDepth Colors, ref TImgExportInfo ExportInfo)
        {
            TPaperDimensions pd = ImgExport.GetRealPageSize();

            PixelFormat RgbPixFormat = Colors != ImageColorDepth.TrueColor ? PixelFormat.Format32bppPArgb : PixelFormat.Format24bppRgb;
            PixelFormat PixFormat    = PixelFormat.Format1bppIndexed;

            switch (Colors)
            {
            case ImageColorDepth.TrueColor: PixFormat = RgbPixFormat; break;

            case ImageColorDepth.Color256: PixFormat = PixelFormat.Format8bppIndexed; break;
            }

            using (Bitmap OutImg = CreateBitmap(ImgExport.Resolution, pd, PixFormat))
            {
                Bitmap ActualOutImg = Colors != ImageColorDepth.TrueColor ? CreateBitmap(ImgExport.Resolution, pd, RgbPixFormat) : OutImg;
                try
                {
                    using (Graphics Gr = Graphics.FromImage(ActualOutImg))
                    {
                        Gr.FillRectangle(Brushes.White, 0, 0, ActualOutImg.Width, ActualOutImg.Height); //Clear the background
                        ImgExport.ExportNext(Gr, ref ExportInfo);
                    }

                    if (Colors == ImageColorDepth.BlackAndWhite)
                    {
                        FloydSteinbergDither.ConvertToBlackAndWhite(ActualOutImg, OutImg);
                    }
                    else
                    if (Colors == ImageColorDepth.Color256)
                    {
                        OctreeQuantizer.ConvertTo256Colors(ActualOutImg, OutImg);
                    }
                }
                finally
                {
                    if (ActualOutImg != OutImg)
                    {
                        ActualOutImg.Dispose();
                    }
                }

                OutImg.Save(OutStream, ImgFormat);
            }
        }
Пример #28
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);
        }
Пример #29
0
 public void MaxColourBitsTooLarge()
 {
     ReportStart();
     try
     {
         _oq = new OctreeQuantizer(10, 9);
     }
     catch (ArgumentOutOfRangeException ex)
     {
         string message = "This should be between 1 and 8";
         StringAssert.Contains(message, ex.Message);
         Assert.AreEqual("maxColourBits", ex.ParamName);
         Assert.AreEqual(9, ex.ActualValue);
         ReportEnd();
         throw;
     }
 }
Пример #30
0
        public void OctreeQuantizerYieldsCorrectTransparentPixel <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 OctreeQuantizer(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]);
                }
            }
        }
 private void RenderImage(Image image, Stream outStream)
 {
     if (ContentType == ImageFormat.Gif)
     {
         var quantizer = new OctreeQuantizer(255, 8);
         using (var quantizedBitmap = quantizer.Quantize(image))
         {
             quantizedBitmap.Save(outStream, ImageFormat.Gif);
         }
     }
     else
     {
         var encParams = new EncoderParameters(1);
         encParams.Param [0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Settings.ImageCompression);
         ImageCodecInfo ici = Utils.GetEncoderInfo(Utils.GetImageMimeType(ContentType));
         image.Save(outStream, ici, encParams);
     }
 }
Пример #32
0
 static void SaveImage(Bitmap image, string targetFileName)
 {
     if (exportFormat.Equals(ImageFormat.Jpeg))
     {
         EncoderParameters encoderParams = new EncoderParameters();
         encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, jpegQuality);
         image.Save(targetFileName, imageEncoder, encoderParams);
     }
     else if (exportFormat.Equals(ImageFormat.Gif))
     {
         OctreeQuantizer q = new OctreeQuantizer(255, 8);
         image = q.Quantize(image);
         image.Save(targetFileName, exportFormat);
     }
     else
     {
         image.Save(targetFileName, exportFormat);
     }
 }
Пример #33
0
        //  max_width   100% 50% 
        //  x   "center" "0" "width"
        public static MemoryStream PaintText(
            string strSourceFileName,
            string strText,
            TextInfo info,
            string s_x,
            string s_y,
            string s_max_width,
            string s_max_height,
            ImageFormat imageformat)
        {
            SizeF size;

            Image source = Image.FromFile(strSourceFileName);

            int width = source.Width;
            int height = source.Height;

            int x = 0;

            if (s_x != "center")
                x = GetValue(s_x,
                 width,
                 width,
                 height);

            int y = GetValue(s_y,
    height,
    width,
    height);
            int max_width = GetValue(s_max_width,
    width,
    width,
    height);
            int max_height = GetValue(s_max_height,
height,
width,
height);

            Font font = null;

            using (Bitmap bitmapTemp = new Bitmap(1, 1))
            {

                Graphics graphicsTemp = Graphics.FromImage(bitmapTemp);

                int text_height = (int)((float)max_height * 0.8);
                // 第一次测算,按照最大高度
                font = new Font(info.FontFace, text_height, info.fontstyle, GraphicsUnit.Pixel);

                    size = graphicsTemp.MeasureString(
                        strText,
                        font);

                    int width_delta = (int)size.Width - max_width;
                    if (width_delta > 0)
                    {
                        int nFontHeight = (int)((float)text_height * ((float)max_width / size.Width));
                        font = new Font(info.FontFace, nFontHeight, info.fontstyle, GraphicsUnit.Pixel);
                        y += (text_height - nFontHeight) / 2;
                    }



                if ((info.effect & ArtEffect.Shadow) == ArtEffect.Shadow)
                {
                    size.Height += 2;
                    size.Width += 2;
                }
            }


            // 正式的图像
            Bitmap bitmapDest = new Bitmap(
                source.Width,   //                (int)size.Width + 1,
                Math.Max(source.Height, y + max_height),  // (int)size.Height + 1,
                PixelFormat.Format64bppPArgb);

            try
            {

                Graphics objGraphics = Graphics.FromImage(bitmapDest);

                objGraphics.Clear(info.colorBack);// Color.Transparent

                objGraphics.DrawImageUnscaled(source, new Point(0, 0));


                // 
                objGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                // System.Drawing.Text.TextRenderingHint oldrenderhint = objGraphics.TextRenderingHint;
                //设置高质量,低速度呈现平滑程度 
                objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

                StringFormat stringFormat = new StringFormat();

                if (s_x == "center")
                {
                    stringFormat.Alignment = StringAlignment.Center;
                    x = 0;
                    size.Width = source.Width;
                }
                else
                    stringFormat.Alignment = StringAlignment.Near;


                // Color.FromArgb(128, 100, 100, 100)
                SolidBrush objBrush = new SolidBrush(info.colorText); // 透明颜色 ' Color.Black
                RectangleF rect = new RectangleF(x,
                    y, 
                    size.Width, size.Height);

                if ((info.effect & ArtEffect.Shadow) == ArtEffect.Shadow)
                {
                    SolidBrush objBrushShadow = new SolidBrush(info.colorShadow);
                    RectangleF rectShadow = new RectangleF(rect.X,
                        rect.Y, rect.Width, rect.Height);
                    rectShadow.Offset(2, 2);
                    objGraphics.DrawString(strText,
                        font,
                        objBrushShadow,
                        rectShadow,
                        stringFormat);
                }

                objGraphics.DrawString(strText,
                    font,
                    objBrush,
                    rect,
                    stringFormat);

                MemoryStream stream = new MemoryStream();

                /*

                stream = SaveGIFWithNewColorTable(
                    bitmapDest,
                    256,
                    true);
                 */


                if (imageformat == ImageFormat.Gif)
                {
                    bitmapDest.MakeTransparent(
                    info.colorBack);

                    OctreeQuantizer quantizer = new OctreeQuantizer(255, 8);
                    quantizer.TransparentColor = info.colorBack;

                    using (Bitmap quantized = quantizer.Quantize(bitmapDest))
                    {
                        quantized.Save(stream, imageformat);
                    }
                }
                else
                {
                    bitmapDest.Save(stream, imageformat);   // System.Drawing.Imaging.ImageFormat.Jpeg
                }

                return stream;
            }
            finally
            {
                bitmapDest.Dispose();
            }
        }
Пример #34
0
        // parameters:
        //      nWidth  控制折行的位置
        public static MemoryStream BuildArtText(
            string strText,
            string strFontFace,
            float fFontSize,
            FontStyle fontstyle,
            Color colorText,
            Color colorBack,
            Color colorShadow,
            ArtEffect effect,
            ImageFormat imageformat,
            int nWidth = 500)
        {
            Bitmap bitmapTemp = new Bitmap(1, 1);
            SizeF size;
            Font font = new Font(strFontFace, fFontSize, fontstyle);

            try
            {
                Graphics graphicsTemp = Graphics.FromImage(bitmapTemp);

                size = graphicsTemp.MeasureString(
                    strText,
                    font,
                    nWidth);

                if ((effect & ArtEffect.Shadow) == ArtEffect.Shadow)
                {
                    size.Height += 2;
                    size.Width += 2;
                }
            }
            finally
            {
                bitmapTemp.Dispose();
                bitmapTemp = null;
            }

            // 正式的图像
            Bitmap bitmapDest = new Bitmap((int)size.Width + 1, (int)size.Height + 1, PixelFormat.Format64bppPArgb);

            try
            {

                Graphics objGraphics = Graphics.FromImage(bitmapDest);

                // colorBack = Color.FromArgb(0, colorBack);
                objGraphics.Clear(colorBack);// Color.Transparent

                // 
                objGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                // System.Drawing.Text.TextRenderingHint oldrenderhint = objGraphics.TextRenderingHint;
                //设置高质量,低速度呈现平滑程度 
                objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
                // objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;

                StringFormat stringFormat = new StringFormat();

                /*
                // 随机产生一个倾斜角度
                Random random = new Random(unchecked((int)DateTime.Now.Ticks));
                int angle = random.Next(-10, 10);

                objGraphics.RotateTransform(angle);
                 */

                stringFormat.Alignment = StringAlignment.Near;
                /*
                if (angle > 0)
                    stringFormat.LineAlignment = StringAlignment.Near;
                else
                    stringFormat.LineAlignment = StringAlignment.Far;
                 */



                // Color.FromArgb(128, 100, 100, 100)
                SolidBrush objBrush = new SolidBrush(colorText); // 透明颜色 ' Color.Black
                RectangleF rect = new RectangleF(0, 0, size.Width, size.Height);

                if ((effect & ArtEffect.Shadow) == ArtEffect.Shadow)
                {
                    SolidBrush objBrushShadow = new SolidBrush(colorShadow);
                    RectangleF rectShadow = new RectangleF(rect.X,
                        rect.Y, rect.Width, rect.Height);
                    rectShadow.Offset(2, 2);
                    objGraphics.DrawString(strText,
                        font,
                        objBrushShadow,
                        rectShadow,
                        stringFormat);
                }

                objGraphics.DrawString(strText,
                    font,
                    objBrush,
                    rect,
                    stringFormat);

                MemoryStream stream = new MemoryStream();

                /*

                stream = SaveGIFWithNewColorTable(
                    bitmapDest,
                    256,
                    true);
                 */
                if (imageformat == ImageFormat.Png
                    && colorBack == Color.Transparent)
                {
                    bitmapDest.MakeTransparent(colorBack);
                }

                if (imageformat == ImageFormat.Gif)
                {
                    bitmapDest.MakeTransparent(
                    colorBack);

                    OctreeQuantizer quantizer = new OctreeQuantizer(255, 8);
                    quantizer.TransparentColor = colorBack;

                    using (Bitmap quantized = quantizer.Quantize(bitmapDest))
                    {
                        quantized.Save(stream, imageformat);
                    }
                }
                else
                {
                    bitmapDest.Save(stream, imageformat);   // System.Drawing.Imaging.ImageFormat.Jpeg
                }

                return stream;
            }
            finally
            {
                bitmapDest.Dispose();
            }
        }
Пример #35
0
        // 2016/10/5 改造为利用下级 Bitmap 函数
        // parameters:
        //      nWidth  控制折行的位置
        public static MemoryStream BuildArtText(
            string strText,
            string strFontFace,
            float fFontSize,
            FontStyle fontstyle,
            Color colorText,
            Color colorBack,
            Color colorShadow,
            ArtEffect effect,
            ImageFormat imageformat,
            int nWidth = 500)
        {
            // 正式的图像
            using (Bitmap bitmapDest = BuildArtText(strText,
                strFontFace,
                fFontSize,
                fontstyle,
                colorText,
                colorBack,
                colorShadow,
                effect,
                nWidth))
            {
                MemoryStream stream = new MemoryStream();

                if (imageformat == ImageFormat.Png
                    && colorBack == Color.Transparent)
                {
                    bitmapDest.MakeTransparent(colorBack);
                }

                if (imageformat == ImageFormat.Gif)
                {
                    bitmapDest.MakeTransparent(
                    colorBack);

                    OctreeQuantizer quantizer = new OctreeQuantizer(255, 8);
                    quantizer.TransparentColor = colorBack;

                    using (Bitmap quantized = quantizer.Quantize(bitmapDest))
                    {
                        quantized.Save(stream, imageformat);
                    }
                }
                else
                {
                    bitmapDest.Save(stream, imageformat);   // System.Drawing.Imaging.ImageFormat.Jpeg
                }

                return stream;
            }
        }