Class GifOptions

Class GifOptions

Название пространства: Aspose.Imaging.ImageOptions Ассоциация: Aspose.Imaging.dll (25.4.0)

API for Graphical Interchange Format (GIF) предлагает создание файлов изображенияразработчики всесторонних вариантов для создания изображений GIF с точностьюс функциями для настройки цвета фонов, цветовой палиты, разрешения,межсвязанный тип, прозрачный цвет, метаданный контейнер XMP и изображениекомпрессия, это API обеспечивает гибкость и эффективность в создании оптимизированнойи визуально привлекательные GIF, адаптированные к конкретным требованиям применения.

[JsonObject(MemberSerialization.OptIn)]
public class GifOptions : ImageOptionsBase, IDisposable, IHasXmpData, IHasMetadata, ICloneable

Inheritance

object DisposableObject ImageOptionsBase GifOptions

Implements

IDisposable , IHasXmpData , IHasMetadata , ICloneable

Наследованные члены

ImageOptionsBase.Clone() , ImageOptionsBase.ReleaseManagedResources() , ImageOptionsBase.KeepMetadata , ImageOptionsBase.XmpData , ImageOptionsBase.Source , ImageOptionsBase.Palette , ImageOptionsBase.ResolutionSettings , ImageOptionsBase.VectorRasterizationOptions , ImageOptionsBase.BufferSizeHint , ImageOptionsBase.MultiPageOptions , ImageOptionsBase.FullFrame , ImageOptionsBase.ProgressEventHandler , DisposableObject.Dispose() , DisposableObject.ReleaseManagedResources() , DisposableObject.ReleaseUnmanagedResources() , DisposableObject.VerifyNotDisposed() , DisposableObject.Disposed , object.GetType() , object.MemberwiseClone() , object.ToString() , object.Equals(object?) , object.Equals(object?, object?) , object.ReferenceEquals(object?, object?) , object.GetHashCode()

Examples

Этот пример показывает использование различных классов из SaveOptions Namespace для экспорта. изображение типа Gif загружается в примере изображения, а затем экспортируется в несколько форматов.

string dir = "c:\\temp\\";

                                                                                                                                                                                                                    //Load an existing image (of type Gif) in an instance of Image class
                                                                                                                                                                                                                    using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                                                                                                                                                    {
                                                                                                                                                                                                                        //Export to BMP file format using the default options
                                                                                                                                                                                                                        image.Save(dir + "output.bmp", new Aspose.Imaging.ImageOptions.BmpOptions());

                                                                                                                                                                                                                        //Export to JPEG file format using the default options
                                                                                                                                                                                                                        image.Save(dir + "output.jpg", new Aspose.Imaging.ImageOptions.JpegOptions());

                                                                                                                                                                                                                        //Export to PNG file format using the default options
                                                                                                                                                                                                                        image.Save(dir + "output.png", new Aspose.Imaging.ImageOptions.PngOptions());

                                                                                                                                                                                                                        //Export to TIFF file format using the default options
                                                                                                                                                                                                                        image.Save(dir + "output.tif", new Aspose.Imaging.ImageOptions.TiffOptions(Aspose.Imaging.FileFormats.Tiff.Enums.TiffExpectedFormat.Default));
                                                                                                                                                                                                                    }

Следующий пример показывает, как конвертировать мультистраничную векторную картину в формат GIF в целом без ссылки на конкретный тип изображения.

