Class Image

Class Image

Името на пространството: Aspose.Imaging Асамблея: Aspose.Imaging.dll (25.4.0)

Снимката е основният клас за всички видове изображения.

[JsonObject(MemberSerialization.OptIn)]
public abstract class Image : DataStreamSupporter, IDisposable, IObjectWithBounds

Inheritance

object DisposableObject DataStreamSupporter Image

Derived

RasterImage , VectorImage

Implements

IDisposable , IObjectWithBounds

наследници

DataStreamSupporter.timeout , DataStreamSupporter.CacheData() , DataStreamSupporter.Save() , DataStreamSupporter.Save(Stream) , DataStreamSupporter.Save(string) , DataStreamSupporter.Save(string, bool) , DataStreamSupporter.SaveData(Stream) , DataStreamSupporter.ReleaseManagedResources() , DataStreamSupporter.OnDataStreamContainerChanging(StreamContainer) , DataStreamSupporter.DataStreamContainer , DataStreamSupporter.IsCached , 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

Определете дали палетата се използва от изображението.

using (var image = Image.Load(folder + "Sample.bmp"))
                                                         {
                                                             if (image.UsePalette)
                                                             {
                                                                 Console.WriteLine("The palette is used by the image");
                                                             }
                                                         }

Рециклиране на изображението с помощта на специфичен Resize Type.

using (var image = Image.Load("Photo.jpg"))
                                                   {
                                                       image.Resize(640, 480, ResizeType.CatmullRom);
                                                       image.Save("ResizedPhoto.jpg");

                                                       image.Resize(1024, 768, ResizeType.CubicConvolution);
                                                       image.Save("ResizedPhoto2.jpg");

                                                       var resizeSettings = new ImageResizeSettings
                                                       {
                                                           Mode = ResizeType.CubicBSpline,
                                                           FilterType = ImageFilterType.SmallRectangular
                                                       };

                                                       image.Resize(800, 800, resizeSettings);
                                                       image.Save("ResizedPhoto3.jpg");
                                                   }

Този пример създава нов файл на изображението в определено местоположение на диска, както е посочено от свойството на източника на примера BmpOptions. Няколко свойства за случая Бmp Options се задават преди да се създаде действителното изображение.

//Create an instance of BmpOptions and set its various properties
                                                                                                                                                                                                                                                                                                             Aspose.Imaging.ImageOptions.BmpOptions bmpOptions = new Aspose.Imaging.ImageOptions.BmpOptions();
                                                                                                                                                                                                                                                                                                             bmpOptions.BitsPerPixel = 24;

                                                                                                                                                                                                                                                                                                             //Create an instance of FileCreateSource and assign it as Source for the instance of BmpOptions
                                                                                                                                                                                                                                                                                                             //Second Boolean parameter determines if the file to be created IsTemporal or not
                                                                                                                                                                                                                                                                                                             bmpOptions.Source = new Aspose.Imaging.Sources.FileCreateSource(@"C:\temp\output.bmp", false);

                                                                                                                                                                                                                                                                                                             //Create an instance of Image and initialize it with instance of BmpOptions by calling Create method
                                                                                                                                                                                                                                                                                                             using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Create(bmpOptions, 500, 500))
                                                                                                                                                                                                                                                                                                             {
                                                                                                                                                                                                                                                                                                                 //do some image processing

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

Constructors

Image()

Иницијализира нова инстанция на Aspose.Imaging.Снимка клас.

[JsonConstructor]
protected Image()

Image(ICOLORПалате)

Иницијализира нова инстанция на Aspose.Imaging.Снимка клас.

protected Image(IColorPalette colorPalette)

Parameters

colorPalette IColorPalette

Цветовата палитра.

Properties

AutoAdjustPalette

Получава или задава стойност, която показва дали палетът автоматично се коригира.

public bool AutoAdjustPalette { get; set; }

стойност на имота

bool

BackgroundColor

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

public virtual Color BackgroundColor { get; set; }

стойност на имота

Color

BitsPerPixel

Получава изображението битове на пиксел.

public abstract int BitsPerPixel { get; }

стойност на имота

int

Bounds

Вземете границите на изображението.

public Rectangle Bounds { get; }

стойност на имота

Rectangle

BufferSizeHint

Получава или поставя индикатора за размера на буфера, който е дефиниран максимално допустим размер за всички вътрешни буфери.

public int BufferSizeHint { get; set; }

стойност на имота

int

Container

Получава се контейнерът за изображение Aspose.Imaging.

public Image Container { get; }

стойност на имота

Image

Remarks

Ако тази собственост не е нула, тя показва, че изображението се съдържа в друга картина.

FileFormat

Получава стойност на файлов формат

public virtual FileFormat FileFormat { get; }

стойност на имота

FileFormat

HasBackgroundColor

Получава или задава стойност, която показва дали изображението има цвят на фона.

public virtual bool HasBackgroundColor { get; set; }

стойност на имота

bool

Height

Получава височината на изображението.

public abstract int Height { get; }

стойност на имота

int

InterruptMonitor

Вземете или поставете прекъснатия монитор.

public InterruptMonitor InterruptMonitor { get; set; }

стойност на имота

InterruptMonitor

Palette

Палетата на цветовете не се използва, когато пикселите са представени директно.

public IColorPalette Palette { get; set; }

стойност на имота

IColorPalette

Size

Намерете размера на изображението.

public Size Size { get; }

стойност на имота

Size

Examples

Този пример показва как да изтеглите изображение на DJVU от файлов поток и да отпечатате информация за страниците.

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

                                                                                                                // Load a DJVU image from a file stream.
                                                                                                                using (System.IO.Stream stream = System.IO.File.OpenRead(dir + "sample.djvu"))
                                                                                                                {
                                                                                                                    using (Aspose.Imaging.FileFormats.Djvu.DjvuImage djvuImage = new Aspose.Imaging.FileFormats.Djvu.DjvuImage(stream))
                                                                                                                    {
                                                                                                                        System.Console.WriteLine("The total number of pages: {0}", djvuImage.Pages.Length);
                                                                                                                        System.Console.WriteLine("The active page number:    {0}", djvuImage.ActivePage.PageNumber);
                                                                                                                        System.Console.WriteLine("The first page number:     {0}", djvuImage.FirstPage.PageNumber);
                                                                                                                        System.Console.WriteLine("The last page number:      {0}", djvuImage.LastPage.PageNumber);

                                                                                                                        foreach (Aspose.Imaging.FileFormats.Djvu.DjvuPage djvuPage in djvuImage.Pages)
                                                                                                                        {
                                                                                                                            System.Console.WriteLine("--------------------------------------------------");
                                                                                                                            System.Console.WriteLine("Page number:     {0}", djvuPage.PageNumber);
                                                                                                                            System.Console.WriteLine("Page size:       {0}", djvuPage.Size);
                                                                                                                            System.Console.WriteLine("Page raw format: {0}", djvuPage.RawDataFormat);
                                                                                                                        }
                                                                                                                    }
                                                                                                                }

                                                                                                                //The output may look like this:
                                                                                                                //The total number of pages: 2
                                                                                                                //The active page number:    1
                                                                                                                //The first page number:     1
                                                                                                                //The last page number:      2
                                                                                                                //--------------------------------------------------
                                                                                                                //Page number:     1
                                                                                                                //Page size:       { Width = 2481, Height = 3508}
                                                                                                                //Page raw format: RgbIndexed1Bpp, used channels: 1
                                                                                                                //--------------------------------------------------
                                                                                                                //Page number:     2
                                                                                                                //Page size:       { Width = 2481, Height = 3508}
                                                                                                                //Page raw format: RgbIndexed1Bpp, used channels: 1

UsePalette

Получава стойност, която показва дали изображението е използвано.

public virtual bool UsePalette { get; }

стойност на имота

bool

Examples

Определете дали палетата се използва от изображението.

using (var image = Image.Load(folder + "Sample.bmp"))
                                                         {
                                                             if (image.UsePalette)
                                                             {
                                                                 Console.WriteLine("The palette is used by the image");
                                                             }
                                                         }

Width

Получава ширината на изображението.

public abstract int Width { get; }

стойност на имота

int

Methods

CanLoad(Стрий)

Определя дали изображението може да бъде изтеглено от посочения файлов път.

public static bool CanLoad(string filePath)

Parameters

filePath string

Пътят на файла.

Returns

bool

“истински”, ако изображението може да бъде изтеглено от посочения файл; в противен случай, “фалшив”.

Examples

Този пример определя дали изображението може да бъде изтеглено от файл.

// Use an absolute path to the file
                                                                           bool canLoad = Aspose.Imaging.Image.CanLoad(@"c:\temp\sample.gif");

CanLoad(Стринг, опции за натоварване)

Определя дали изображението може да бъде изтеглено от посочения път на файла и опционално, използвайки посочените отворени опции.

public static bool CanLoad(string filePath, LoadOptions loadOptions)

Parameters

filePath string

Пътят на файла.

loadOptions LoadOptions

Опции за натоварване.

Returns

bool

“истински”, ако изображението може да бъде изтеглено от посочения файл; в противен случай, “фалшив”.

CanLoad(Stream)

Определя дали изображението може да бъде заредено от посочения поток.

public static bool CanLoad(Stream stream)

Parameters

stream Stream

Потокът да се изтегли.

Returns

bool

“истински”, ако изображението може да бъде изтеглено от посочения поток; в противен случай, “фалшив”.

Examples

Този пример определя дали изображението може да бъде изтеглено от файл поток.

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

                                                                                  bool canLoad;

                                                                                  // Use a file stream
                                                                                  using (System.IO.FileStream stream = System.IO.File.OpenRead(dir + "sample.bmp"))
                                                                                  {
                                                                                      canLoad = Aspose.Imaging.Image.CanLoad(stream);
                                                                                  }

                                                                                  // The following data is not a valid image stream, so CanLoad returns false.
                                                                                  byte[] imageData = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
                                                                                  using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageData))
                                                                                  {
                                                                                      canLoad = Aspose.Imaging.Image.CanLoad(stream);
                                                                                  }

