Class PngImage
Името на пространството: Aspose.Imaging.FileFormats.Png Асамблея: Aspose.Imaging.dll (25.4.0)
Manipulate Portable Network Graphics (PNG) растер изображения с нашата универсална API,поддържане на нивата на компресия и различните цветови дълбочини, включителноGrayscale, индексиран цвят, TrueColor и алфа канали. безпроблемно обработва XMP метаданни,да позволява цялостно управление на метаданните на изображението, като в същото време лесно зарежда PNG изображения,извършване на различни манипулации, прилагане на филтри и конвертиране на изображения в други файловеформати за оптимална универсалност и персонализация.
[JsonObject(MemberSerialization.OptIn)]
public class PngImage : RasterCachedImage, IDisposable, IObjectWithBounds, IRasterImageArgb32PixelLoader, IRasterImageRawDataLoader, IHasXmpData, IHasMetadata
Inheritance
object ← DisposableObject ← DataStreamSupporter ← Image ← RasterImage ← RasterCachedImage ← PngImage
Implements
IDisposable , IObjectWithBounds , IRasterImageArgb32PixelLoader , IRasterImageRawDataLoader , IHasXmpData , IHasMetadata
наследници
RasterCachedImage.CacheData() , RasterCachedImage.Blend(Point, RasterImage, Rectangle, byte) , RasterCachedImage.Resize(int, int, ResizeType) , RasterCachedImage.Resize(int, int, ImageResizeSettings) , RasterCachedImage.RotateFlip(RotateFlipType) , RasterCachedImage.Rotate(float, bool, Color) , RasterCachedImage.Crop(Rectangle) , RasterCachedImage.Dither(DitheringMethod, int, IColorPalette) , RasterCachedImage.Grayscale() , RasterCachedImage.NormalizeHistogram() , RasterCachedImage.BinarizeFixed(byte) , RasterCachedImage.BinarizeOtsu() , RasterCachedImage.BinarizeBradley(double, int) , RasterCachedImage.BinarizeBradley(double) , RasterCachedImage.AdjustBrightness(int) , RasterCachedImage.AdjustContrast(float) , RasterCachedImage.AdjustGamma(float, float, float) , RasterCachedImage.AdjustGamma(float) , RasterCachedImage.OnCached() , RasterCachedImage.OnPaletteChanged(IColorPalette, IColorPalette) , RasterCachedImage.IsCached , RasterImage.xmpData , RasterImage.RemoveMetadata() , RasterImage.Save(Stream, ImageOptionsBase, Rectangle) , RasterImage.GetModifyDate(bool) , RasterImage.Dither(DitheringMethod, int) , RasterImage.Dither(DitheringMethod, int, IColorPalette) , RasterImage.GetDefaultPixels(Rectangle, IPartialArgb32PixelLoader) , RasterImage.GetDefaultRawData(Rectangle, IPartialRawDataLoader, RawDataSettings) , RasterImage.GetDefaultArgb32Pixels(Rectangle) , RasterImage.GetDefaultRawData(Rectangle, RawDataSettings) , RasterImage.GetArgb32Pixel(int, int) , RasterImage.GetPixel(int, int) , RasterImage.SetArgb32Pixel(int, int, int) , RasterImage.SetPixel(int, int, Color) , RasterImage.ReadScanLine(int) , RasterImage.ReadArgb32ScanLine(int) , RasterImage.WriteScanLine(int, Color[]) , RasterImage.WriteArgb32ScanLine(int, int[]) , RasterImage.LoadPartialArgb32Pixels(Rectangle, IPartialArgb32PixelLoader) , RasterImage.LoadPartialPixels(Rectangle, IPartialPixelLoader) , RasterImage.LoadArgb32Pixels(Rectangle) , RasterImage.LoadArgb64Pixels(Rectangle) , RasterImage.LoadPartialArgb64Pixels(Rectangle, IPartialArgb64PixelLoader) , RasterImage.LoadPixels(Rectangle) , RasterImage.LoadCmykPixels(Rectangle) , RasterImage.LoadCmyk32Pixels(Rectangle) , RasterImage.LoadRawData(Rectangle, RawDataSettings, IPartialRawDataLoader) , RasterImage.LoadRawData(Rectangle, Rectangle, RawDataSettings, IPartialRawDataLoader) , RasterImage.SaveRawData(byte[], int, Rectangle, RawDataSettings) , RasterImage.SaveArgb32Pixels(Rectangle, int[]) , RasterImage.SavePixels(Rectangle, Color[]) , RasterImage.SaveCmykPixels(Rectangle, CmykColor[]) , RasterImage.SaveCmyk32Pixels(Rectangle, int[]) , RasterImage.SetResolution(double, double) , RasterImage.SetPalette(IColorPalette, bool) , RasterImage.Resize(int, int, ImageResizeSettings) , RasterImage.Rotate(float, bool, Color) , RasterImage.Rotate(float) , RasterImage.BinarizeFixed(byte) , RasterImage.BinarizeOtsu() , RasterImage.BinarizeBradley(double) , RasterImage.BinarizeBradley(double, int) , RasterImage.Blend(Point, RasterImage, Rectangle, byte) , RasterImage.Blend(Point, RasterImage, byte) , RasterImage.Grayscale() , RasterImage.NormalizeHistogram() , RasterImage.AdjustBrightness(int) , RasterImage.AdjustContrast(float) , RasterImage.AdjustGamma(float, float, float) , RasterImage.AdjustGamma(float) , RasterImage.GetSkewAngle() , RasterImage.NormalizeAngle() , RasterImage.NormalizeAngle(bool, Color) , RasterImage.Filter(Rectangle, FilterOptionsBase) , RasterImage.ReplaceColor(Color, byte, Color) , RasterImage.ReplaceColor(int, byte, int) , RasterImage.ReplaceNonTransparentColors(Color) , RasterImage.ReplaceNonTransparentColors(int) , RasterImage.ToBitmap() , RasterImage.ReleaseManagedResources() , RasterImage.UpdateMetadata() , RasterImage.UpdateDimensions(int, int) , RasterImage.PremultiplyComponents , RasterImage.UseRawData , RasterImage.UpdateXmpData , RasterImage.XmpData , RasterImage.RawIndexedColorConverter , RasterImage.RawCustomColorConverter , RasterImage.RawFallbackIndex , RasterImage.RawDataSettings , RasterImage.UsePalette , RasterImage.RawDataFormat , RasterImage.RawLineSize , RasterImage.IsRawDataAvailable , RasterImage.HorizontalResolution , RasterImage.VerticalResolution , RasterImage.HasTransparentColor , RasterImage.HasAlpha , RasterImage.TransparentColor , RasterImage.ImageOpacity , RasterImage.DataLoader , Image.CanLoad(string) , Image.CanLoad(string, LoadOptions) , Image.CanLoad(Stream) , Image.CanLoad(Stream, LoadOptions) , Image.Create(ImageOptionsBase, int, int) , Image.Create(Image[]) , Image.Create(MultipageCreateOptions) , Image.Create(string[], bool) , Image.Create(string[]) , Image.Create(Image[], bool) , Image.GetFileFormat(string) , Image.GetFileFormat(Stream) , Image.GetFittingRectangle(Rectangle, int, int) , Image.GetFittingRectangle(Rectangle, int[], int, int) , Image.Load(string, LoadOptions) , Image.Load(string) , Image.Load(Stream, LoadOptions) , Image.Load(Stream) , Image.GetProportionalWidth(int, int, int) , Image.GetProportionalHeight(int, int, int) , Image.RemoveMetadata() , Image.CanSave(ImageOptionsBase) , Image.Resize(int, int) , Image.Resize(int, int, ResizeType) , Image.Resize(int, int, ImageResizeSettings) , Image.GetDefaultOptions(object[]) , Image.GetOriginalOptions() , Image.ResizeWidthProportionally(int) , Image.ResizeHeightProportionally(int) , Image.ResizeWidthProportionally(int, ResizeType) , Image.ResizeHeightProportionally(int, ResizeType) , Image.ResizeWidthProportionally(int, ImageResizeSettings) , Image.ResizeHeightProportionally(int, ImageResizeSettings) , Image.RotateFlip(RotateFlipType) , Image.Rotate(float) , Image.Crop(Rectangle) , Image.Crop(int, int, int, int) , Image.Save() , Image.Save(string) , Image.Save(string, ImageOptionsBase) , Image.Save(string, ImageOptionsBase, Rectangle) , Image.Save(Stream, ImageOptionsBase) , Image.Save(Stream, ImageOptionsBase, Rectangle) , Image.GetSerializedStream(ImageOptionsBase, Rectangle, out int) , Image.SetPalette(IColorPalette, bool) , Image.UpdateContainer(Image) , Image.GetCanNotSaveMessage(ImageOptionsBase) , Image.GetFitRectangle(Rectangle) , Image.GetImage2Export(ImageOptionsBase, Rectangle, IImageExporter) , Image.GetFitRectangle(Rectangle, int[]) , Image.OnPaletteChanged(IColorPalette, IColorPalette) , Image.OnPaletteChanging(IColorPalette, IColorPalette) , Image.ReleaseManagedResources() , Image.BitsPerPixel , Image.Bounds , Image.Container , Image.Height , Image.Palette , Image.UsePalette , Image.Size , Image.Width , Image.InterruptMonitor , Image.BufferSizeHint , Image.AutoAdjustPalette , Image.HasBackgroundColor , Image.FileFormat , Image.BackgroundColor , 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
Този пример показва как да изтеглите PNG изображение от файл.
string dir = "c:\\temp\\";
// Load a PNG image from a file.
using (Aspose.Imaging.FileFormats.Png.PngImage pngImage = new Aspose.Imaging.FileFormats.Png.PngImage(dir + "sample.png"))
{
// Transform the image to grayscale representation
pngImage.Grayscale();
// Save to a file.
pngImage.Save(dir + "sample.grayscale.png");
}
Constructors
PngImage(в, в)
Иницијализирайте нов обект на Aspose.Imaging.FileFormats.Png. PngImage клас, като предоставитеширина и височина параметри. този конструктор улеснява създаването на PNGизображения, като позволява на разработчиците да определят измеренията директно, улеснявайкиефективно управление на данните за изображенията на PNG в рамките на техните приложения.
public PngImage(int width, int height)
Parameters
width
int
и ширината.
height
int
на височината.
Examples
Този пример показва как да създадете PNG изображение на посочения размер, да го попълните с твърд цвят и да я съхранявате в файл.
string dir = "c:\\temp\\";
// Create a PNG image of 100x100 px.
using (Aspose.Imaging.FileFormats.Png.PngImage pngImage = new Aspose.Imaging.FileFormats.Png.PngImage(100, 100))
{
// Do some image processing, e.g. fill the entire image in red.
Aspose.Imaging.Graphics graphics = new Aspose.Imaging.Graphics(pngImage);
Aspose.Imaging.Brushes.SolidBrush brush = new Aspose.Imaging.Brushes.SolidBrush(Aspose.Imaging.Color.Red);
graphics.FillRectangle(brush, pngImage.Bounds);
// Save to a file.
pngImage.Save(dir + "output.png");
}
PngImage(Стрий)
Създава нова инстанция на Aspose.Imaging.FileFormats.Png. PngImage клас с помощта на пътяпараметър за определяне на местоположението на изображението файл за зареждане.позволява на разработчиците удобно да създават PNG изображения, като ги изтеглят от файл,Опростяване на процеса на работа с PNG изображения в техните приложения.
public PngImage(string path)
Parameters
path
string
Пътят за зареждане на изображение.
Examples
Този пример показва как да изтеглите PNG изображение от файл.
string dir = "c:\\temp\\";
// Load a PNG image from a file.
using (Aspose.Imaging.FileFormats.Png.PngImage pngImage = new Aspose.Imaging.FileFormats.Png.PngImage(dir + "sample.png"))
{
// Transform the image to grayscale representation
pngImage.Grayscale();
// Save to a file.
pngImage.Save(dir + "sample.grayscale.png");
}
PngImage(RasterImage)
Създава нова инстанция на Aspose.Imaging.FileFormats.Png. PngImage клас чрез предоставяне на растеризображение като параметър. този конструктор позволява на разработчиците да започнат директноPNG изображението обект, използвайки съществуваща растер изображение, ускоряване на процеса наРабота с PNG изображения в техните приложения.
public PngImage(RasterImage rasterImage)
Parameters
rasterImage
RasterImage
Изображението на Растер.
Examples
Този пример показва как да зареждате изображението PNG от изображение BMP.
string dir = "c:\\temp\\";
// Load a TrueColor PNG image from a BMP image.
// First, create a temporal BMP image that will be a foundation for building a PNG image.
// You can also load BMP image from a file or use an image of any other raster format.
using (Aspose.Imaging.FileFormats.Bmp.BmpImage bmpImage = new Aspose.Imaging.FileFormats.Bmp.BmpImage(100, 100))
{
// Fill the entire BMP image in red.
Aspose.Imaging.Graphics gr = new Aspose.Imaging.Graphics(bmpImage);
Aspose.Imaging.Brushes.SolidBrush brush = new Aspose.Imaging.Brushes.SolidBrush(Aspose.Imaging.Color.Red);
gr.FillRectangle(brush, bmpImage.Bounds);
using (Aspose.Imaging.FileFormats.Png.PngImage pngImage = new Aspose.Imaging.FileFormats.Png.PngImage(bmpImage))
{
System.Console.WriteLine("The PNG color type: {0}", pngImage.GetOriginalOptions());
pngImage.Save(dir + "output.png");
}
}
PngImage(Стъпка, PngColorType)
Иницијализира нова инстанция на Aspose.Imaging.FileFormats.Png. PngImage клас, като посочваПътят към файла на изображението и цветовия тип. Този конструктор позволявасъздаване на PNG изображения от файлове с различни цветови типове, предоставящигъвкавост при обработката на различни формати на изображението.
public PngImage(string path, PngColorType colorType)
Parameters
path
string
Пътят за зареждане на изображение.
colorType
PngColorType
Типът на цвета.
Examples
Този пример показва как да изтеглите PNG изображение от файл с определен тип цвят.
string dir = "c:\\temp\\";
// Load a PNG image from a file.
// Note that the colorful image will be converted to grayscale automatically.
using (Aspose.Imaging.FileFormats.Png.PngImage pngImage = new Aspose.Imaging.FileFormats.Png.PngImage(dir + "sample.png", Aspose.Imaging.FileFormats.Png.PngColorType.Grayscale))
{
// Save to a file.
pngImage.Save(dir + "sample.grayscale.png");
}
Exceptions
PngImage(Снимка, PngColorType)
Създава нова инстанция на Aspose.Imaging.FileFormats.Png. PngImage клас, като посочваизображение и цвят тип. този конструктор позволява на разработчиците директно даКонвертирайте изображенията на растер в PNG формат, като посочете желания тип цвят.Предлагат гъвкавост в цветовото представяне.
public PngImage(RasterImage rasterImage, PngColorType colorType)
Parameters
rasterImage
RasterImage
Изображението на Растер.
colorType
PngColorType
Типът на цвета.
Examples
Този пример показва как да зареждате изображението PNG от изображение BMP с посочения тип цвят.
string dir = "c:\\temp\\";
// Load a grayscale PNG image from a colored BMP image.
// First, create a temporal BMP image that will be a foundation for building a PNG image.
// You can also load BMP image from a file or use an image of any other raster format.
using (Aspose.Imaging.FileFormats.Bmp.BmpImage bmpImage = new Aspose.Imaging.FileFormats.Bmp.BmpImage(100, 100))
{
// Fill the entire BMP image in red.
Aspose.Imaging.Graphics gr = new Aspose.Imaging.Graphics(bmpImage);
Aspose.Imaging.Brushes.SolidBrush brush = new Aspose.Imaging.Brushes.SolidBrush(Aspose.Imaging.Color.Red);
gr.FillRectangle(brush, bmpImage.Bounds);
// The colors of the image pixels will be converted to their grayscale counterparts.
using (Aspose.Imaging.FileFormats.Png.PngImage pngImage = new Aspose.Imaging.FileFormats.Png.PngImage(bmpImage, Aspose.Imaging.FileFormats.Png.PngColorType.Grayscale))
{
pngImage.Save(dir + "output.grayscale.png");
}
}
PngImage(Stream)
Създава нова инстанция на Aspose.Imaging.FileFormats.Png. PngImage клас, като го стартираТози конструктор позволява на разработчиците да зареждат PNG изображения директноот един поток, осигуряване на гъвкавост в изображението възвръщаемост от различни източници.
public PngImage(Stream stream)
Parameters
stream
Stream
Потокът за зареждане на изображение.
Examples
Този пример показва как да изтеглите PNG изображение от файл или файл поток.
string dir = "c:\\temp\\";
// Load a PNG image from a file stream.
using (System.IO.Stream stream = System.IO.File.OpenRead(dir + "sample.png"))
{
using (Aspose.Imaging.FileFormats.Png.PngImage pngImage = new Aspose.Imaging.FileFormats.Png.PngImage(stream))
{
// Transform the image to grayscale representation
pngImage.Grayscale();
// Save to a file.
pngImage.Save(dir + "sample.grayscale.png");
}
}
PngImage(Инт, инт и PngColorType)
Инсталирайте нова инстанция на класата Aspose.Imaging.FileFormats.Png. PngImage, като посочитежеланата ширина, височина и цветен тип параметри. този конструктор позволявабързо създаване на PNG изображения с персонализирани размери и цветови конфигурации,Улесняване на ускореното генериране на изображения за различни приложения и работни потоци.
public PngImage(int width, int height, PngColorType colorType)
Parameters
width
int
и ширината.
height
int
на височината.
colorType
PngColorType
Типът на цвета.
Examples
Този пример показва как да се създаде PNG изображение на посочения размер с конкретния цвят тип, да го попълни със солиден цвят и да я съхранява в файл.
string dir = "c:\\temp\\";
// Create a grayscale PNG image of 100x100 px.
// All colors will be automatically converted to the grayscale format.
using (Aspose.Imaging.FileFormats.Png.PngImage pngImage = new Aspose.Imaging.FileFormats.Png.PngImage(100, 100, Aspose.Imaging.FileFormats.Png.PngColorType.Grayscale))
{
// Do some image processing, e.g. fill the entire image in red.
Aspose.Imaging.Graphics graphics = new Aspose.Imaging.Graphics(pngImage);
Aspose.Imaging.Brushes.SolidBrush brush = new Aspose.Imaging.Brushes.SolidBrush(Aspose.Imaging.Color.Red);
graphics.FillRectangle(brush, pngImage.Bounds);
// Save to a file.
pngImage.Save(dir + "output.grayscale.png");
}
PngImage(Пинг опции, int и int)
Иницијализирайте нова инстанция на класата Aspose.Imaging.FileFormats.Png. PngImage, която включваОпции PNG заедно с ширината и височината на параметрите. този конструктор улесняваразработчиците да създават PNG изображения с персонализирани настройки и измерения,Осигуряване на гъвкавост в генерирането на изображения за различни случаи на употреба.
public PngImage(PngOptions pngOptions, int width, int height)
Parameters
pngOptions
PngOptions
Опции за PNG.
width
int
и ширината.
height
int
на височината.
Examples
Този пример показва как да се създаде PNG изображение с посочените опции, да го попълни с линейни градиентни цветове и да я съхранява в файл.
string dir = "c:\\temp\\";
Aspose.Imaging.ImageOptions.PngOptions createOptions = new Aspose.Imaging.ImageOptions.PngOptions();
// The number of bits per color channel
createOptions.BitDepth = 8;
// Each pixel is a (red, green, blue) triple followed by the alpha component.
createOptions.ColorType = Imaging.FileFormats.Png.PngColorType.TruecolorWithAlpha;
// The maximum level of compression.
createOptions.CompressionLevel = 9;
// Usage of filters allows to compress continuous tonal images more effectively.
createOptions.FilterType = Aspose.Imaging.FileFormats.Png.PngFilterType.Sub;
// Use progressive loading
createOptions.Progressive = true;
// Create a PNG image with custom parameters.
using (Aspose.Imaging.FileFormats.Png.PngImage pngImage = new Aspose.Imaging.FileFormats.Png.PngImage(createOptions, 100, 100))
{
Aspose.Imaging.Brushes.LinearGradientBrush gradientBrush = new Aspose.Imaging.Brushes.LinearGradientBrush(
new Aspose.Imaging.Point(0, 0),
new Aspose.Imaging.Point(pngImage.Width, pngImage.Height),
Aspose.Imaging.Color.Blue,
Aspose.Imaging.Color.Transparent);
Aspose.Imaging.Graphics graphics = new Aspose.Imaging.Graphics(pngImage);
// Fill the image with a semi-transparent gradient.
graphics.FillRectangle(gradientBrush, pngImage.Bounds);
// Save to a file.
pngImage.Save(dir + "output.explicitoptions.png");
}
Properties
BackgroundColor
Възпроизвежда цвета на фона на изображението, ако е посочено едно.е полезен за приложения, които трябва да идентифицират и потенциално манипулиратЦветът на фона на изображението.
public override Color BackgroundColor { get; set; }
стойност на имота
Examples
Следващият пример показва как да зададете напълно прозрачни цветове за част от изображението TrueColor PNG, което не поддържа алфа канал.
Aspose.Imaging.ImageOptions.PngOptions createOptions = new Aspose.Imaging.ImageOptions.PngOptions();
createOptions.Source = new Aspose.Imaging.Sources.FileCreateSource("c:\\temp\\transparent.png", false);
createOptions.ColorType = Aspose.Imaging.FileFormats.Png.PngColorType.Truecolor;
// Create a TrueColor PNG image of 100x100 px.
using (Aspose.Imaging.Image image = Image.Create(createOptions, 100, 100))
{
Aspose.Imaging.FileFormats.Png.PngImage pngImage = (Aspose.Imaging.FileFormats.Png.PngImage)image;
Aspose.Imaging.Graphics gr = new Aspose.Imaging.Graphics(pngImage);
// All red pixels will be considered as fully transparent.
pngImage.TransparentColor = Aspose.Imaging.Color.Red;
pngImage.HasTransparentColor = true;
// All transparent pixels will have a background color.
pngImage.BackgroundColor = Aspose.Imaging.Color.Green;
pngImage.HasBackgroundColor = true;
// Fill the entire image with white color.
gr.FillRectangle(new Aspose.Imaging.Brushes.SolidBrush(Aspose.Imaging.Color.White), pngImage.Bounds);
// Fill the top-left quarter of the image with the transparent color.
// This makes the top-left quarter colored in the background color.
Rectangle rect = new Rectangle(0, 0, pngImage.Width / 2, pngImage.Height / 2);
gr.FillRectangle(new Aspose.Imaging.Brushes.SolidBrush(Aspose.Imaging.Color.Red), rect);
pngImage.Save();
}
BitsPerPixel
Възстановяване на стойността на битите на пиксел за изображението. това свойство дава решаващо значениеинформация относно цветната дълбочина на изображението, което позволява на разработчиците даРазбиране на нивото на детайл и точност на цветовете, присъстващи в данните на изображението.
public override int BitsPerPixel { get; }
стойност на имота
FileFormat
Изтегля форматът на файла, свързан с изображението.собствеността предоставя съществена информация относно типа на файла, позволяващаЕфективно обработване и обработка въз основа на специфичните изисквания за формат.
public override FileFormat FileFormat { get; }
стойност на имота
HasAlpha
Възстановява булеанна стойност, която показва дали изображението има алфа канал,който определя неговата прозрачност. тази собственост е полезна за приложениятатрябва да се справят с прозрачността, позволявайки на разработчиците да определят далиДопълнителна обработка е необходима, за да се справят с прозрачни области на изображението.
public override bool HasAlpha { get; }
стойност на имота
Examples
Следващият пример показва как да се провери дали изображението PNG поддържа алфа канал.
// Get all supported PNG color types.
System.Array colorTypes = System.Enum.GetValues(typeof(Aspose.Imaging.FileFormats.Png.PngColorType));
foreach (Aspose.Imaging.FileFormats.Png.PngColorType colorType in colorTypes)
{
Aspose.Imaging.ImageOptions.PngOptions createOptions = new Aspose.Imaging.ImageOptions.PngOptions();
createOptions.Source = new Sources.StreamSource(new System.IO.MemoryStream());
createOptions.ColorType = colorType;
using (Aspose.Imaging.Image image = Image.Create(createOptions, 100, 100))
{
Aspose.Imaging.FileFormats.Png.PngImage pngImage = (Aspose.Imaging.FileFormats.Png.PngImage)image;
if (pngImage.HasAlpha)
{
System.Console.WriteLine("A {0} PNG image supports alpha channel", createOptions.ColorType);
}
else
{
System.Console.WriteLine("A {0} PNG image doesn't support alpha channel", createOptions.ColorType);
}
}
}
// The output looks like this:
// A Grayscale PNG image doesn't support alpha channel
// A Truecolor PNG image doesn't support alpha channel
// A IndexedColor PNG image doesn't support alpha channel
// A GrayscaleWithAlpha PNG image supports alpha channel
// A TruecolorWithAlpha PNG image supports alpha channel
HasBackgroundColor
Ретровира булеанна стойност, която показва дали изображението има цвят на фона.Тази собственост е полезна за приложения, които трябва да определят дали изображениетосъдържа цвят на фона, който може да бъде важен за различни обработкизадачи като композиране, изнасяне или експортиране.
public override bool HasBackgroundColor { get; set; }
стойност на имота
Examples
Следващият пример показва как да зададете напълно прозрачни цветове за част от изображението TrueColor PNG, което не поддържа алфа канал.
Aspose.Imaging.ImageOptions.PngOptions createOptions = new Aspose.Imaging.ImageOptions.PngOptions();
createOptions.Source = new Aspose.Imaging.Sources.FileCreateSource("c:\\temp\\transparent.png", false);
createOptions.ColorType = Aspose.Imaging.FileFormats.Png.PngColorType.Truecolor;
// Create a TrueColor PNG image of 100x100 px.
using (Aspose.Imaging.Image image = Image.Create(createOptions, 100, 100))
{
Aspose.Imaging.FileFormats.Png.PngImage pngImage = (Aspose.Imaging.FileFormats.Png.PngImage)image;
Aspose.Imaging.Graphics gr = new Aspose.Imaging.Graphics(pngImage);
// All red pixels will be considered as fully transparent.
pngImage.TransparentColor = Aspose.Imaging.Color.Red;
pngImage.HasTransparentColor = true;
// All transparent pixels will have a background color.
pngImage.BackgroundColor = Aspose.Imaging.Color.Green;
pngImage.HasBackgroundColor = true;
// Fill the entire image with white color.
gr.FillRectangle(new Aspose.Imaging.Brushes.SolidBrush(Aspose.Imaging.Color.White), pngImage.Bounds);
// Fill the top-left quarter of the image with the transparent color.
// This makes the top-left quarter colored in the background color.
Rectangle rect = new Rectangle(0, 0, pngImage.Width / 2, pngImage.Height / 2);
gr.FillRectangle(new Aspose.Imaging.Brushes.SolidBrush(Aspose.Imaging.Color.Red), rect);
pngImage.Save();
}
HasTransparentColor
Осигурява булеанна стойност, която показва дали изображението съдържа прозраченЦветът. тази собственост е от решаващо значение за приложенията, които трябва да се справятпрозрачност, позволяваща на разработчиците да определят дали допълнителната обработка еНеобходимо е да се справят с прозрачни региони на изображението.
public override bool HasTransparentColor { get; set; }
стойност на имота
Examples
Следващият пример показва как да зададете напълно прозрачни цветове за част от изображението TrueColor PNG, което не поддържа алфа канал.
Aspose.Imaging.ImageOptions.PngOptions createOptions = new Aspose.Imaging.ImageOptions.PngOptions();
createOptions.Source = new Aspose.Imaging.Sources.FileCreateSource("c:\\temp\\transparent.png", false);
createOptions.ColorType = Aspose.Imaging.FileFormats.Png.PngColorType.Truecolor;
// Create a TrueColor PNG image of 100x100 px.
using (Aspose.Imaging.Image image = Image.Create(createOptions, 100, 100))
{
Aspose.Imaging.FileFormats.Png.PngImage pngImage = (Aspose.Imaging.FileFormats.Png.PngImage)image;
Aspose.Imaging.Graphics gr = new Aspose.Imaging.Graphics(pngImage);
// All red pixels will be considered as fully transparent.
pngImage.TransparentColor = Aspose.Imaging.Color.Red;
pngImage.HasTransparentColor = true;
// All transparent pixels will have a background color.
pngImage.BackgroundColor = Aspose.Imaging.Color.Green;
pngImage.HasBackgroundColor = true;
// Fill the entire image with white color.
gr.FillRectangle(new Aspose.Imaging.Brushes.SolidBrush(Aspose.Imaging.Color.White), pngImage.Bounds);
// Fill the top-left quarter of the image with the transparent color.
// This makes the top-left quarter colored in the background color.
Rectangle rect = new Rectangle(0, 0, pngImage.Width / 2, pngImage.Height / 2);
gr.FillRectangle(new Aspose.Imaging.Brushes.SolidBrush(Aspose.Imaging.Color.Red), rect);
pngImage.Save();
}
Height
Получете височината на изображението. тази собственост връща вертикалното измерение наизображението, което позволява на разработчиците да определят размера му в пиксели по време наВертикална ос.
public override int Height { get; }
стойност на имота
HorizontalResolution
Възстановяване или промяна на хоризонталната резолюция на изображението.представлява броя на пикселите на инча по хоризонталната ос наАдаптирането на тази резолюция може да повлияе на физическия размер на изображението, когатоОтпечатан или показан.
public override double HorizontalResolution { get; set; }
стойност на имота
Examples
Следващият пример показва как да се зададе хоризонтална/вертикална резолюция на изображение PNG.
string dir = "c:\\temp\\";
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.FileFormats.Png.PngImage pngImage = (Aspose.Imaging.FileFormats.Png.PngImage)image;
// Get horizontal and vertical resolution of the PngImage.
double horizontalResolution = pngImage.HorizontalResolution;
double verticalResolution = pngImage.VerticalResolution;
System.Console.WriteLine("The horizontal resolution, in pixels per inch: {0}", horizontalResolution);
System.Console.WriteLine("The vertical resolution, in pixels per inch: {0}", verticalResolution);
if (horizontalResolution != 96.0 || verticalResolution != 96.0)
{
// Use the SetResolution method for updating both resolution values in a single call.
System.Console.WriteLine("Set resolution values to 96 dpi");
pngImage.SetResolution(96.0, 96.0);
System.Console.WriteLine("The horizontal resolution, in pixels per inch: {0}", pngImage.HorizontalResolution);
System.Console.WriteLine("The vertical resolution, in pixels per inch: {0}", pngImage.VerticalResolution);
}
}
Interlaced
Възстановява стойност на булея, която показва дали Aspose.Imaging.FileFormats.Png. PngImage еинтерлайд, който определя дали данните на изображението се съхраняват в прогресивнаНачин за по-бързо зареждане или предаване.
public bool Interlaced { get; }
стойност на имота
IsInterlaced
Възстановява булеанна стойност, която показва дали изображението е свързано.Имотът е от решаващо значение за оптимизиране на стратегиите за зареждане и осигуряване на ефективностизпълнение по време на обработка на изображения или задачи за показване.
public bool IsInterlaced { get; }
стойност на имота
RawDataFormat
Достъп до формата на сурови данни на изображението.Това свойство дава вписване вКак се структурират данните на изображението вътрешно, което може да бъде полезно за напредналиОбработка на изображенията или конвертиране на формати.
public override PixelDataFormat RawDataFormat { get; }
стойност на имота
Examples
Следващият пример зарежда PNG изображения и отпечатва информация за формат на сурови данни и алфа канал.
// The PNG images to load.
string[] fileNames = new string[]
{
@"c:\temp\sample.png",
@"c:\temp\alpha.png",
};
foreach (string fileName in fileNames)
{
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(fileName))
{
Aspose.Imaging.FileFormats.Png.PngImage pngImage = (Aspose.Imaging.FileFormats.Png.PngImage)image;
System.Console.WriteLine("ImageFile={0}, FileFormat={1}, HasAlpha={2}", fileName, pngImage.RawDataFormat, pngImage.HasAlpha);
}
}
// The output may look like this:
// ImageFile=c:\temp\sample.png, FileFormat=Rgb24Bpp, used channels: 8,8,8, HasAlpha=False
// ImageFile=c:\temp\alpha.png, FileFormat=RGBA32Bpp, used channels: 8,8,8,8, HasAlpha=True
TransparentColor
Превръща прозрачния цвят на изображението, ако съществува.ценни за приложения, които изискват прецизно управление на прозрачни областив рамките на изображенията, което позволява на разработчиците да имат достъп и да манипулиратИзползва се прозрачен цвят.
public override Color TransparentColor { get; set; }
стойност на имота
Examples
Следващият пример показва как да зададете напълно прозрачни цветове за част от изображението TrueColor PNG, което не поддържа алфа канал.
Aspose.Imaging.ImageOptions.PngOptions createOptions = new Aspose.Imaging.ImageOptions.PngOptions();
createOptions.Source = new Aspose.Imaging.Sources.FileCreateSource("c:\\temp\\transparent.png", false);
createOptions.ColorType = Aspose.Imaging.FileFormats.Png.PngColorType.Truecolor;
// Create a TrueColor PNG image of 100x100 px.
using (Aspose.Imaging.Image image = Image.Create(createOptions, 100, 100))
{
Aspose.Imaging.FileFormats.Png.PngImage pngImage = (Aspose.Imaging.FileFormats.Png.PngImage)image;
Aspose.Imaging.Graphics gr = new Aspose.Imaging.Graphics(pngImage);
// All red pixels will be considered as fully transparent.
pngImage.TransparentColor = Aspose.Imaging.Color.Red;
pngImage.HasTransparentColor = true;
// All transparent pixels will have a background color.
pngImage.BackgroundColor = Aspose.Imaging.Color.Green;
pngImage.HasBackgroundColor = true;
// Fill the entire image with white color.
gr.FillRectangle(new Aspose.Imaging.Brushes.SolidBrush(Aspose.Imaging.Color.White), pngImage.Bounds);
// Fill the top-left quarter of the image with the transparent color.
// This makes the top-left quarter colored in the background color.
Rectangle rect = new Rectangle(0, 0, pngImage.Width / 2, pngImage.Height / 2);
gr.FillRectangle(new Aspose.Imaging.Brushes.SolidBrush(Aspose.Imaging.Color.Red), rect);
pngImage.Save();
}
VerticalResolution
предоставя достъп до вертикалната резолюция на изображението. разработчиците могат да използваттова имущество за възстановяване или изменение на настройката за разрешаване, което показва, чеБрой пиксели на инч (PPI) по вертикалната ос на изображението.
public override double VerticalResolution { get; set; }
стойност на имота
Examples
Следващият пример показва как да се зададе хоризонтална/вертикална резолюция на изображение PNG.
string dir = "c:\\temp\\";
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.FileFormats.Png.PngImage pngImage = (Aspose.Imaging.FileFormats.Png.PngImage)image;
// Get horizontal and vertical resolution of the PngImage.
double horizontalResolution = pngImage.HorizontalResolution;
double verticalResolution = pngImage.VerticalResolution;
System.Console.WriteLine("The horizontal resolution, in pixels per inch: {0}", horizontalResolution);
System.Console.WriteLine("The vertical resolution, in pixels per inch: {0}", verticalResolution);
if (horizontalResolution != 96.0 || verticalResolution != 96.0)
{
// Use the SetResolution method for updating both resolution values in a single call.
System.Console.WriteLine("Set resolution values to 96 dpi");
pngImage.SetResolution(96.0, 96.0);
System.Console.WriteLine("The horizontal resolution, in pixels per inch: {0}", pngImage.HorizontalResolution);
System.Console.WriteLine("The vertical resolution, in pixels per inch: {0}", pngImage.VerticalResolution);
}
}
Width
Осигурява възвръщаемост на ширината на изображението, предоставяща съществена информацияТази собственост често се използва от разработчиците заопределя ширината на изображението, което им позволява да извършват различни операции въз основа нана размера си
public override int Width { get; }
стойност на имота
XmpData
Достъп или модификация на метаданните, свързани с платформата за разширени метадани (XMP)Тази собственост улеснява извличането, модификацията илиДобавяне на метаданни, което позволява цялостно управление на информацията, свързана с изображението.
public override XmpPacketWrapper XmpData { get; set; }
стойност на имота
Methods
GetDefaultOptions(Обект[])
Получават се дефолтните опции.
public override ImageOptionsBase GetDefaultOptions(object[] args)
Parameters
args
object
[]
и аргументите.
Returns
Дефинирани опции
GetModifyDate(Боул)
Изтегля времевата лента, показваща най-новата модификация на ресурсаТози метод осигурява достъп до жизненоважни метаданни, което позволява на приложенията дапроверяват кога изображението е последно променено, улеснявайки проследяването на версията иУправление на съдържанието.
public override DateTime GetModifyDate(bool useDefault)
Parameters
useDefault
bool
ако сте зададени на “истински”, използвайте информацията от FileInfo като стандартна стойност.
Returns
Датата и времето на изображението на ресурса е последната промяна.
GetOriginalOptions()
Получава опциите въз основа на първоначалните настройки на файла.Това може да бъде полезно, за да се запази битовата дълбочина и други параметри на оригиналната картина непроменени.Например, ако зареждаме черно-бяло PNG изображение с 1 бит на пиксел и след това го съхраняваме с помощта наAspose.Imaging.DataStreamSupporter.Save(System.String) метод, изходната PNG изображение с 8 бита на пиксел ще бъде произведена.За да избегнете това и да спестите PNG изображение с 1-бит на пиксел, използвайте този метод, за да получите съответните възможности за спестяване и ги прехвърлитена метода Aspose.Imaging.Image.Save(System.String,_Wl17.ImageOptionsBase) като втори параметър.
public override ImageOptionsBase GetOriginalOptions()
Returns
Опциите се основават на първоначалните настройки на файла.
OnPaletteChanged(Изолация, IColorPalette)
Позива се, когато палетът се променя.
protected override void OnPaletteChanged(IColorPalette oldPalette, IColorPalette newPalette)
Parameters
oldPalette
IColorPalette
Старата палитра.
newPalette
IColorPalette
Новата палитра.
SaveData(Stream)
Съхранение на данни.
protected override void SaveData(Stream stream)
Parameters
stream
Stream
на потока .
UpdateDimensions(в, в)
Актуализиране на измеренията.
protected override void UpdateDimensions(int newWidth, int newHeight)
Parameters
newWidth
int
Новата ширина.
newHeight
int
Новата височина.
UpdateMetadata()
Датата и времето на последната модификация на изображението.
protected override void UpdateMetadata()