string dir = "C:\\aspose.imaging\\net\\misc\\ImagingReleaseQATester\\Tests\\testdata\\2548";
                                                                                                                                                           string inputFilePath = System.IO.Path.Combine(dir, "Multipage.cdr");
                                                                                                                                                           string outputFilePath = System.IO.Path.Combine(dir, "Multipage.cdr.gif");

                                                                                                                                                           Aspose.Imaging.ImageOptionsBase exportOptions = new Aspose.Imaging.ImageOptions.GifOptions();

                                                                                                                                                           using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(inputFilePath))
                                                                                                                                                           {
                                                                                                                                                               exportOptions.MultiPageOptions = null;

                                                                                                                                                               // Export only first two pages. These pages will be presented as animated frames in the output GIF.
                                                                                                                                                               Aspose.Imaging.IMultipageImage multipageImage = image as Aspose.Imaging.IMultipageImage;
                                                                                                                                                               if (multipageImage != null && (multipageImage.Pages != null && multipageImage.PageCount > 2))
                                                                                                                                                               {
                                                                                                                                                                   exportOptions.MultiPageOptions = new Aspose.Imaging.ImageOptions.MultiPageOptions(new Aspose.Imaging.IntRange(0, 2));
                                                                                                                                                               }

                                                                                                                                                               if (image is Aspose.Imaging.VectorImage)
                                                                                                                                                               {
                                                                                                                                                                   exportOptions.VectorRasterizationOptions = (Aspose.Imaging.ImageOptions.VectorRasterizationOptions)image.GetDefaultOptions(new object[] { Aspose.Imaging.Color.White, image.Width, image.Height });
                                                                                                                                                                   exportOptions.VectorRasterizationOptions.TextRenderingHint = Aspose.Imaging.TextRenderingHint.SingleBitPerPixel;
                                                                                                                                                                   exportOptions.VectorRasterizationOptions.SmoothingMode = Aspose.Imaging.SmoothingMode.None;
                                                                                                                                                               }

                                                                                                                                                               image.Save(outputFilePath, exportOptions);
                                                                                                                                                           }

Этот пример показывает, как загрузить информацию Pixel в Array of Type Color, манипулировать array и вернуть ее обратно к изображению. Для выполнения этих операций, этот пример создает новый файл Image (в формате GIF) uisng MemoryStream объект.

//Create an instance of MemoryStream
                                                                                                                                                                                                                                                         using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                                                                                                                                                                                                                                                         {
                                                                                                                                                                                                                                                             //Create an instance of GifOptions and set its various properties including the Source property
                                                                                                                                                                                                                                                             Aspose.Imaging.ImageOptions.GifOptions gifOptions = new Aspose.Imaging.ImageOptions.GifOptions();
                                                                                                                                                                                                                                                             gifOptions.Source = new Aspose.Imaging.Sources.StreamSource(stream);

                                                                                                                                                                                                                                                             //Create an instance of Image
                                                                                                                                                                                                                                                             using (Aspose.Imaging.RasterImage image = (Aspose.Imaging.RasterImage)Aspose.Imaging.Image.Create(gifOptions, 500, 500))
                                                                                                                                                                                                                                                             {
                                                                                                                                                                                                                                                                 //Get the pixels of image by specifying the area as image boundary
                                                                                                                                                                                                                                                                 Aspose.Imaging.Color[] pixels = image.LoadPixels(image.Bounds);

                                                                                                                                                                                                                                                                 //Loop over the Array and sets color of alrenative indexed pixel
                                                                                                                                                                                                                                                                 for (int index = 0; index < pixels.Length; index++)
                                                                                                                                                                                                                                                                 {
                                                                                                                                                                                                                                                                     if (index % 2 == 0)
                                                                                                                                                                                                                                                                     {
                                                                                                                                                                                                                                                                         //Set the indexed pixel color to yellow
                                                                                                                                                                                                                                                                         pixels[index] = Aspose.Imaging.Color.Yellow;
                                                                                                                                                                                                                                                                     }
                                                                                                                                                                                                                                                                     else
                                                                                                                                                                                                                                                                     {
                                                                                                                                                                                                                                                                         //Set the indexed pixel color to blue
                                                                                                                                                                                                                                                                         pixels[index] = Aspose.Imaging.Color.Blue;
                                                                                                                                                                                                                                                                     }
                                                                                                                                                                                                                                                                 }

                                                                                                                                                                                                                                                                 //Apply the pixel changes to the image
                                                                                                                                                                                                                                                                 image.SavePixels(image.Bounds, pixels);

                                                                                                                                                                                                                                                                 // save all changes.
                                                                                                                                                                                                                                                                 image.Save();
                                                                                                                                                                                                                                                             }

                                                                                                                                                                                                                                                             // Write MemoryStream to File
                                                                                                                                                                                                                                                             using (System.IO.FileStream fileStream = new System.IO.FileStream(@"C:\temp\output.gif", System.IO.FileMode.Create))
                                                                                                                                                                                                                                                             {
                                                                                                                                                                                                                                                                 stream.WriteTo(fileStream);
                                                                                                                                                                                                                                                             }   
                                                                                                                                                                                                                                                         }