CanLoad(Изтегляне, LoadOptions)

Определя дали изображението може да бъде изтеглено от посочения поток и опционално използва loadOptions".

public static bool CanLoad(Stream stream, LoadOptions loadOptions)

Parameters

stream Stream

Потокът да се изтегли.

loadOptions LoadOptions

Опции за натоварване.

Returns

bool

“истински”, ако изображението може да бъде изтеглено от посочения поток; в противен случай, “фалшив”.

CanSave(ImageOptionsBase)

Определя дали изображението може да се съхранява в посочения формат на файла, представен от пропуснатите опции за съхранение.

public bool CanSave(ImageOptionsBase options)

Parameters

options ImageOptionsBase

Възможностите за спестяване да се използват.

Returns

bool

“истински”, ако изображението може да се съхранява в посочения формат на файла, представен от пропуснатите опции за съхранение; в противен случай, “фалшив”.

Examples

Този пример показва как да се определи дали изображението може да бъде съхранено в посочения формат на файла, представен от пропуснатите опции за запазване.

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

                                                                                                                                              using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                                                                              {
                                                                                                                                                  Aspose.Imaging.ImageOptions.JpegOptions saveOptions = new Aspose.Imaging.ImageOptions.JpegOptions();
                                                                                                                                                  saveOptions.Quality = 50;

                                                                                                                                                  // Determine whether the image can be saved to Jpeg
                                                                                                                                                  bool canSave = image.CanSave(saveOptions);
                                                                                                                                              }

Create(ImageOptionsBase, int, инт)

Създава ново изображение, като използва определените опции за създаване.

public static Image Create(ImageOptionsBase imageOptions, int width, int height)

Parameters

imageOptions ImageOptionsBase

Опции за изображение.

width int

и ширината.

height int

на височината.

Returns

Image

Новосъздадената картина.

Examples

Този пример създава нов файл на изображението в определено местоположение на диска, както е посочено от свойството на източника на примера BmpOptions. Няколко свойства за случая Бmp Options се задават преди да се създаде действителното изображение.

