Class Image
Название пространства: Aspose.Imaging Ассоциация: Aspose.Imaging.dll (25.5.0)
Изображение является базовым классом для всех видов изображений.
[JsonObject(MemberSerialization.OptIn)]
public abstract class Image : DataStreamSupporter, IDisposable, IObjectWithBoundsInheritance
object ← DisposableObject ← DataStreamSupporter ← Image
Derived
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");
}
}Рециклировать изображение с помощью конкретного типа рецилирования.
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. Некоторые свойства для примера Bmoptions устанавливаются перед созданием реальной картины.
//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; }Стоимость недвижимости
BackgroundColor
Получается или устанавливается значение для цвета фонов.
public virtual Color BackgroundColor { get; set; }Стоимость недвижимости
BitsPerPixel
Получает биты изображения по числу пикселей.
public abstract int BitsPerPixel { get; }Стоимость недвижимости
Bounds
Получите границы изображения.
public Rectangle Bounds { get; }Стоимость недвижимости
BufferSizeHint
Получается или устанавливается указание размеров буфера, которое определяется максимальным разрешенным размером для всех внутренних буферов.
public int BufferSizeHint { get; set; }Стоимость недвижимости
Container
Получите контейнер Aspose.Imaging.Изображение.
public Image Container { get; }Стоимость недвижимости
Remarks
Если это имущество не нулевое, то оно указывает на то, что изображение содержится в другом изображении.
FileFormat
Получается значение файлового формата
public virtual FileFormat FileFormat { get; }Стоимость недвижимости
HasBackgroundColor
Получается или устанавливается значение, указывающее на то, имеет ли изображение цвет фонов.
public virtual bool HasBackgroundColor { get; set; }Стоимость недвижимости
Height
Получается высота изображения.
public abstract int Height { get; }Стоимость недвижимости
InterruptMonitor
Получить или установить перерыв монитора.
public InterruptMonitor InterruptMonitor { get; set; }Стоимость недвижимости
Palette
Получается или устанавливается цветная палетка. цветная палетка не используется при непосредственном представлении пикселей.
public IColorPalette Palette { get; set; }Стоимость недвижимости
Size
Получите размер изображения.
public Size Size { get; }Стоимость недвижимости
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: 1UsePalette
Получается значение, указывающее, используется ли палетка изображения.
public virtual bool UsePalette { get; }Стоимость недвижимости
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; }Стоимость недвижимости
Methods
CanLoad(Стриг)
Определяет, можно ли загрузить изображение с указанного файлового пути.
public static bool CanLoad(string filePath)Parameters
filePath string
Доступный файл маршрута.
Returns
«Правда», если изображение может быть загружено из указанного файла; в противном случае, «фальшивое».
Examples
Этот пример определяет, можно ли загрузить изображение из файла.
// Use an absolute path to the file
bool canLoad = Aspose.Imaging.Image.CanLoad(@"c:\temp\sample.gif");CanLoad(Стриг, LoadOptions)
Определяет, можно ли загрузить изображение с указанного файлового пути и опционально использует указанные открытые варианты.
public static bool CanLoad(string filePath, LoadOptions loadOptions)Parameters
filePath string
Доступный файл маршрута.
loadOptions LoadOptions
Возможность загрузки опций.
Returns
«Правда», если изображение может быть загружено из указанного файла; в противном случае, «фальшивое».
CanLoad(Stream)
Определяет, можно ли загрузить изображение из указанного потока.
public static bool CanLoad(Stream stream)Parameters
stream Stream
Проток для загрузки.
Returns
«Правда», если изображение может быть загружено из указанного потока; в противном случае, «фальшивое».
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
«Правда», если изображение может быть загружено из указанного потока; в противном случае, «фальшивое».
CanSave(ImageOptionsBase)
Определяет, может ли изображение быть сохранено в указанный формат файла, представленный прошлыми вариантами сохранения.
public bool CanSave(ImageOptionsBase options)Parameters
options ImageOptionsBase
Сохранение вариантов для использования.
Returns
«Правда», если изображение может быть сохранено в указанном формате файла, представленном прошлым вариантом сохранения; в противном случае, «фальшивое».
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, int)
Создание нового изображения с использованием указанных вариантов создания.
public static Image Create(ImageOptionsBase imageOptions, int width, int height)Parameters
imageOptions ImageOptionsBase
Опции для изображения.
width int
и широты .
height int
и высоты .
Returns
Новое созданное изображение.
Examples
Этот пример создает новый файл изображения на некотором местоположении диска, как это указано свойством источника в примере BmpOptions. Некоторые свойства для примера Bmoptions устанавливаются перед созданием реальной картины.
//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
Изображение как IMultipageImage
Create(MultipageCreateOptions)
Создает определенную мультистраницу, создает варианты.
public static Image Create(MultipageCreateOptions multipageCreateOptions)Parameters
multipageCreateOptions MultipageCreateOptions
Многостраница создает варианты.
Returns
Многостраничное изображение
Create(Стриг[ ], Боол)
Создает многостраничное изображение, содержащее указанные файлы.
public static Image Create(string[] files, bool throwExceptionOnLoadError)Parameters
files string
[ ]
и файлов .
throwExceptionOnLoadError bool
Если вы настроены на «Правда» [сбросить исключение на ошибку загрузки].
Returns
Многостраничное изображение
Create(Стриг[])
Создает многостраничное изображение, содержащее указанные файлы.
public static Image Create(string[] files)Parameters
files string
[ ]
и файлов .
Returns
Многостраничное изображение
Create(Image[ ], Боол)
Создает новое изображение указанных изображений как страниц.
public static Image Create(Image[] images, bool disposeImages)Parameters
images Image
[ ]
и изображениями .
disposeImages bool
Если вы настроены на «истинный» [доставите изображения].
Returns
Изображение как 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
Они не могут сохранить сообщение.
GetDefaultOptions(Объекты[])
Получите стандартные варианты.
public virtual ImageOptionsBase GetDefaultOptions(object[] args)Parameters
args object
[ ]
и аргументов .
Returns
Стандартные варианты
GetFileFormat(Стриг)
Получается формат файла.
public static FileFormat GetFileFormat(string filePath)Parameters
filePath string
Доступный файл маршрута.
Returns
Определенный формат файла.
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
Определенный формат файла.
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
Подходящий прямоугольник
GetFitRectangle(Ректоуголь, int[])
Получается прямоугольник, который соответствует текущей битмапе с учетом прошедших пикселей. Прошедшие пикселы должны быть равными размеру соответствующего прямоугольника.
protected Rectangle GetFitRectangle(Rectangle rectangle, int[] pixels)Parameters
rectangle Rectangle
Прямой для того, чтобы получить подходящий прямоуголь.
pixels int
[ ]
32-битные ARGB пиксели.
Returns
Подходит для прямоугольника.
GetFittingRectangle(Ректоуголь, int, int)
Получается прямоугольник, который соответствует текущему изображению.
public static Rectangle GetFittingRectangle(Rectangle rectangle, int width, int height)Parameters
rectangle Rectangle
Прямой для того, чтобы получить подходящий прямоуголь.
width int
Объект ширины.
height int
Высота объекта.
Returns
Подходящий прямоугольник или исключение, если нет подходящего прямоугольника.
GetFittingRectangle(Ректоуголь, int[ ], 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
Подходящий прямоугольник или исключение, если нет подходящего прямоугольника.
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
Образ для экспорта
GetOriginalOptions()
Получает опции, основанные на первоначальных настройках файла.Это может быть полезным для сохранения детальной глубины и других параметров оригинального изображения неизменными.Например, если мы загружаем черно-белый PNG-изображение с 1 битом на пиксель, а затем сохраним его с помощьюAspose.Imaging.DataStreamSupporter.Save(System.String) метод, выходный PNG изображение с 8-битным на пиксель будет производиться.Чтобы избежать этого и сохранить изображение PNG на 1 бит на пиксель, используйте этот метод, чтобы получить соответствующие варианты сохранения и пройти их.В качестве второго параметра используется метод Aspose.Imaging.Image.Save (System.String,Aspose,ImageOptionsBase).
public virtual ImageOptionsBase GetOriginalOptions()Returns
Опции, основанные на первоначальных настройках файла.
GetProportionalHeight(Инт, Инт, Инт)
Получается пропорциональная высота.
public static int GetProportionalHeight(int width, int height, int newWidth)Parameters
width int
и широты .
height int
и высоты .
newWidth int
Новая ширина .
Returns
Пропорциональная высота .
GetProportionalWidth(Инт, Инт, Инт)
Получается пропорциональная ширина.
public static int GetProportionalWidth(int width, int height, int newHeight)Parameters
width int
и широты .
height int
и высоты .
newHeight int
Новая высота .
Returns
Пропорциональная ширина .
GetSerializedStream(ImageOptionsBase, Rectangle, out int)
Конвертируются в APS.
public virtual Stream GetSerializedStream(ImageOptionsBase imageOptions, Rectangle clippingRectangle, out int pageNumber)Parameters
imageOptions ImageOptionsBase
Опции для изображения.
clippingRectangle Rectangle
Клейпинг прямоугольника .
pageNumber int
Номер страницы .
Returns
Сериализированный поток
Load(Стриг, LoadOptions)
Если filePath" является файловым маршрутом, то метод только открывает файл.Если <cod class=paramaFilePat’ является URL, метод загружает файл, хранит его в качестве временного маршрута, и откроет его.
public static Image Load(string filePath, LoadOptions loadOptions)Parameters
filePath string
Путь файла или URL для загрузки изображения из.
loadOptions LoadOptions
Возможность загрузки опций.
Returns
Загруженное изображение .
Load(Стриг)
Если filePath" является файловым маршрутом, то метод только открывает файл.Если <cod class=paramaFilePat’ является URL, метод загружает файл, хранит его в качестве временного маршрута, и откроет его.
public static Image Load(string filePath)Parameters
filePath string
Путь файла или URL для загрузки изображения из.
Returns
Загруженное изображение .
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
Загруженное изображение .
Load(Stream)
Загрузить новое изображение из указанного потока.
public static Image Load(Stream stream)Parameters
stream Stream
Поток для загрузки изображения из.
Returns
Загруженное изображение .
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(Коллекция, Коллекция, Коллекция)
Назовите, когда палет меняется.
protected virtual void OnPaletteChanged(IColorPalette oldPalette, IColorPalette newPalette)Parameters
oldPalette IColorPalette
Старый палец
newPalette IColorPalette
Новая палитра .
OnPaletteChanging(Коллекция, Коллекция, Коллекция)
Назовите, когда палет меняется.
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(int, int, resizeType)
Изображение восстанавливается.
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());
}Рециклировать изображение с помощью конкретного типа рецилирования.
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(int, int, ImageResizeНастройки)
Изображение восстанавливается.
public abstract void Resize(int newWidth, int newHeight, ImageResizeSettings settings)Parameters
newWidth int
Новая ширина .
newHeight int
Новая высота .
settings ImageResizeSettings
Рецидивные настройки .
Examples
Рециклировать изображение с помощью конкретного типа рецилирования.
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
Пример загружает существующий файл изображения с определенного местоположения диска и выполняет операцию Rotate на изображении по значению 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: 6046Save(Стриг)
Сохранить изображение в указанное местоположение файла.
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);
}Для демонстрации этой операции мы загружаем существующий файл с определенного местоположения диска, выполняем операцию «Ротация» на изображении и сохраняем изображение в формате PSD с помощью файлового маршрута.
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: 6046Save(Стриг, 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: 6046Exceptions
Опции
Спасение изображения провалилось.
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);
}
}Для демонстрации этой операции пример загружает существующий файл с определенного местоположения диска, выполняет операцию «Ротация» на изображении и «Спасите изображение» в формате PSD.
//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: 6046Exceptions
опционы
Нельзя хранить в указанном формате, так как в данный момент он не поддерживается; опции
Экспорт изображений провалился.
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: 6046Exceptions
опционы
Нельзя хранить в указанном формате, так как в данный момент он не поддерживается; опции
Экспорт изображений провалился.
SetPalette(Иосиф Палет, Боол)
Сделайте палету изображения.
public abstract void SetPalette(IColorPalette palette, bool updateColors)Parameters
palette IColorPalette
Палеты для установки.
updateColors bool
Если настроены на “истинные” цвета будут обновлены в соответствии с новым палетом; в противном случае индексы цвета остаются неизменными. Обратите внимание, что неизменные индексы могут разрушить изображение на загрузке, если некоторые индексы не имеют соответствующих палетных входов.
UpdateContainer(Image)
Обновление контейнера.
protected void UpdateContainer(Image container)Parameters
container Image
и контейнера .