Constructors

GifOptions()

Инициализует новую инстанцию класса Aspose.Imaging.ImageOptions.GifOption.

[JsonConstructor]
public GifOptions()

GifOptions(GifOptions)

Инициализует новую инстанцию класса Aspose.Imaging.ImageOptions.GifOption.

public GifOptions(GifOptions gifOptions)

Parameters

gifOptions GifOptions

Опции для GIF.

Properties

BackgroundColor

Получает или устанавливает цвет фонов.

[JsonProperty]
public Color BackgroundColor { get; set; }

Стоимость недвижимости

Color

BackgroundColorIndex

Получить или установить индекс цветов фонов GIF.

public byte BackgroundColorIndex { get; set; }

Стоимость недвижимости

byte

ColorResolution

Получает или устанавливает цветную резолюцию GIF.

public byte ColorResolution { get; set; }

Стоимость недвижимости

byte

Examples

Этот пример показывает, как сохранить изображение BMP в формате GIF с помощью различных вариантов.

string dir = "c:\\temp\\";

                                                                                          using (Aspose.Imaging.Image bmpImage = new Aspose.Imaging.FileFormats.Bmp.BmpImage(1000, 1000))
                                                                                          {
                                                                                              // Fill the entire image with the blue-yellow gradient.
                                                                                              Aspose.Imaging.Brushes.LinearGradientBrush gradientBrush = new Aspose.Imaging.Brushes.LinearGradientBrush(
                                                                                                      new Aspose.Imaging.Point(0, 0),
                                                                                                      new Aspose.Imaging.Point(bmpImage.Width, bmpImage.Height),
                                                                                                      Aspose.Imaging.Color.Blue,
                                                                                                      Aspose.Imaging.Color.Yellow);

                                                                                              Aspose.Imaging.Graphics graphics = new Aspose.Imaging.Graphics(bmpImage);
                                                                                              graphics.FillRectangle(gradientBrush, bmpImage.Bounds);

                                                                                              Aspose.Imaging.ImageOptions.GifOptions saveOptions = new Aspose.Imaging.ImageOptions.GifOptions();

                                                                                              // The number of bits required to store a color, minus 1.
                                                                                              saveOptions.ColorResolution = 7;

                                                                                              // Palette correction means that whenever image is exported to GIF the source image colors will be analyzed
                                                                                              // in order to build the best matching palette (in case image Palette does not exist or not specified in the options)
                                                                                              saveOptions.DoPaletteCorrection = true;

                                                                                              // Load a GIF image in a progressive way.
                                                                                              // An interlaced GIF doesn't display its scanlines linearly from top to bottom, but instead reorders it
                                                                                              // so the content of the GIF becomes clear even before it finishes loading.
                                                                                              saveOptions.Interlaced = true;

                                                                                              // Save as a lossless GIF.
                                                                                              using (System.IO.Stream stream = System.IO.File.OpenWrite(dir + "output.gif"))
                                                                                              {
                                                                                                  bmpImage.Save(stream, saveOptions);
                                                                                                  System.Console.WriteLine("The size of the lossless GIF: {0} bytes.", stream.Length);
                                                                                              }

                                                                                              // Set the maximum allowed pixel difference. If greater than zero, lossy compression will be used.
                                                                                              // The recommended value for optimal lossy compression is 80. 30 is very light compression, 200 is heavy.
                                                                                              saveOptions.MaxDiff = 80;

                                                                                              // Save as a lossy GIF.
                                                                                              using (System.IO.Stream stream = System.IO.File.OpenWrite(dir + "output.lossy.gif"))
                                                                                              {
                                                                                                  bmpImage.Save(stream, saveOptions);
                                                                                                  System.Console.WriteLine("The size of the lossy GIF: {0} bytes.", stream.Length);
                                                                                              }
                                                                                          }

                                                                                          //The output may look like this:
                                                                                          //The size of the lossless GIF: 212816 bytes.
                                                                                          //The size of the lossy GIF: 89726 bytes.

Remarks