//Create an instance of BmpOptions and set its various properties
                                                                                                                                                                                                                                                                                                             Aspose.Imaging.ImageOptions.BmpOptions bmpOptions = new Aspose.Imaging.ImageOptions.BmpOptions();
                                                                                                                                                                                                                                                                                                             bmpOptions.BitsPerPixel = 24;

                                                                                                                                                                                                                                                                                                             //Create an instance of FileCreateSource and assign it as Source for the instance of BmpOptions
                                                                                                                                                                                                                                                                                                             //Second Boolean parameter determines if the file to be created IsTemporal or not
                                                                                                                                                                                                                                                                                                             bmpOptions.Source = new Aspose.Imaging.Sources.FileCreateSource(@"C:\temp\output.bmp", false);

                                                                                                                                                                                                                                                                                                             //Create an instance of Image and initialize it with instance of BmpOptions by calling Create method
                                                                                                                                                                                                                                                                                                             using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Create(bmpOptions, 500, 500))
                                                                                                                                                                                                                                                                                                             {
                                                                                                                                                                                                                                                                                                                 //do some image processing

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

Create(Image[])

Създава ново изображение, като използва посочените изображения като страници

public static Image Create(Image[] images)

Parameters

images Image []

Изображенията .

Returns

Image

Снимка като IMultipageImage

Create(MultipageCreateOptions)

Създаване на определената мултистраница създава опции.

public static Image Create(MultipageCreateOptions multipageCreateOptions)

Parameters

multipageCreateOptions MultipageCreateOptions

Многостраниците създават опции.

Returns

Image

Мултистранен имидж

Create(Стрий[]Боул)

Създава мултистрани изображения, съдържащи посочените файлове.

public static Image Create(string[] files, bool throwExceptionOnLoadError)

Parameters

files string []

и на файловете.

throwExceptionOnLoadError bool

Ако сте зададени на “истински” [изхвърляйте изключението на грешката на натоварването].

Returns

Image

Мултистранен имидж

Create(Стрий[])

Създава мултистрани изображения, съдържащи посочените файлове.

public static Image Create(string[] files)

Parameters

files string []

и на файловете.

Returns

Image

Мултистранен имидж

Create(Image[]Боул)

Създава ново изображение на посочените изображения като страници.

public static Image Create(Image[] images, bool disposeImages)

Parameters

images Image []

Изображенията .

disposeImages bool

Ако се зададе на „истински“ [да се предоставят изображения].

Returns

Image

Снимка като IMultipageImage

Crop(Rectangle)

Намаляване на посочения правоъгълник.

public virtual void Crop(Rectangle rectangle)

Parameters

rectangle Rectangle

на правоъгълника.

Examples

Следващият пример събира изображение на растер. Областта на отглеждане се посочва чрез Aspose.Imaging.Rectangle.

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

                                                                                                                      using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
                                                                                                                      {
                                                                                                                          // Crop the image. The cropping area is the rectangular central area of the image.
                                                                                                                          Aspose.Imaging.Rectangle area = new Aspose.Imaging.Rectangle(rasterImage.Width / 4, rasterImage.Height / 4, rasterImage.Width / 2, rasterImage.Height / 2);
                                                                                                                          image.Crop(area);

                                                                                                                          // Save the cropped image to PNG
                                                                                                                          image.Save(dir + "sample.Crop.png");
                                                                                                                      }

Crop(Инт, инт, инт, инт)

Изображение на растението с промени.

public virtual void Crop(int leftShift, int rightShift, int topShift, int bottomShift)

Parameters

leftShift int

Вляво се сменя.

rightShift int

правилната промяна.

topShift int

На върха на промяната.

bottomShift int

Долната промяна.

Examples

Следващият пример отглежда изображение на растер. Площта на отглеждане се посочва чрез левите, горните, десните, долните маргини.

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

                                                                                                                           using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
                                                                                                                           {
                                                                                                                               // Crop again. Set a margin of 10% of the image size.
                                                                                                                               int horizontalMargin = rasterImage.Width / 10;
                                                                                                                               int verticalMargin = rasterImage.Height / 10;
                                                                                                                               image.Crop(horizontalMargin, horizontalMargin, verticalMargin, verticalMargin);

                                                                                                                               // Save the cropped image to PNG.
                                                                                                                               image.Save(dir + "sample.Crop.png");
                                                                                                                           }

~Image()

protected ~Image()

GetCanNotSaveMessage(ImageOptionsBase)

Не можете да спестите съобщение.

protected virtual string GetCanNotSaveMessage(ImageOptionsBase optionsBase)

Parameters

optionsBase ImageOptionsBase

Опции за изображение.

Returns

string

Тя не може да съхранява съобщение.

GetDefaultOptions(Обект[])

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

public virtual ImageOptionsBase GetDefaultOptions(object[] args)

Parameters

args object []

и аргументите.

Returns

ImageOptionsBase

Дефинирани опции

GetFileFormat(Стрий)

Получаване на формат на файла.

public static FileFormat GetFileFormat(string filePath)

Parameters

filePath string

Пътят на файла.

Returns

FileFormat

Определен формат на файла.

Examples

Този пример показва как да определите формата на изображението, без да зареждате цялата картина от файл.

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

                                                                                                             // Use an absolute path to the file
                                                                                                             Aspose.Imaging.FileFormat format = Aspose.Imaging.Image.GetFileFormat(dir + "sample.gif");
                                                                                                             System.Console.WriteLine("The file format is {0}", format);

Remarks

Определеният формат на файла не означава, че посоченото изображение може да бъде изтеглено. Използвайте един от методите на CanLoad за презареждане, за да определите дали файловете могат да бъдат заредени.

GetFileFormat(Stream)

Получаване на формат на файла.

public static FileFormat GetFileFormat(Stream stream)

Parameters

stream Stream

на потока .

Returns

FileFormat

Определен формат на файла.

Examples

Този пример показва как да определите формата на изображението, без да зареждате цялата картина от файл поток.

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

                                                                                                                    // Use a file stream
                                                                                                                    using (System.IO.FileStream stream = System.IO.File.OpenRead(dir + "sample.bmp"))
                                                                                                                    {
                                                                                                                        Aspose.Imaging.FileFormat format = Aspose.Imaging.Image.GetFileFormat(stream);
                                                                                                                        System.Console.WriteLine("The file format is {0}", format);
                                                                                                                    }

                                                                                                                    // The following data is not a valid image stream, so GetFileFormat returns FileFormat.Undefined.
                                                                                                                    byte[] imageData = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
                                                                                                                    using (System.IO.MemoryStream stream = new System.IO.MemoryStream(imageData))
                                                                                                                    {
                                                                                                                        Aspose.Imaging.FileFormat format = Aspose.Imaging.Image.GetFileFormat(stream);
                                                                                                                        System.Console.WriteLine("The file format is {0}", format);
                                                                                                                    }

Remarks

Определеният формат на файла не означава, че посоченото изображение може да бъде заредено. Използвайте един от методите за претоварване на CanLoad, за да определите дали потокът могат да бъдат заредени.

GetFitRectangle(Rectangle)

Получава правоъгълник, който съответства на текущото изображение.

protected Rectangle GetFitRectangle(Rectangle rectangle)

Parameters

rectangle Rectangle

За да се получи подходящ правоъгълник.

Returns

Rectangle

Подходящ правоъгълник

GetFitRectangle(Връзката, инт[])

Получава правоъгълник, който съответства на текущата битка, като се вземат предвид преминатите пиксели.

protected Rectangle GetFitRectangle(Rectangle rectangle, int[] pixels)

Parameters

rectangle Rectangle

За да се получи подходящ правоъгълник.

pixels int []

32-битови ARGB пиксели са на разположение.

Returns

Rectangle

Подходящ правоъгълник .

GetFittingRectangle(Ректангъл, int и int)

Получава правоъгълник, който съответства на текущото изображение.

public static Rectangle GetFittingRectangle(Rectangle rectangle, int width, int height)

Parameters

rectangle Rectangle

За да се получи подходящ правоъгълник.

width int

Обектът е широк.

height int

Височина на обекта.

Returns

Rectangle

Подходящият правоъгълник или изключението, ако не може да се намери подходящ правоък.

GetFittingRectangle(Връзката, инт[], int, int)

Получава правоъгълник, който съответства на текущото изображение.

public static Rectangle GetFittingRectangle(Rectangle rectangle, int[] pixels, int width, int height)

Parameters

rectangle Rectangle

За да се получи подходящ правоъгълник.

pixels int []

32-битови ARGB пиксели

width int

Обектът е широк.

height int

Височина на обекта.

Returns

Rectangle

Подходящият правоъгълник или изключението, ако не може да се намери подходящ правоък.

GetImage2Export(ImageOptionsBase, Rectangle, IImageЕкспортер)

Налице е изображението за износ.

[Obsolete("Will be changed by method with other signature")]
protected virtual Image GetImage2Export(ImageOptionsBase optionsBase, Rectangle boundsRectangle, IImageExporter exporter)

Parameters

optionsBase ImageOptionsBase

Базата на опциите за изображение.

boundsRectangle Rectangle

Ограниченията са правоъгълни.

exporter IImageExporter

на износителя.

Returns

Image

Снимка за износ

GetOriginalOptions()

Получава опциите въз основа на първоначалните настройки на файла.Това може да бъде полезно, за да се запази битовата дълбочина и други параметри на оригиналната картина непроменени.Например, ако зареждаме черно-бяло PNG изображение с 1 бит на пиксел и след това го съхраняваме с помощта наAspose.Imaging.DataStreamSupporter.Save(System.String) метод, изходната PNG изображение с 8 бита на пиксел ще бъде произведена.За да избегнете това и да спестите PNG изображение с 1-бит на пиксел, използвайте този метод, за да получите съответните възможности за спестяване и ги прехвърлитена метода Aspose.Imaging.Image.Save(System.String,_Wl17.ImageOptionsBase) като втори параметър.

public virtual ImageOptionsBase GetOriginalOptions()

Returns

ImageOptionsBase

Опциите се основават на първоначалните настройки на файла.

GetProportionalHeight(Инт, инт, инт)

Получава пропорционална височина.

public static int GetProportionalHeight(int width, int height, int newWidth)

Parameters

width int

и ширината.

height int

на височината.

newWidth int

Новата ширина.

Returns

int

Пропорционалната височина.

GetProportionalWidth(Инт, инт, инт)

Има пропорционална широчина.

public static int GetProportionalWidth(int width, int height, int newHeight)

Parameters

width int

и ширината.

height int

на височината.

newHeight int

Новата височина.

Returns

int

Пропорционална широчина.

GetSerializedStream(ImageOptionsBase, Rectangle, изход int)

Превръща се в APS.

public virtual Stream GetSerializedStream(ImageOptionsBase imageOptions, Rectangle clippingRectangle, out int pageNumber)

Parameters

imageOptions ImageOptionsBase

Опции за изображение.

clippingRectangle Rectangle

Клепингът е правоъгълник.

pageNumber int

Номер на страницата.

Returns

Stream

Сериализираният поток

Load(Стринг, опции за натоварване)

Изтегля нова картина от посочения файлов път или URL.Ако filePath’ е файл път, методът просто отваря файла.И ако file Path е URL, метода изтегли файлът, го съхранява като временна и го открива.

public static Image Load(string filePath, LoadOptions loadOptions)

Parameters

filePath string

Пътят на файла или URL за изтегляне на изображението от.

loadOptions LoadOptions

Опции за натоварване.

Returns

Image

Натовареното изображение.

Load(Стрий)

Изтегля нова картина от посочения файлов път или URL.Ако filePath’ е файл път, методът просто отваря файла.И ако file Path е URL, метода изтегли файлът, го съхранява като временна и го открива.

public static Image Load(string filePath)

Parameters

filePath string

Пътят на файла или URL за изтегляне на изображението от.

Returns

Image

Натовареното изображение.

Examples

Този пример показва изтеглянето на съществуващ файл на изображението в инстанция на Aspose.Imaging.Снимка, използвайки посочения път на файла

//Create Image instance and initialize it with an existing image file from disk location
                                                                                                                                             using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(@"C:\temp\sample.bmp"))
                                                                                                                                             {
                                                                                                                                                 //do some image processing
                                                                                                                                             }

Load(Изтегляне, LoadOptions)

Изтегля нова картина от посочения поток.

public static Image Load(Stream stream, LoadOptions loadOptions)

Parameters

stream Stream

Потокът за зареждане на изображението от.

loadOptions LoadOptions

Опции за натоварване.

Returns

Image

Натовареното изображение.

Load(Stream)

Изтегля нова картина от посочения поток.

public static Image Load(Stream stream)

Parameters

stream Stream

Потокът за зареждане на изображението от.

Returns

Image

Натовареното изображение.

Examples

Този пример показва използването на System.IO.Stream обекти за зареждане на съществуващ файл Снимка

//Create an instance of FileStream
                                                                                                       using (System.IO.FileStream stream = new System.IO.FileStream(@"C:\temp\sample.bmp", System.IO.FileMode.Open))
                                                                                                       {
                                                                                                           //Create an instance of Image class and load an existing file through FileStream object by calling Load method
                                                                                                           using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(stream))
                                                                                                           {
                                                                                                               //do some image processing.
                                                                                                           }
                                                                                                       }

OnPaletteChanged(Изолация, IColorPalette)

Позива се, когато палетът се променя.

protected virtual void OnPaletteChanged(IColorPalette oldPalette, IColorPalette newPalette)

Parameters

oldPalette IColorPalette

Старата палитра.

newPalette IColorPalette

Новата палитра.

OnPaletteChanging(Изолация, IColorPalette)

Позива се, когато палетът се променя.

protected virtual void OnPaletteChanging(IColorPalette oldPalette, IColorPalette newPalette)

Parameters

oldPalette IColorPalette

Старата палитра.

newPalette IColorPalette

Новата палитра.

ReleaseManagedResources()

Уверете се, че не управлявани ресурси не се пускат тук, тъй като те може да са вече пуснати.

protected override void ReleaseManagedResources()

RemoveMetadata()

Премахване на метаданни.

public virtual void RemoveMetadata()

Resize(в, в)

Използва се подразбиране Aspose.Imaging.ResizeType.NearestNeighbourResample.

public void Resize(int newWidth, int newHeight)

Parameters

newWidth int

Новата ширина.

newHeight int

Новата височина.

Examples

Следващият пример показва как да се рецизира метафил (WMF и EMF).

string dir = "c:\\aspose.imaging\\issues\\net\\3280\\";
                                                                              string[] fileNames = new[] { "image3.emf", "image4.wmf" };
                                                                              foreach (string fileName in fileNames)
                                                                              {
                                                                                  string inputFilePath = dir + fileName;
                                                                                  string outputFilePath = dir + "Downscale_" + fileName;

                                                                                  using (Aspose.Imaging.FileFormats.Emf.MetaImage image = (Aspose.Imaging.FileFormats.Emf.MetaImage)Aspose.Imaging.Image.Load(inputFilePath))
                                                                                  {
                                                                                      image.Resize(image.Width / 4, image.Height / 4);
                                                                                      image.Save(outputFilePath);
                                                                                  }
                                                                              }