Резолюция цвета - количество битов по первичному цвету доступнодо оригинального изображения, минус 1.Эта величина представляет собой размервся палетка, из которой цвета в графике былиВыбранный, а не количество цветов, которые фактически используются в графике.Например, если значение в этом поле составляет 3, то палетПервоначальное изображение имело 4 бита по первоначальному цвету, доступное для создания.Эта ценность должна быть установлена, чтобы указать богатствоОригинальная палитра, даже если не каждая краска из всегоПалет доступен на источном машине.

DoPaletteCorrection

Получается или устанавливается значение, указывающее на то, применяется ли коррекция палиты.

public bool DoPaletteCorrection { get; set; }

Стоимость недвижимости

bool

Examples

Этот пример показывает, как сохранить изображение BMP в формате GIF с помощью различных вариантов.

string dir = "c:\\temp\\";

                                                                                          using (Aspose.Imaging.Image bmpImage = new Aspose.Imaging.FileFormats.Bmp.BmpImage(1000, 1000))
                                                                                          {
                                                                                              // Fill the entire image with the blue-yellow gradient.
                                                                                              Aspose.Imaging.Brushes.LinearGradientBrush gradientBrush = new Aspose.Imaging.Brushes.LinearGradientBrush(
                                                                                                      new Aspose.Imaging.Point(0, 0),
                                                                                                      new Aspose.Imaging.Point(bmpImage.Width, bmpImage.Height),
                                                                                                      Aspose.Imaging.Color.Blue,
                                                                                                      Aspose.Imaging.Color.Yellow);

                                                                                              Aspose.Imaging.Graphics graphics = new Aspose.Imaging.Graphics(bmpImage);
                                                                                              graphics.FillRectangle(gradientBrush, bmpImage.Bounds);

                                                                                              Aspose.Imaging.ImageOptions.GifOptions saveOptions = new Aspose.Imaging.ImageOptions.GifOptions();

                                                                                              // The number of bits required to store a color, minus 1.
                                                                                              saveOptions.ColorResolution = 7;

                                                                                              // Palette correction means that whenever image is exported to GIF the source image colors will be analyzed
                                                                                              // in order to build the best matching palette (in case image Palette does not exist or not specified in the options)
                                                                                              saveOptions.DoPaletteCorrection = true;

                                                                                              // Load a GIF image in a progressive way.
                                                                                              // An interlaced GIF doesn't display its scanlines linearly from top to bottom, but instead reorders it
                                                                                              // so the content of the GIF becomes clear even before it finishes loading.
                                                                                              saveOptions.Interlaced = true;

                                                                                              // Save as a lossless GIF.
                                                                                              using (System.IO.Stream stream = System.IO.File.OpenWrite(dir + "output.gif"))
                                                                                              {
                                                                                                  bmpImage.Save(stream, saveOptions);
                                                                                                  System.Console.WriteLine("The size of the lossless GIF: {0} bytes.", stream.Length);
                                                                                              }

                                                                                              // Set the maximum allowed pixel difference. If greater than zero, lossy compression will be used.
                                                                                              // The recommended value for optimal lossy compression is 80. 30 is very light compression, 200 is heavy.
                                                                                              saveOptions.MaxDiff = 80;

                                                                                              // Save as a lossy GIF.
                                                                                              using (System.IO.Stream stream = System.IO.File.OpenWrite(dir + "output.lossy.gif"))
                                                                                              {
                                                                                                  bmpImage.Save(stream, saveOptions);
                                                                                                  System.Console.WriteLine("The size of the lossy GIF: {0} bytes.", stream.Length);
                                                                                              }
                                                                                          }

                                                                                          //The output may look like this:
                                                                                          //The size of the lossless GIF: 212816 bytes.
                                                                                          //The size of the lossy GIF: 89726 bytes.

Remarks

Палетная коррекция означает, что каждый раз, когда изображение экспортируется в GIF, цвета источника изображения будут анализированы.с целью создания наилучшей палиты соответствия (в случае, если изображения палиты не существует или не указано в вариантах).Процесс анализа занимает некоторое время, однако изображение выхода получит наилучшую палету цветов, и результат визуально лучше.

HasTrailer

Получается или устанавливается значение, указывающее, есть ли GIF трейлер.