Следващият пример показва как да преразгледате изображението SVG и да го съхранявате в PNG.

string dir = "c:\\aspose.imaging\\net\\issues\\3549";
                                                                                  string[] fileNames = new string[]
                                                                                  {
                                                                                      "Logotype.svg",
                                                                                      "sample_car.svg",
                                                                                      "rg1024_green_grapes.svg",
                                                                                      "MidMarkerFigure.svg",
                                                                                      "embeddedFonts.svg"
                                                                                  };

                                                                                  Aspose.Imaging.PointF[] scales = new Aspose.Imaging.PointF[]
                                                                                  {
                                                                                      new Aspose.Imaging.PointF(0.5f, 0.5f),
                                                                                      new Aspose.Imaging.PointF(1f, 1f),
                                                                                      new Aspose.Imaging.PointF(2f, 2f),
                                                                                      new Aspose.Imaging.PointF(3.5f, 9.2f),
                                                                                  };

                                                                                  foreach (string inputFile in fileNames)
                                                                                  {
                                                                                      foreach (Aspose.Imaging.PointF scale in scales)
                                                                                      {
                                                                                          string outputFile = string.Format("{0}_{1}_{2}.png", inputFile, scale.X.ToString(System.Globalization.CultureInfo.InvariantCulture), scale.Y.ToString(System.Globalization.CultureInfo.InvariantCulture));
                                                                                          using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(System.IO.Path.Combine(dir, inputFile)))
                                                                                          {
                                                                                              image.Resize((int)(image.Width * scale.X), (int)(image.Height * scale.Y));
                                                                                              image.Save(System.IO.Path.Combine(dir, outputFile), new Aspose.Imaging.ImageOptions.PngOptions());
                                                                                          }
                                                                                      }
                                                                                  }

Resize(Инт, инт и резистент)

Рециклира изображението.

public virtual void Resize(int newWidth, int newHeight, ResizeType resizeType)

Parameters

newWidth int

Новата ширина.

newHeight int

Новата височина.

resizeType ResizeType

Типът на възстановяване.

Examples

Изтеглете изображението на EPS и го експортирате в PNG формат.

// Load EPS image
                                                        using (var image = Image.Load("AstrixObelix.eps"))
                                                        {
                                                            // Resize the image using the Mitchell cubic interpolation method
                                                            image.Resize(400, 400, ResizeType.Mitchell);

                                                            // Export image to PNG format
                                                            image.Save("ExportResult.png", new PngOptions());
                                                        }

Рециклиране на изображението с помощта на специфичен Resize Type.

using (var image = Image.Load("Photo.jpg"))
                                                   {
                                                       image.Resize(640, 480, ResizeType.CatmullRom);
                                                       image.Save("ResizedPhoto.jpg");

                                                       image.Resize(1024, 768, ResizeType.CubicConvolution);
                                                       image.Save("ResizedPhoto2.jpg");

                                                       var resizeSettings = new ImageResizeSettings
                                                       {
                                                           Mode = ResizeType.CubicBSpline,
                                                           FilterType = ImageFilterType.SmallRectangular
                                                       };

                                                       image.Resize(800, 800, resizeSettings);
                                                       image.Save("ResizedPhoto3.jpg");
                                                   }

Този пример натоварва изображение на WMF и го рецизира с помощта на различни методи за ресизиране.

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

                                                                                        using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.wmf"))
                                                                                        {
                                                                                            // Scale up by 2 times using Nearest Neighbour resampling.
                                                                                            image.Resize(image.Width * 2, image.Height * 2, Aspose.Imaging.ResizeType.NearestNeighbourResample);
                                                                                        }

                                                                                        using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.wmf"))
                                                                                        {
                                                                                            // Scale down by 2 times using Nearest Neighbour resampling.
                                                                                            image.Resize(image.Width / 2, image.Height / 2, Aspose.Imaging.ResizeType.NearestNeighbourResample);
                                                                                        }

                                                                                        using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.wmf"))
                                                                                        {
                                                                                            // Scale up by 2 times using Bilinear resampling.
                                                                                            image.Resize(image.Width * 2, image.Height * 2, Aspose.Imaging.ResizeType.BilinearResample);
                                                                                        }

                                                                                        using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.wmf"))
                                                                                        {
                                                                                            // Scale down by 2 times using Bilinear resampling.
                                                                                            image.Resize(image.Width / 2, image.Height / 2, Aspose.Imaging.ResizeType.BilinearResample);
                                                                                        }

Този пример натоварва изображението и го рецизира с помощта на различни методи за рецесиране.

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

                                                                                     using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                     {
                                                                                         // Scale up by 2 times using Nearest Neighbour resampling.
                                                                                         image.Resize(image.Width* 2, image.Height* 2, Aspose.Imaging.ResizeType.NearestNeighbourResample);
                                                                                         image.Save(dir + "upsample.nearestneighbour.gif");
                                                                                     }

                                                                                     using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                     {
                                                                                         // Scale down by 2 times using Nearest Neighbour resampling.
                                                                                         image.Resize(image.Width / 2, image.Height / 2, Aspose.Imaging.ResizeType.NearestNeighbourResample);
                                                                                         image.Save(dir + "downsample.nearestneighbour.gif");
                                                                                     }

                                                                                     using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                     {
                                                                                         // Scale up by 2 times using Bilinear resampling.
                                                                                         image.Resize(image.Width* 2, image.Height* 2, Aspose.Imaging.ResizeType.BilinearResample);
                                                                                         image.Save(dir + "upsample.bilinear.gif");
                                                                                     }

                                                                                     using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                     {
                                                                                         // Scale down by 2 times using Bilinear resampling.
                                                                                         image.Resize(image.Width / 2, image.Height / 2, Aspose.Imaging.ResizeType.BilinearResample);
                                                                                         image.Save(dir + "downsample.bilinear.gif");
                                                                                     }

Този пример натоварва изображение на растер и го рецизира с помощта на различни методи за ресизиране.

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

                                                                                           using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                           {
                                                                                               // Scale up by 2 times using Nearest Neighbour resampling.
                                                                                               image.Resize(image.Width * 2, image.Height * 2, Aspose.Imaging.ResizeType.NearestNeighbourResample);
                                                                                               image.Save(dir + "upsample.nearestneighbour.gif");
                                                                                           }

                                                                                           using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                           {
                                                                                               // Scale down by 2 times using Nearest Neighbour resampling.
                                                                                               image.Resize(image.Width / 2, image.Height / 2, Aspose.Imaging.ResizeType.NearestNeighbourResample);
                                                                                               image.Save(dir + "downsample.nearestneighbour.gif");
                                                                                           }

                                                                                           using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                           {
                                                                                               // Scale up by 2 times using Bilinear resampling.
                                                                                               image.Resize(image.Width * 2, image.Height * 2, Aspose.Imaging.ResizeType.BilinearResample);
                                                                                               image.Save(dir + "upsample.bilinear.gif");
                                                                                           }

                                                                                           using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                           {
                                                                                               // Scale down by 2 times using Bilinear resampling.
                                                                                               image.Resize(image.Width / 2, image.Height / 2, Aspose.Imaging.ResizeType.BilinearResample);
                                                                                               image.Save(dir + "downsample.bilinear.gif");
                                                                                           }

Този пример зарежда мулти-страница ODG изображение и го рецизира с помощта на различни методи за ресизиране.

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

                                                                                                   using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.odg"))
                                                                                                   {
                                                                                                       // Scale up by 2 times using Nearest Neighbour resampling.
                                                                                                       image.Resize(image.Width* 2, image.Height* 2, Aspose.Imaging.ResizeType.NearestNeighbourResample);

                                                                                                       // Save to PNG with default options.
                                                                                                       image.Save(dir + "upsample.nearestneighbour.png", new Aspose.Imaging.ImageOptions.PngOptions());
                                                                                                   }

                                                                                                   using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.odg"))
                                                                                                   {
                                                                                                       // Scale down by 2 times using Nearest Neighbour resampling.
                                                                                                       image.Resize(image.Width / 2, image.Height / 2, Aspose.Imaging.ResizeType.NearestNeighbourResample);

                                                                                                       // Save to PNG with default options.
                                                                                                       image.Save(dir + "downsample.nearestneighbour.png", new Aspose.Imaging.ImageOptions.PngOptions());
                                                                                                   }

                                                                                                   using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.odg"))
                                                                                                   {
                                                                                                       // Scale up by 2 times using Bilinear resampling.
                                                                                                       image.Resize(image.Width* 2, image.Height* 2, Aspose.Imaging.ResizeType.BilinearResample);

                                                                                                       // Save to PNG with default options.
                                                                                                       image.Save(dir + "upsample.bilinear.png", new Aspose.Imaging.ImageOptions.PngOptions());
                                                                                                   }

                                                                                                   using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.odg"))
                                                                                                   {
                                                                                                       // Scale down by 2 times using Bilinear resampling.
                                                                                                       image.Resize(image.Width / 2, image.Height / 2, Aspose.Imaging.ResizeType.BilinearResample);

                                                                                                       // Save to PNG with default options.
                                                                                                       image.Save(dir + "downsample.bilinear.png", new Aspose.Imaging.ImageOptions.PngOptions());
                                                                                                   }

Използвайте маска за сегментиране, за да ускорите процеса на сегментация

// Masking export options
                                                                    Aspose.Imaging.ImageOptions.PngOptions exportOptions = new Aspose.Imaging.ImageOptions.PngOptions();
                                                                    exportOptions.ColorType = Aspose.Imaging.FileFormats.Png.PngColorType.TruecolorWithAlpha;
                                                                    exportOptions.Source = new Aspose.Imaging.Sources.StreamSource(new System.IO.MemoryStream());

                                                                    Aspose.Imaging.Masking.Options.MaskingOptions maskingOptions = new Aspose.Imaging.Masking.Options.MaskingOptions();

                                                                    // Use GraphCut clustering.
                                                                    maskingOptions.Method = Masking.Options.SegmentationMethod.GraphCut;
                                                                    maskingOptions.Decompose = false;
                                                                    maskingOptions.Args = new Aspose.Imaging.Masking.Options.AutoMaskingArgs();

                                                                    // The backgroung color will be transparent.
                                                                    maskingOptions.BackgroundReplacementColor = Aspose.Imaging.Color.Transparent;
                                                                    maskingOptions.ExportOptions = exportOptions;

                                                                    string dir = "c:\\temp\\";
                                                                    using (Aspose.Imaging.RasterImage image = (Aspose.Imaging.RasterImage)Aspose.Imaging.Image.Load(dir + "BigImage.jpg"))
                                                                    {
                                                                        Aspose.Imaging.Size imageSize = image.Size;

                                                                        // Reducing image size to speed up the segmentation process
                                                                        image.ResizeHeightProportionally(600, Aspose.Imaging.ResizeType.HighQualityResample);

                                                                        // Create an instance of the ImageMasking class.
                                                                        Aspose.Imaging.Masking.ImageMasking masking = new Aspose.Imaging.Masking.ImageMasking(image);

                                                                        // Divide the source image into several clusters (segments).
                                                                        using (Aspose.Imaging.Masking.Result.MaskingResult maskingResult = masking.Decompose(maskingOptions))
                                                                        {
                                                                            // Getting the foreground mask
                                                                            using (Aspose.Imaging.RasterImage foregroundMask = maskingResult[1].GetMask()) 
                                                                            {
                                                                                // Increase the size of the mask to the size of the original image
                                                                                foregroundMask.Resize(imageSize.Width, imageSize.Height, Aspose.Imaging.ResizeType.NearestNeighbourResample);

                                                                                // Applying the mask to the original image to obtain a foreground segment
                                                                                using (Aspose.Imaging.RasterImage originImage = (Aspose.Imaging.RasterImage)Aspose.Imaging.Image.Load(dir + "BigImage.jpg"))
                                                                                {
                                                                                    Aspose.Imaging.Masking.ImageMasking.ApplyMask(originImage, foregroundMask, maskingOptions);
                                                                                    originImage.Save(dir + "BigImage_foreground.png", exportOptions);
                                                                                }
                                                                            }
                                                                        }
                                                                    }

Resize(Инт, инт и ImageResizeSettings)

Рециклира изображението.

public abstract void Resize(int newWidth, int newHeight, ImageResizeSettings settings)

Parameters

newWidth int

Новата ширина.

newHeight int

Новата височина.

settings ImageResizeSettings

Изтегляне на настройките.

Examples

Рециклиране на изображението с помощта на специфичен Resize Type.

using (var image = Image.Load("Photo.jpg"))
                                                   {
                                                       image.Resize(640, 480, ResizeType.CatmullRom);
                                                       image.Save("ResizedPhoto.jpg");

                                                       image.Resize(1024, 768, ResizeType.CubicConvolution);
                                                       image.Save("ResizedPhoto2.jpg");

                                                       var resizeSettings = new ImageResizeSettings
                                                       {
                                                           Mode = ResizeType.CubicBSpline,
                                                           FilterType = ImageFilterType.SmallRectangular
                                                       };

                                                       image.Resize(800, 800, resizeSettings);
                                                       image.Save("ResizedPhoto3.jpg");
                                                   }

Възстановяване на EPS изображение с помощта на усъвършенствани настройки.

// Load EPS image
                                                    using (var image = Image.Load("AstrixObelix.eps"))
                                                    {
                                                        // Resize the image using advanced resize settings
                                                        image.Resize(400, 400, new ImageResizeSettings
                                                        {
                                                            // Set the interpolation mode
                                                            Mode = ResizeType.LanczosResample,

                                                            // Set the type of the filter
                                                            FilterType = ImageFilterType.SmallRectangular,

                                                            // Sets the color compare method
                                                            ColorCompareMethod = ColorCompareMethod.Euclidian,

                                                            // Set the color quantization method
                                                            ColorQuantizationMethod = ColorQuantizationMethod.Popularity
                                                        });

                                                        // Export image to PNG format
                                                        image.Save("ExportResult.png", new PngOptions());
                                                    }

Този пример натоварва изображение и го рецизира с помощта на различни настройки за възстановяване.

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

                                                                                      Aspose.Imaging.ImageResizeSettings resizeSettings = new Aspose.Imaging.ImageResizeSettings();

                                                                                      // The adaptive algorithm based on weighted and blended rational function and lanczos3 interpolation.
                                                                                      resizeSettings.Mode = Aspose.Imaging.ResizeType.AdaptiveResample;

                                                                                      // The small rectangular filter
                                                                                      resizeSettings.FilterType = Aspose.Imaging.ImageFilterType.SmallRectangular;

                                                                                      // The number of colors in the palette.
                                                                                      resizeSettings.EntriesCount = 256;

                                                                                      // The color quantization is not used
                                                                                      resizeSettings.ColorQuantizationMethod = ColorQuantizationMethod.None;

                                                                                      // The euclidian method
                                                                                      resizeSettings.ColorCompareMethod = ColorCompareMethod.Euclidian;

                                                                                      using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                      {
                                                                                          // Scale down by 2 times using adaptive resampling.
                                                                                          image.Resize(image.Width / 2, image.Height / 2, resizeSettings);
                                                                                          image.Save(dir + "downsample.adaptive.gif");
                                                                                      }

ResizeHeightProportionally(инт)

Използва се подразбиране Aspose.Imaging.ResizeType.NearestNeighbourResample.

public void ResizeHeightProportionally(int newHeight)

Parameters

newHeight int

Новата височина.

ResizeHeightProportionally(Изтегляне, ResizeType)

Намаляване на височината пропорционално.

public virtual void ResizeHeightProportionally(int newHeight, ResizeType resizeType)

Parameters

newHeight int

Новата височина.

resizeType ResizeType

Тип на възстановяване.

Examples

Този пример натоварва изображение и го рецизира пропорционално, използвайки различни методи за ресизиране. само височината е посочена, ширината се изчислява автоматично.

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

                                                                                                                                                                         using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                                                                                                         {
                                                                                                                                                                             // Scale up by 2 times using Nearest Neighbour resampling.
                                                                                                                                                                             image.ResizeHeightProportionally(image.Height* 2, Aspose.Imaging.ResizeType.NearestNeighbourResample);
                                                                                                                                                                             image.Save(dir + "upsample.nearestneighbour.gif");
                                                                                                                                                                         }

                                                                                                                                                                         using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                                                                                                         {
                                                                                                                                                                             // Scale down by 2 times using Nearest Neighbour resampling.
                                                                                                                                                                             image.ResizeHeightProportionally(image.Height / 2, Aspose.Imaging.ResizeType.NearestNeighbourResample);
                                                                                                                                                                             image.Save(dir + "upsample.nearestneighbour.gif");
                                                                                                                                                                         }

                                                                                                                                                                         using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                                                                                                         {
                                                                                                                                                                             // Scale up by 2 times using Bilinear resampling.
                                                                                                                                                                             image.ResizeHeightProportionally(image.Height* 2, Aspose.Imaging.ResizeType.BilinearResample);
                                                                                                                                                                             image.Save(dir + "upsample.bilinear.gif");
                                                                                                                                                                         }

                                                                                                                                                                         using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                                                                                                         {
                                                                                                                                                                             // Scale down by 2 times using Bilinear resampling.
                                                                                                                                                                             image.ResizeHeightProportionally(image.Height / 2, Aspose.Imaging.ResizeType.BilinearResample);
                                                                                                                                                                             image.Save(dir + "downsample.bilinear.gif");
                                                                                                                                                                         }

Използвайте маска за сегментиране, за да ускорите процеса на сегментация