public bool HasTrailer { get; set; }

Стоимость недвижимости

bool

HasTransparentColor

Получается или устанавливается значение, указывающее на то, имеет ли изображение GIF прозрачный цвет.Если доходная стоимость нуль, эта собственность преобладает источником изображения контекста.

[JsonProperty]
public bool? HasTransparentColor { get; set; }

Стоимость недвижимости

bool ?

Interlaced

Правда, если изображение должно быть взаимосвязано.

public bool Interlaced { get; set; }

Стоимость недвижимости

bool

Examples

Этот пример показывает, как сохранить изображение BMP в формате GIF с помощью различных вариантов.

string dir = "c:\\temp\\";

                                                                                          using (Aspose.Imaging.Image bmpImage = new Aspose.Imaging.FileFormats.Bmp.BmpImage(1000, 1000))
                                                                                          {
                                                                                              // Fill the entire image with the blue-yellow gradient.
                                                                                              Aspose.Imaging.Brushes.LinearGradientBrush gradientBrush = new Aspose.Imaging.Brushes.LinearGradientBrush(
                                                                                                      new Aspose.Imaging.Point(0, 0),
                                                                                                      new Aspose.Imaging.Point(bmpImage.Width, bmpImage.Height),
                                                                                                      Aspose.Imaging.Color.Blue,
                                                                                                      Aspose.Imaging.Color.Yellow);

                                                                                              Aspose.Imaging.Graphics graphics = new Aspose.Imaging.Graphics(bmpImage);
                                                                                              graphics.FillRectangle(gradientBrush, bmpImage.Bounds);

                                                                                              Aspose.Imaging.ImageOptions.GifOptions saveOptions = new Aspose.Imaging.ImageOptions.GifOptions();

                                                                                              // The number of bits required to store a color, minus 1.
                                                                                              saveOptions.ColorResolution = 7;

                                                                                              // Palette correction means that whenever image is exported to GIF the source image colors will be analyzed
                                                                                              // in order to build the best matching palette (in case image Palette does not exist or not specified in the options)
                                                                                              saveOptions.DoPaletteCorrection = true;

                                                                                              // Load a GIF image in a progressive way.
                                                                                              // An interlaced GIF doesn't display its scanlines linearly from top to bottom, but instead reorders it
                                                                                              // so the content of the GIF becomes clear even before it finishes loading.
                                                                                              saveOptions.Interlaced = true;

                                                                                              // Save as a lossless GIF.
                                                                                              using (System.IO.Stream stream = System.IO.File.OpenWrite(dir + "output.gif"))
                                                                                              {
                                                                                                  bmpImage.Save(stream, saveOptions);
                                                                                                  System.Console.WriteLine("The size of the lossless GIF: {0} bytes.", stream.Length);
                                                                                              }

                                                                                              // Set the maximum allowed pixel difference. If greater than zero, lossy compression will be used.
                                                                                              // The recommended value for optimal lossy compression is 80. 30 is very light compression, 200 is heavy.
                                                                                              saveOptions.MaxDiff = 80;

                                                                                              // Save as a lossy GIF.
                                                                                              using (System.IO.Stream stream = System.IO.File.OpenWrite(dir + "output.lossy.gif"))
                                                                                              {
                                                                                                  bmpImage.Save(stream, saveOptions);
                                                                                                  System.Console.WriteLine("The size of the lossy GIF: {0} bytes.", stream.Length);
                                                                                              }
                                                                                          }

                                                                                          //The output may look like this:
                                                                                          //The size of the lossless GIF: 212816 bytes.
                                                                                          //The size of the lossy GIF: 89726 bytes.

IsPaletteSorted

Получается или устанавливается значение, указывающее, сортируются ли входы в палец.

public bool IsPaletteSorted { get; set; }

Стоимость недвижимости

bool

LoopsCount

Получается или устанавливается число лопов (Default 1 loop)

public int LoopsCount { get; set; }

Стоимость недвижимости

int

MaxDiff

Получается или устанавливается максимальная разрешенная пиксельная разница.Если она превышает нуль, используется компрессия потери.Рекомендуемая ценность для оптимальной компрессии потери 80.30 очень легкая компрессия, 200 тяжелая.Он лучше всего работает, когда вводится только небольшой убыток, и из-за ограничения алгоритма компрессии очень высокие уровни убытков не дадут столько прибыли.Объем допустимых значений составляет [0, 1000].