// Masking export options
                                                                    Aspose.Imaging.ImageOptions.PngOptions exportOptions = new Aspose.Imaging.ImageOptions.PngOptions();
                                                                    exportOptions.ColorType = Aspose.Imaging.FileFormats.Png.PngColorType.TruecolorWithAlpha;
                                                                    exportOptions.Source = new Aspose.Imaging.Sources.StreamSource(new System.IO.MemoryStream());

                                                                    Aspose.Imaging.Masking.Options.MaskingOptions maskingOptions = new Aspose.Imaging.Masking.Options.MaskingOptions();

                                                                    // Use GraphCut clustering.
                                                                    maskingOptions.Method = Masking.Options.SegmentationMethod.GraphCut;
                                                                    maskingOptions.Decompose = false;
                                                                    maskingOptions.Args = new Aspose.Imaging.Masking.Options.AutoMaskingArgs();

                                                                    // The backgroung color will be transparent.
                                                                    maskingOptions.BackgroundReplacementColor = Aspose.Imaging.Color.Transparent;
                                                                    maskingOptions.ExportOptions = exportOptions;

                                                                    string dir = "c:\\temp\\";
                                                                    using (Aspose.Imaging.RasterImage image = (Aspose.Imaging.RasterImage)Aspose.Imaging.Image.Load(dir + "BigImage.jpg"))
                                                                    {
                                                                        Aspose.Imaging.Size imageSize = image.Size;

                                                                        // Reducing image size to speed up the segmentation process
                                                                        image.ResizeHeightProportionally(600, Aspose.Imaging.ResizeType.HighQualityResample);

                                                                        // Create an instance of the ImageMasking class.
                                                                        Aspose.Imaging.Masking.ImageMasking masking = new Aspose.Imaging.Masking.ImageMasking(image);

                                                                        // Divide the source image into several clusters (segments).
                                                                        using (Aspose.Imaging.Masking.Result.MaskingResult maskingResult = masking.Decompose(maskingOptions))
                                                                        {
                                                                            // Getting the foreground mask
                                                                            using (Aspose.Imaging.RasterImage foregroundMask = maskingResult[1].GetMask()) 
                                                                            {
                                                                                // Increase the size of the mask to the size of the original image
                                                                                foregroundMask.Resize(imageSize.Width, imageSize.Height, Aspose.Imaging.ResizeType.NearestNeighbourResample);

                                                                                // Applying the mask to the original image to obtain a foreground segment
                                                                                using (Aspose.Imaging.RasterImage originImage = (Aspose.Imaging.RasterImage)Aspose.Imaging.Image.Load(dir + "BigImage.jpg"))
                                                                                {
                                                                                    Aspose.Imaging.Masking.ImageMasking.ApplyMask(originImage, foregroundMask, maskingOptions);
                                                                                    originImage.Save(dir + "BigImage_foreground.png", exportOptions);
                                                                                }
                                                                            }
                                                                        }
                                                                    }

ResizeHeightProportionally(Източник: ImageResizeSettings)

Намаляване на височината пропорционално.

public virtual void ResizeHeightProportionally(int newHeight, ImageResizeSettings settings)

Parameters

newHeight int

Новата височина.

settings ImageResizeSettings

Снимката възстановява настройките.

ResizeWidthProportionally(инт)

Използва се подразбиране Aspose.Imaging.ResizeType.NearestNeighbourResample.

public void ResizeWidthProportionally(int newWidth)

Parameters

newWidth int

Новата ширина.

ResizeWidthProportionally(Изтегляне, ResizeType)

Пропорционално рециклира ширината.

public virtual void ResizeWidthProportionally(int newWidth, ResizeType resizeType)

Parameters

newWidth int

Новата ширина.

resizeType ResizeType

Тип на възстановяване.

Examples

Този пример натоварва изображението и го рецизира пропорционално, като използва различни методи за ресизиране. само ширината е посочена, височината се изразява автоматично.

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

                                                                                                                                                                         using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                                                                                                         {
                                                                                                                                                                             // Scale up by 2 times using Nearest Neighbour resampling.
                                                                                                                                                                             image.ResizeWidthProportionally(image.Width* 2, Aspose.Imaging.ResizeType.NearestNeighbourResample);
                                                                                                                                                                             image.Save(dir + "upsample.nearestneighbour.gif");
                                                                                                                                                                         }

                                                                                                                                                                         using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                                                                                                         {
                                                                                                                                                                             // Scale down by 2 times using Nearest Neighbour resampling.
                                                                                                                                                                             image.ResizeWidthProportionally(image.Width / 2, Aspose.Imaging.ResizeType.NearestNeighbourResample);
                                                                                                                                                                             image.Save(dir + "downsample.nearestneighbour.gif");
                                                                                                                                                                         }

                                                                                                                                                                         using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                                                                                                         {
                                                                                                                                                                             // Scale up by 2 times using Bilinear resampling.
                                                                                                                                                                             image.ResizeWidthProportionally(image.Width* 2, Aspose.Imaging.ResizeType.BilinearResample);
                                                                                                                                                                             image.Save(dir + "upsample.bilinear.gif");
                                                                                                                                                                         }

                                                                                                                                                                         using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.gif"))
                                                                                                                                                                         {
                                                                                                                                                                             // Scale down by 2 times using Bilinear resampling.
                                                                                                                                                                             image.ResizeWidthProportionally(image.Width / 2, Aspose.Imaging.ResizeType.BilinearResample);
                                                                                                                                                                             image.Save(dir + "downsample.bilinear.gif");
                                                                                                                                                                         }

ResizeWidthProportionally(Източник: ImageResizeSettings)

Пропорционално рециклира ширината.

public virtual void ResizeWidthProportionally(int newWidth, ImageResizeSettings settings)

Parameters

newWidth int

Новата ширина.

settings ImageResizeSettings

Снимката възстановява настройките.

Rotate(Флота)

Снимка се върти около центъра.

public virtual void Rotate(float angle)

Parameters

angle float

Позитивните стойности ще се въртят по часовника.

RotateFlip(RotateFlipType)

Ротира, флипсва или ротира и флепва изображението.

public abstract void RotateFlip(RotateFlipType rotateFlipType)

Parameters

rotateFlipType RotateFlipType

Типът на ротативния флип.

Examples

Примерът изтегля съществуващ файл на изображението от определено местоположение на диска и изпълнява операцията на ротацията върху снимката според стойността на Enum Aspose.Imaging.RotateFlipType