public int MaxDiff { get; set; }

Стоимость недвижимости

int

Examples

Этот пример показывает, как сохранить изображение BMP в формате GIF с помощью различных вариантов.

string dir = "c:\\temp\\";

                                                                                          using (Aspose.Imaging.Image bmpImage = new Aspose.Imaging.FileFormats.Bmp.BmpImage(1000, 1000))
                                                                                          {
                                                                                              // Fill the entire image with the blue-yellow gradient.
                                                                                              Aspose.Imaging.Brushes.LinearGradientBrush gradientBrush = new Aspose.Imaging.Brushes.LinearGradientBrush(
                                                                                                      new Aspose.Imaging.Point(0, 0),
                                                                                                      new Aspose.Imaging.Point(bmpImage.Width, bmpImage.Height),
                                                                                                      Aspose.Imaging.Color.Blue,
                                                                                                      Aspose.Imaging.Color.Yellow);

                                                                                              Aspose.Imaging.Graphics graphics = new Aspose.Imaging.Graphics(bmpImage);
                                                                                              graphics.FillRectangle(gradientBrush, bmpImage.Bounds);

                                                                                              Aspose.Imaging.ImageOptions.GifOptions saveOptions = new Aspose.Imaging.ImageOptions.GifOptions();

                                                                                              // The number of bits required to store a color, minus 1.
                                                                                              saveOptions.ColorResolution = 7;

                                                                                              // Palette correction means that whenever image is exported to GIF the source image colors will be analyzed
                                                                                              // in order to build the best matching palette (in case image Palette does not exist or not specified in the options)
                                                                                              saveOptions.DoPaletteCorrection = true;

                                                                                              // Load a GIF image in a progressive way.
                                                                                              // An interlaced GIF doesn't display its scanlines linearly from top to bottom, but instead reorders it
                                                                                              // so the content of the GIF becomes clear even before it finishes loading.
                                                                                              saveOptions.Interlaced = true;

                                                                                              // Save as a lossless GIF.
                                                                                              using (System.IO.Stream stream = System.IO.File.OpenWrite(dir + "output.gif"))
                                                                                              {
                                                                                                  bmpImage.Save(stream, saveOptions);
                                                                                                  System.Console.WriteLine("The size of the lossless GIF: {0} bytes.", stream.Length);
                                                                                              }

                                                                                              // Set the maximum allowed pixel difference. If greater than zero, lossy compression will be used.
                                                                                              // The recommended value for optimal lossy compression is 80. 30 is very light compression, 200 is heavy.
                                                                                              saveOptions.MaxDiff = 80;

                                                                                              // Save as a lossy GIF.
                                                                                              using (System.IO.Stream stream = System.IO.File.OpenWrite(dir + "output.lossy.gif"))
                                                                                              {
                                                                                                  bmpImage.Save(stream, saveOptions);
                                                                                                  System.Console.WriteLine("The size of the lossy GIF: {0} bytes.", stream.Length);
                                                                                              }
                                                                                          }

                                                                                          //The output may look like this:
                                                                                          //The size of the lossless GIF: 212816 bytes.
                                                                                          //The size of the lossy GIF: 89726 bytes.

PixelAspectRatio

Получить или установить GIF пиксельный аспект соотношение.

public byte PixelAspectRatio { get; set; }

Стоимость недвижимости

byte

Remarks

Pixel Aspect Ratio — фактор, используемый для расчета приближенияиз аспекта соотношения пикселя в оригинальном изображении. еслизначение поля не 0, это приближение аспектного соотношенияСчитается на основе формулы:Aspect Ratio = (Pixel Aspect Ratio + 15) / 64Pixel Aspect Ratio определяется как коефициент пикселя.ширина выше его высоты. диапазон значений в этом поле позволяетСпецификация широчайшего пикселя от 4:1 до высочайшего пикселя1:4 в увеличениях 1/64.Ценности →0 - Информация о аспекте соотношения не предоставляется.1..255 - Значение, используемое в вычислении.

 Русский