//Create an instance of image class and initialize it with an existing image file through File path
                                                                                                                                                                                                                                                       using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(@"C:\temp\sample.bmp"))
                                                                                                                                                                                                                                                       {
                                                                                                                                                                                                                                                           //Rotate the image at 180 degree about X axis
                                                                                                                                                                                                                                                           image.RotateFlip(Aspose.Imaging.RotateFlipType.Rotate180FlipX);

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

Този пример натоварва изображение, го върти на 90 градуса и опционално флипира изображението хоризонтално и/или вертикално.

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

                                                                                                                                          Aspose.Imaging.RotateFlipType[] rotateFlipTypes = new Aspose.Imaging.RotateFlipType[]
                                                                                                                                          {
                                                                                                                                              Aspose.Imaging.RotateFlipType.Rotate90FlipNone,
                                                                                                                                              Aspose.Imaging.RotateFlipType.Rotate90FlipX,
                                                                                                                                              Aspose.Imaging.RotateFlipType.Rotate90FlipXY,
                                                                                                                                              Aspose.Imaging.RotateFlipType.Rotate90FlipY,
                                                                                                                                          };

                                                                                                                                          foreach (Aspose.Imaging.RotateFlipType rotateFlipType in rotateFlipTypes)
                                                                                                                                          {
                                                                                                                                              // Rotate, flip and save to the output file.
                                                                                                                                              using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.bmp"))
                                                                                                                                              {
                                                                                                                                                  image.RotateFlip(rotateFlipType);
                                                                                                                                                  image.Save(dir + "sample." + rotateFlipType + ".bmp");
                                                                                                                                              }
                                                                                                                                          }

Този пример зарежда изображение на ODG, го върти на 90 градуса и опционално флипира изображението хоризонтално и/или вертикално.

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

                                                                                                                                             Aspose.Imaging.RotateFlipType[] rotateFlipTypes = new Aspose.Imaging.RotateFlipType[]
                                                                                                                                             {
                                                                                                                                                 Aspose.Imaging.RotateFlipType.Rotate90FlipNone,
                                                                                                                                                 Aspose.Imaging.RotateFlipType.Rotate90FlipX,
                                                                                                                                                 Aspose.Imaging.RotateFlipType.Rotate90FlipXY,
                                                                                                                                                 Aspose.Imaging.RotateFlipType.Rotate90FlipY,
                                                                                                                                             };

                                                                                                                                             foreach (Aspose.Imaging.Image rotateFlipType in rotateFlipTypes)
                                                                                                                                             {
                                                                                                                                                 // Rotate, flip and save to the output file.
                                                                                                                                                 using (Aspose.Imaging.Image image = (Aspose.Imaging.FileFormats.OpenDocument.OdImage)Aspose.Imaging.Image.Load(dir + "sample.odg"))
                                                                                                                                                 {
                                                                                                                                                     image.RotateFlip(rotateFlipType);
                                                                                                                                                     image.Save(dir + "sample." + rotateFlipType + ".png", new Aspose.Imaging.ImageOptions.PngOptions());
                                                                                                                                                 }
                                                                                                                                             }

Save()

Съхранява данните на изображението в основния поток.

public override sealed void Save()

Examples

Следващият пример показва как да се съхранява интегрирана BMP изображение или част от него в файл или поток.

string dir = "c:\\temp\\";
                                                                                                          using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.bmp"))
                                                                                                          {
                                                                                                              Aspose.Imaging.FileFormats.Bmp.BmpImage bmpImage = (Aspose.Imaging.FileFormats.Bmp.BmpImage)image;

                                                                                                              // Convert to a black-white image
                                                                                                              bmpImage.BinarizeOtsu();

                                                                                                              // Save to the same location with default options.
                                                                                                              image.Save();

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

                                                                                                              // A palette contains only two colors: Black and White in this case.
                                                                                                              saveOptions.Palette = Aspose.Imaging.ColorPaletteHelper.CreateMonochrome();

                                                                                                              // For all monochrome images (including black-white ones) it is enough to allocate 1 bit per pixel.
                                                                                                              saveOptions.BitsPerPixel = 1;

                                                                                                              // Save to another location with the specified options.
                                                                                                              image.Save(dir + "sample.bw.palettized.bmp", saveOptions);

                                                                                                              // Save only the central part of the image.
                                                                                                              Aspose.Imaging.Rectangle bounds = new Aspose.Imaging.Rectangle(image.Width / 4, image.Height / 4, image.Width / 2, image.Height / 2);
                                                                                                              image.Save(dir + "sample.bw.palettized.part.bmp", saveOptions, bounds);

                                                                                                              // Save the entire image to a memory stream
                                                                                                              using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                                                                                                              {
                                                                                                                  image.Save(stream, saveOptions);
                                                                                                                  System.Console.WriteLine("The size of the whole image in bytes: {0}", stream.Length);
                                                                                                              }

                                                                                                              // Save the central part of the image to a memory stream
                                                                                                              using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                                                                                                              {
                                                                                                                  image.Save(stream, saveOptions, bounds);
                                                                                                                  System.Console.WriteLine("The size of the central part of the image in bytes: {0}", stream.Length);
                                                                                                              }
                                                                                                          }
                                                                                                          //The output may look like this:
                                                                                                          //The size of the whole image in bytes: 24062
                                                                                                          //The size of the central part of the image in bytes: 6046

Save(Стрий)

Съхранява изображението до посоченото местоположение на файла.

public override void Save(string filePath)

Parameters

filePath string

Пътят на файла за съхранение на изображението.

Save(Снимка, ImageOptionsBase)

Съхранява данните на обекта до посоченото местоположение на файла в посочения файлов формат в съответствие с опциите за съхранение.

public virtual void Save(string filePath, ImageOptionsBase options)

Parameters

filePath string

Пътят на файла.

options ImageOptionsBase

и възможностите.

Examples

Следващият пример изтегля BMP изображение от файл, а след това съхранява изображението в PNG файл.

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

                                                                                                   using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.bmp"))
                                                                                                   {
                                                                                                       // Save the entire image to a PNG file.
                                                                                                       Aspose.Imaging.ImageOptions.PngOptions saveOptions = new Aspose.Imaging.ImageOptions.PngOptions();
                                                                                                       image.Save(dir + "output.png", saveOptions);
                                                                                                   }

За да демонстрираме тази операция, изтегляме съществуващ файл от определено местоположение на диска, изпълняваме операцията Rotate върху изображението и Save the image in PSD format using File Path.

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

                                                                                                                                                                                                                                         //Create an instance of image class and initialize it with an existing file through File path
                                                                                                                                                                                                                                         using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.bmp"))
                                                                                                                                                                                                                                         {
                                                                                                                                                                                                                                             //Rotate the image at 180 degree about X axis
                                                                                                                                                                                                                                             image.RotateFlip(Aspose.Imaging.RotateFlipType.Rotate180FlipX);

                                                                                                                                                                                                                                             //Save the Image as PSD to File Path with default PsdOptions settings
                                                                                                                                                                                                                                             image.Save(dir + "output.psd", new Aspose.Imaging.ImageOptions.PsdOptions());
                                                                                                                                                                                                                                         }

Следващият пример показва как да се съхранява интегрирана BMP изображение или част от него в файл или поток.

string dir = "c:\\temp\\";
                                                                                                          using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.bmp"))
                                                                                                          {
                                                                                                              Aspose.Imaging.FileFormats.Bmp.BmpImage bmpImage = (Aspose.Imaging.FileFormats.Bmp.BmpImage)image;

                                                                                                              // Convert to a black-white image
                                                                                                              bmpImage.BinarizeOtsu();

                                                                                                              // Save to the same location with default options.
                                                                                                              image.Save();

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

                                                                                                              // A palette contains only two colors: Black and White in this case.
                                                                                                              saveOptions.Palette = Aspose.Imaging.ColorPaletteHelper.CreateMonochrome();

                                                                                                              // For all monochrome images (including black-white ones) it is enough to allocate 1 bit per pixel.
                                                                                                              saveOptions.BitsPerPixel = 1;

                                                                                                              // Save to another location with the specified options.
                                                                                                              image.Save(dir + "sample.bw.palettized.bmp", saveOptions);

                                                                                                              // Save only the central part of the image.
                                                                                                              Aspose.Imaging.Rectangle bounds = new Aspose.Imaging.Rectangle(image.Width / 4, image.Height / 4, image.Width / 2, image.Height / 2);
                                                                                                              image.Save(dir + "sample.bw.palettized.part.bmp", saveOptions, bounds);

                                                                                                              // Save the entire image to a memory stream
                                                                                                              using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                                                                                                              {
                                                                                                                  image.Save(stream, saveOptions);
                                                                                                                  System.Console.WriteLine("The size of the whole image in bytes: {0}", stream.Length);
                                                                                                              }

                                                                                                              // Save the central part of the image to a memory stream
                                                                                                              using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                                                                                                              {
                                                                                                                  image.Save(stream, saveOptions, bounds);
                                                                                                                  System.Console.WriteLine("The size of the central part of the image in bytes: {0}", stream.Length);
                                                                                                              }
                                                                                                          }
                                                                                                          //The output may look like this:
                                                                                                          //The size of the whole image in bytes: 24062
                                                                                                          //The size of the central part of the image in bytes: 6046

Save(Стъпка, ImageOptionsBase, Rectangle)

Съхранява данните на обекта до посоченото местоположение на файла в посочения файлов формат в съответствие с опциите за съхранение.

public virtual void Save(string filePath, ImageOptionsBase options, Rectangle boundsRectangle)

Parameters

filePath string

Пътят на файла.

options ImageOptionsBase

и възможностите.

boundsRectangle Rectangle

Намерете празен правоъгълник, за да използвате източните граници.

Examples

Следващият пример изтегля BMP изображение от файл, след което съхранява правоъгълна част на изображението в PNG файл.

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

                                                                                                                         using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.bmp"))
                                                                                                                         {
                                                                                                                             // Save the upper half of the image to a PNG file.
                                                                                                                             Aspose.Imaging.ImageOptions.PngOptions saveOptions = new Aspose.Imaging.ImageOptions.PngOptions();
                                                                                                                             Aspose.Imaging.Rectangle bounds = new Aspose.Imaging.Rectangle(0, 0, image.Width, image.Height / 2);
                                                                                                                             image.Save(dir + "output.png", saveOptions, bounds);
                                                                                                                         }

Следващият пример показва как да се съхранява интегрирана BMP изображение или част от него в файл или поток.

string dir = "c:\\temp\\";
                                                                                                          using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.bmp"))
                                                                                                          {
                                                                                                              Aspose.Imaging.FileFormats.Bmp.BmpImage bmpImage = (Aspose.Imaging.FileFormats.Bmp.BmpImage)image;

                                                                                                              // Convert to a black-white image
                                                                                                              bmpImage.BinarizeOtsu();

                                                                                                              // Save to the same location with default options.
                                                                                                              image.Save();

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

                                                                                                              // A palette contains only two colors: Black and White in this case.
                                                                                                              saveOptions.Palette = Aspose.Imaging.ColorPaletteHelper.CreateMonochrome();

                                                                                                              // For all monochrome images (including black-white ones) it is enough to allocate 1 bit per pixel.
                                                                                                              saveOptions.BitsPerPixel = 1;

                                                                                                              // Save to another location with the specified options.
                                                                                                              image.Save(dir + "sample.bw.palettized.bmp", saveOptions);

                                                                                                              // Save only the central part of the image.
                                                                                                              Aspose.Imaging.Rectangle bounds = new Aspose.Imaging.Rectangle(image.Width / 4, image.Height / 4, image.Width / 2, image.Height / 2);
                                                                                                              image.Save(dir + "sample.bw.palettized.part.bmp", saveOptions, bounds);

                                                                                                              // Save the entire image to a memory stream
                                                                                                              using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                                                                                                              {
                                                                                                                  image.Save(stream, saveOptions);
                                                                                                                  System.Console.WriteLine("The size of the whole image in bytes: {0}", stream.Length);
                                                                                                              }

                                                                                                              // Save the central part of the image to a memory stream
                                                                                                              using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                                                                                                              {
                                                                                                                  image.Save(stream, saveOptions, bounds);
                                                                                                                  System.Console.WriteLine("The size of the central part of the image in bytes: {0}", stream.Length);
                                                                                                              }
                                                                                                          }
                                                                                                          //The output may look like this:
                                                                                                          //The size of the whole image in bytes: 24062
                                                                                                          //The size of the central part of the image in bytes: 6046

Exceptions

ArgumentNullException

Опции

ImageSaveException

Спасяването на изображенията се провали.

Save(Източник: ImageOptionsBase)

Съхранява данните на изображението в посочения поток във формат на файла в съответствие с опциите за съхранение.

public void Save(Stream stream, ImageOptionsBase optionsBase)

Parameters

stream Stream

Потокът за съхранение на данните на изображението.

optionsBase ImageOptionsBase

Възможностите за спасяване.

Examples

Следващият пример изтегля изображение от файл, а след това съхранява изображението в PNG файлов поток.

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

                                                                                                       using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.bmp"))
                                                                                                       {
                                                                                                           Aspose.Imaging.ImageOptions.PngOptions saveOptions = new Aspose.Imaging.ImageOptions.PngOptions();
                                                                                                           using (System.IO.Stream outputStream = System.IO.File.Open(dir + "output.png", System.IO.FileMode.Create))
                                                                                                           {
                                                                                                               // Save the entire image to a file stream.
                                                                                                               image.Save(outputStream, saveOptions);
                                                                                                           }
                                                                                                       }

Този пример показва процеса на Съхранение на изображение в MemoryStream. За да се демонстрира тази операция, примерът изтегля съществуващ файл от определено местоположение на диска, изпълнява операцията Rotate върху изображението и Save the image in PSD format

//Create an instance of MemoryStream
                                                                                                                                                                                                                                            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                                                                                                                                                                                                                                            {
                                                                                                                                                                                                                                                //Create an instance of image class and initialize it with an existing file through File path
                                                                                                                                                                                                                                                using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(@"C:\temp\sample.bmp"))
                                                                                                                                                                                                                                                {
                                                                                                                                                                                                                                                    //Rotate the image at 180 degree about X axis
                                                                                                                                                                                                                                                    image.RotateFlip(Aspose.Imaging.RotateFlipType.Rotate180FlipX);

                                                                                                                                                                                                                                                    //Save the Image as PSD to MemoryStream with default PsdOptions settings
                                                                                                                                                                                                                                                    image.Save(stream, new Aspose.Imaging.ImageOptions.PsdOptions());
                                                                                                                                                                                                                                                }
                                                                                                                                                                                                                                            }

Следващият пример показва как да се съхранява интегрирана BMP изображение или част от него в файл или поток.

string dir = "c:\\temp\\";
                                                                                                          using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.bmp"))
                                                                                                          {
                                                                                                              Aspose.Imaging.FileFormats.Bmp.BmpImage bmpImage = (Aspose.Imaging.FileFormats.Bmp.BmpImage)image;

                                                                                                              // Convert to a black-white image
                                                                                                              bmpImage.BinarizeOtsu();

                                                                                                              // Save to the same location with default options.
                                                                                                              image.Save();

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

                                                                                                              // A palette contains only two colors: Black and White in this case.
                                                                                                              saveOptions.Palette = Aspose.Imaging.ColorPaletteHelper.CreateMonochrome();

                                                                                                              // For all monochrome images (including black-white ones) it is enough to allocate 1 bit per pixel.
                                                                                                              saveOptions.BitsPerPixel = 1;

                                                                                                              // Save to another location with the specified options.
                                                                                                              image.Save(dir + "sample.bw.palettized.bmp", saveOptions);

                                                                                                              // Save only the central part of the image.
                                                                                                              Aspose.Imaging.Rectangle bounds = new Aspose.Imaging.Rectangle(image.Width / 4, image.Height / 4, image.Width / 2, image.Height / 2);
                                                                                                              image.Save(dir + "sample.bw.palettized.part.bmp", saveOptions, bounds);

                                                                                                              // Save the entire image to a memory stream
                                                                                                              using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                                                                                                              {
                                                                                                                  image.Save(stream, saveOptions);
                                                                                                                  System.Console.WriteLine("The size of the whole image in bytes: {0}", stream.Length);
                                                                                                              }

                                                                                                              // Save the central part of the image to a memory stream
                                                                                                              using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                                                                                                              {
                                                                                                                  image.Save(stream, saveOptions, bounds);
                                                                                                                  System.Console.WriteLine("The size of the central part of the image in bytes: {0}", stream.Length);
                                                                                                              }
                                                                                                          }
                                                                                                          //The output may look like this:
                                                                                                          //The size of the whole image in bytes: 24062
                                                                                                          //The size of the central part of the image in bytes: 6046

Exceptions

ArgumentNullException

Опции на база

ArgumentException

Не може да се съхранява в посочения формат, тъй като в момента не се поддържа; опцииBase

ImageSaveException

Износът на изображения се провали.

Save(Поток, ImageOptionsBase, Rectangle)

Съхранява данните на изображението в посочения поток във формат на файла в съответствие с опциите за съхранение.

public virtual void Save(Stream stream, ImageOptionsBase optionsBase, Rectangle boundsRectangle)

Parameters

stream Stream

Потокът за съхранение на данните на изображението.

optionsBase ImageOptionsBase

Възможностите за спасяване.

boundsRectangle Rectangle

Снимката на дестинацията се ограничава с правоъгълност.Настройки на празен правоугас за използване на източните граници.

Examples

Следващият пример изтегля изображение от файл, а след това съхранява правоъгълна част от изображението в PNG файлов поток.

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

                                                                                                                             using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.bmp"))
                                                                                                                             {
                                                                                                                                 Aspose.Imaging.ImageOptions.PngOptions saveOptions = new Aspose.Imaging.ImageOptions.PngOptions();
                                                                                                                                 Aspose.Imaging.Rectangle bounds = new Aspose.Imaging.Rectangle(0, 0, image.Width, image.Height / 2);
                                                                                                                                 using (System.IO.Stream outputStream = System.IO.File.Open(dir + "sample.output.png", System.IO.FileMode.Create))
                                                                                                                                 {
                                                                                                                                     // Save the upper half of the image to a file stream.
                                                                                                                                     image.Save(outputStream, saveOptions, bounds);
                                                                                                                                 }
                                                                                                                             }

Следващият пример показва как да се съхранява интегрирана BMP изображение или част от него в файл или поток.

string dir = "c:\\temp\\";
                                                                                                          using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.bmp"))
                                                                                                          {
                                                                                                              Aspose.Imaging.FileFormats.Bmp.BmpImage bmpImage = (Aspose.Imaging.FileFormats.Bmp.BmpImage)image;

                                                                                                              // Convert to a black-white image
                                                                                                              bmpImage.BinarizeOtsu();

                                                                                                              // Save to the same location with default options.
                                                                                                              image.Save();

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

                                                                                                              // A palette contains only two colors: Black and White in this case.
                                                                                                              saveOptions.Palette = Aspose.Imaging.ColorPaletteHelper.CreateMonochrome();

                                                                                                              // For all monochrome images (including black-white ones) it is enough to allocate 1 bit per pixel.
                                                                                                              saveOptions.BitsPerPixel = 1;

                                                                                                              // Save to another location with the specified options.
                                                                                                              image.Save(dir + "sample.bw.palettized.bmp", saveOptions);

                                                                                                              // Save only the central part of the image.
                                                                                                              Aspose.Imaging.Rectangle bounds = new Aspose.Imaging.Rectangle(image.Width / 4, image.Height / 4, image.Width / 2, image.Height / 2);
                                                                                                              image.Save(dir + "sample.bw.palettized.part.bmp", saveOptions, bounds);

                                                                                                              // Save the entire image to a memory stream
                                                                                                              using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                                                                                                              {
                                                                                                                  image.Save(stream, saveOptions);
                                                                                                                  System.Console.WriteLine("The size of the whole image in bytes: {0}", stream.Length);
                                                                                                              }

                                                                                                              // Save the central part of the image to a memory stream
                                                                                                              using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                                                                                                              {
                                                                                                                  image.Save(stream, saveOptions, bounds);
                                                                                                                  System.Console.WriteLine("The size of the central part of the image in bytes: {0}", stream.Length);
                                                                                                              }
                                                                                                          }
                                                                                                          //The output may look like this:
                                                                                                          //The size of the whole image in bytes: 24062
                                                                                                          //The size of the central part of the image in bytes: 6046

Exceptions

ArgumentNullException

Опции на база

ArgumentException

Не може да се съхранява в посочения формат, тъй като в момента не се поддържа; опцииBase

ImageSaveException

Износът на изображения се провали.

SetPalette(Изолация, Bool)

Поставете палетата на изображението.

public abstract void SetPalette(IColorPalette palette, bool updateColors)

Parameters

palette IColorPalette

Палетата трябва да бъде поставена.

updateColors bool

ако сте зададени на “истински” цветове ще бъдат актуализирани в съответствие с новата палета; в противен случай индексите на цветовете остават непроменени.

UpdateContainer(Image)

Актуализирайте контейнера.

protected void UpdateContainer(Image container)

Parameters

container Image

и контейнера.

Вижте също

DataStreamSupporter , IObjectWithBounds

 Български