Class RasterImage
Nome do espaço: Aspose.Imaging Assembleia: Aspose.Imaging.dll (25.4.0)
Representa uma imagem raster que suporta operações gráficas raster.
public abstract class RasterImage : Image, IDisposable, IObjectWithBounds, IRasterImageArgb32PixelLoader, IRasterImageRawDataLoader, IHasXmpData, IHasMetadata
Inheritance
object ← DisposableObject ← DataStreamSupporter ← Image ← RasterImage
Derived
Implements
IDisposable , IObjectWithBounds , IRasterImageArgb32PixelLoader , IRasterImageRawDataLoader , IHasXmpData , IHasMetadata
Membros herdados
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
Este exemplo mostra como carregar informações do Pixel em um Array de Tipo de Cor, manipula o array e a coloca de volta à imagem. Para executar essas operações, este exemplo cria um novo arquivo de imagem (em formato GIF) uisng Objeto MemoryStream.
//Create an instance of MemoryStream
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
//Create an instance of GifOptions and set its various properties including the Source property
Aspose.Imaging.ImageOptions.GifOptions gifOptions = new Aspose.Imaging.ImageOptions.GifOptions();
gifOptions.Source = new Aspose.Imaging.Sources.StreamSource(stream);
//Create an instance of Image
using (Aspose.Imaging.RasterImage image = (Aspose.Imaging.RasterImage)Aspose.Imaging.Image.Create(gifOptions, 500, 500))
{
//Get the pixels of image by specifying the area as image boundary
Aspose.Imaging.Color[] pixels = image.LoadPixels(image.Bounds);
//Loop over the Array and sets color of alrenative indexed pixel
for (int index = 0; index < pixels.Length; index++)
{
if (index % 2 == 0)
{
//Set the indexed pixel color to yellow
pixels[index] = Aspose.Imaging.Color.Yellow;
}
else
{
//Set the indexed pixel color to blue
pixels[index] = Aspose.Imaging.Color.Blue;
}
}
//Apply the pixel changes to the image
image.SavePixels(image.Bounds, pixels);
// save all changes.
image.Save();
}
// Write MemoryStream to File
using (System.IO.FileStream fileStream = new System.IO.FileStream(@"C:\temp\output.gif", System.IO.FileMode.Create))
{
stream.WriteTo(fileStream);
}
}
Constructors
RasterImage()
Inicia uma nova instância da classe Aspose.Imaging.RasterImage.
[JsonConstructor]
protected RasterImage()
RasterImage(Iluminação)
Inicia uma nova instância da classe Aspose.Imaging.RasterImage.
protected RasterImage(IColorPalette colorPalette)
Parameters
colorPalette
IColorPalette
A paleta de cores.
Fields
xmpData
Os metadados do XMP
[JsonProperty]
protected XmpPacketWrapper xmpData
Valor de campo
Properties
DataLoader
Receba ou coloca o carregador de dados.
[JsonProperty]
protected IRasterImageArgb32PixelLoader DataLoader { get; set; }
Valor da propriedade
HasAlpha
Obtenha um valor indicando se esta instância tem alfa.
public virtual bool HasAlpha { get; }
Valor da propriedade
Examples
O exemplo a seguir carrega imagens de raster e imprime informações sobre o formato de dados crus e o canal alfa.
// The image files to load.
string[] fileNames = new string[]
{
@"c:\temp\sample.bmp",
@"c:\temp\alpha.png",
};
foreach (string fileName in fileNames)
{
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(fileName))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
System.Console.WriteLine("ImageFile={0}, FileFormat={1}, HasAlpha={2}", fileName, rasterImage.RawDataFormat, rasterImage.HasAlpha);
}
}
// The output may look like this:
// ImageFile=c:\temp\sample.bmp, FileFormat=Rgb24Bpp, used channels: 8,8,8, HasAlpha=False
// ImageFile=c:\temp\alpha.png, FileFormat=RGBA32Bpp, used channels: 8,8,8,8, HasAlpha=True
O exemplo a seguir mostra como extrair informações sobre o formato de dados crus e canal alfa de uma imagem BMP.
// Create a 32-bpp BMP image of 100 x 100 px.
using (Aspose.Imaging.FileFormats.Bmp.BmpImage bmpImage = new Aspose.Imaging.FileFormats.Bmp.BmpImage(100, 100, 32, null))
{
System.Console.WriteLine("FileFormat={0}, RawDataFormat={1}, HasAlpha={2}", bmpImage.FileFormat, bmpImage.RawDataFormat, bmpImage.HasAlpha);
};
// Create a 24-bpp BMP image of 100 x 100 px.
using (Aspose.Imaging.FileFormats.Bmp.BmpImage bmpImage = new Aspose.Imaging.FileFormats.Bmp.BmpImage(100, 100, 24, null))
{
System.Console.WriteLine("FileFormat={0}, RawDataFormat={1}, HasAlpha={2}", bmpImage.FileFormat, bmpImage.RawDataFormat, bmpImage.HasAlpha);
};
// Generally, BMP doesn't support alpha channel so the output will look like this:
// FileFormat = Bmp, RawDataFormat = Rgb32Bpp, used channels: 8,8,8,8, HasAlpha = False
// FileFormat = Bmp, RawDataFormat = Rgb24Bpp, used channels: 8,8,8, HasAlpha = False
HasTransparentColor
Recebe um valor indicando se a imagem tem uma cor transparente.
public virtual bool HasTransparentColor { get; set; }
Valor da propriedade
HorizontalResolution
Obter ou definir a resolução horizontal, em pixels por polegada, deste Aspose.Imaging.RasterImage.
public virtual double HorizontalResolution { get; set; }
Valor da propriedade
Examples
O exemplo a seguir mostra como definir a resolução horizontal/vertical de uma imagem de raster.
string dir = "c:\\temp\\";
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.jpg"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Get horizontal and vertical resolution of the image
double horizontalResolution = rasterImage.HorizontalResolution;
double verticalResolution = rasterImage.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");
rasterImage.SetResolution(96.0, 96.0);
System.Console.WriteLine("The horizontal resolution, in pixels per inch: {0}", rasterImage.HorizontalResolution);
System.Console.WriteLine("The vertical resolution, in pixels per inch: {0}", rasterImage.VerticalResolution);
}
// The output may look like this:
// The horizontal resolution, in pixels per inch: 300
// The vertical resolution, in pixels per inch: 300
// Set resolution values to 96 dpi
// The horizontal resolution, in pixels per inch: 96
// The vertical resolution, in pixels per inch: 96
}
Remarks
Nota por padrão este valor é sempre 96 porque diferentes plataformas não podem devolver a resolução da tela. Você pode considerar usar o método SetResolution para atualizar ambos os valores de resolução em uma única chamada.
ImageOpacity
Obtenha opacidade desta imagem.
public virtual float ImageOpacity { get; }
Valor da propriedade
IsRawDataAvailable
Recebe um valor indicando se o carregamento de dados crus está disponível.
public bool IsRawDataAvailable { get; }
Valor da propriedade
PremultiplyComponents
Recebe ou coloca um valor indicando se os componentes da imagem devem ser pre-multipliados.
public virtual bool PremultiplyComponents { get; set; }
Valor da propriedade
Examples
O exemplo a seguir cria uma nova imagem de raster, salva os pixels semi-transparentes especificados, depois carrega esses pixels e obtém cores finais na forma pre-multipliada.
int imageWidth = 3;
int imageHeight = 2;
Aspose.Imaging.Color[] colors = new Aspose.Imaging.Color[]
{
Aspose.Imaging.Color.FromArgb(127, 255, 0, 0),
Aspose.Imaging.Color.FromArgb(127, 0, 255, 0),
Aspose.Imaging.Color.FromArgb(127, 0, 0, 255),
Aspose.Imaging.Color.FromArgb(127, 255, 255, 0),
Aspose.Imaging.Color.FromArgb(127, 255, 0, 255),
Aspose.Imaging.Color.FromArgb(127, 0, 255, 255),
};
Aspose.Imaging.ImageOptions.PngOptions createOptions = new Aspose.Imaging.ImageOptions.PngOptions();
createOptions.Source = new Aspose.Imaging.Sources.StreamSource(new System.IO.MemoryStream(), true);
createOptions.ColorType = Aspose.Imaging.FileFormats.Png.PngColorType.TruecolorWithAlpha;
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Create(createOptions, imageWidth, imageHeight))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Save pixels for the whole image.
rasterImage.SavePixels(rasterImage.Bounds, colors);
// The pixels are stored in the original image in the non-premultiplied form.
// Need to specify the corresponding option explicitly to obtain premultiplied color components.
// The premultiplied color components are calculated by the formulas:
// red = original_red * alpha / 255;
// green = original_green * alpha / 255;
// blue = original_blue * alpha / 255;
rasterImage.PremultiplyComponents = true;
Aspose.Imaging.Color[] premultipliedColors = rasterImage.LoadPixels(rasterImage.Bounds);
for (int i = 0; i < colors.Length; i++)
{
System.Console.WriteLine("Original color: {0}", colors[i].ToString());
System.Console.WriteLine("Premultiplied color: {0}", premultipliedColors[i].ToString());
}
}
RawCustomColorConverter
Obter ou configurar o conversor de cor personalizado
public IColorConverter RawCustomColorConverter { get; set; }
Valor da propriedade
RawDataFormat
Obtenha o formato de dados crus.
public virtual PixelDataFormat RawDataFormat { get; }
Valor da propriedade
Examples
O exemplo a seguir carrega imagens de raster e imprime informações sobre o formato de dados crus e o canal alfa.
// The image files to load.
string[] fileNames = new string[]
{
@"c:\temp\sample.bmp",
@"c:\temp\alpha.png",
};
foreach (string fileName in fileNames)
{
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(fileName))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
System.Console.WriteLine("ImageFile={0}, FileFormat={1}, HasAlpha={2}", fileName, rasterImage.RawDataFormat, rasterImage.HasAlpha);
}
}
// The output may look like this:
// ImageFile=c:\temp\sample.bmp, FileFormat=Rgb24Bpp, used channels: 8,8,8, HasAlpha=False
// ImageFile=c:\temp\alpha.png, FileFormat=RGBA32Bpp, used channels: 8,8,8,8, HasAlpha=True
Este exemplo mostra como carregar uma imagem DJVU de um fluxo de arquivo e imprimir informações sobre as páginas.
string dir = "c:\\temp\\";
// Load a DJVU image from a file stream.
using (System.IO.Stream stream = System.IO.File.OpenRead(dir + "sample.djvu"))
{
using (Aspose.Imaging.FileFormats.Djvu.DjvuImage djvuImage = new Aspose.Imaging.FileFormats.Djvu.DjvuImage(stream))
{
System.Console.WriteLine("The total number of pages: {0}", djvuImage.Pages.Length);
System.Console.WriteLine("The active page number: {0}", djvuImage.ActivePage.PageNumber);
System.Console.WriteLine("The first page number: {0}", djvuImage.FirstPage.PageNumber);
System.Console.WriteLine("The last page number: {0}", djvuImage.LastPage.PageNumber);
foreach (Aspose.Imaging.FileFormats.Djvu.DjvuPage djvuPage in djvuImage.Pages)
{
System.Console.WriteLine("--------------------------------------------------");
System.Console.WriteLine("Page number: {0}", djvuPage.PageNumber);
System.Console.WriteLine("Page size: {0}", djvuPage.Size);
System.Console.WriteLine("Page raw format: {0}", djvuPage.RawDataFormat);
}
}
}
//The output may look like this:
//The total number of pages: 2
//The active page number: 1
//The first page number: 1
//The last page number: 2
//--------------------------------------------------
//Page number: 1
//Page size: { Width = 2481, Height = 3508}
//Page raw format: RgbIndexed1Bpp, used channels: 1
//--------------------------------------------------
//Page number: 2
//Page size: { Width = 2481, Height = 3508}
//Page raw format: RgbIndexed1Bpp, used channels: 1
RawDataSettings
Observe quando você usa essas configurações, os dados carregam sem conversão.
[JsonIgnore]
public RawDataSettings RawDataSettings { get; }
Valor da propriedade
RawFallbackIndex
Obter ou definir o índice de queda para usar quando o índice de paleta está fora dos limites
public int RawFallbackIndex { get; set; }
Valor da propriedade
RawIndexedColorConverter
Obter ou definir o conversor de cor indexado
public IIndexedColorConverter RawIndexedColorConverter { get; set; }
Valor da propriedade
RawLineSize
Obtenha o tamanho da linha raiz em bytes.
public virtual int RawLineSize { get; }
Valor da propriedade
TransparentColor
Obtenha a imagem de cor transparente.
public virtual Color TransparentColor { get; set; }
Valor da propriedade
UpdateXmpData
Obter ou definir um valor indicando se atualizar os metadados XMP.
public virtual bool UpdateXmpData { get; set; }
Valor da propriedade
UsePalette
Recebe um valor indicando se a paleta de imagem é usada.
public override bool UsePalette { get; }
Valor da propriedade
UseRawData
Recebe ou coloca um valor indicando se utilizar o carregamento de dados crus quando o carregamento de dados crus está disponível.
public virtual bool UseRawData { get; set; }
Valor da propriedade
VerticalResolution
Obter ou definir a resolução vertical, em pixels por polegada, deste Aspose.Imaging.RasterImage.
public virtual double VerticalResolution { get; set; }
Valor da propriedade
Examples
O exemplo a seguir mostra como definir a resolução horizontal/vertical de uma imagem de raster.
string dir = "c:\\temp\\";
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.jpg"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Get horizontal and vertical resolution of the image
double horizontalResolution = rasterImage.HorizontalResolution;
double verticalResolution = rasterImage.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");
rasterImage.SetResolution(96.0, 96.0);
System.Console.WriteLine("The horizontal resolution, in pixels per inch: {0}", rasterImage.HorizontalResolution);
System.Console.WriteLine("The vertical resolution, in pixels per inch: {0}", rasterImage.VerticalResolution);
}
// The output may look like this:
// The horizontal resolution, in pixels per inch: 300
// The vertical resolution, in pixels per inch: 300
// Set resolution values to 96 dpi
// The horizontal resolution, in pixels per inch: 96
// The vertical resolution, in pixels per inch: 96
}
Remarks
Nota por padrão este valor é sempre 96 porque diferentes plataformas não podem devolver a resolução da tela. Você pode considerar usar o método SetResolution para atualizar ambos os valores de resolução em uma única chamada.
XmpData
Receba ou coloca os metadados XMP.
public virtual XmpPacketWrapper XmpData { get; set; }
Valor da propriedade
Methods
AdjustBrightness(Int)
Ajuste de brilho para a imagem.
public virtual void AdjustBrightness(int brightness)
Parameters
brightness
int
Valor de brilho.
Examples
O exemplo seguinte realiza a correção de brilho de uma imagem.
string dir = "c:\\temp\\";
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Set the brightness value. The accepted values of brightness are in the range [-255, 255].
rasterImage.AdjustBrightness(50);
rasterImage.Save(dir + "sample.AdjustBrightness.png");
}
AdjustContrast(Flotação)
Imagem Contraste
public virtual void AdjustContrast(float contrast)
Parameters
contrast
float
Valor de contraste (em faixa [-100; 100])
Examples
O exemplo seguinte realiza a correção de contraste de uma imagem.
string dir = "c:\\temp\\";
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Set the contrast value. The accepted values of contrast are in the range [-100f, 100f].
rasterImage.AdjustContrast(50);
rasterImage.Save(dir + "sample.AdjustContrast.png");
}
AdjustGamma(Flotas, Flotas e Flotas)
Correção de Gamma de uma imagem.
public virtual void AdjustGamma(float gammaRed, float gammaGreen, float gammaBlue)
Parameters
gammaRed
float
Gamma para o Coeficiente de Canais Vermelhos
gammaGreen
float
Gamma para o coeficiente de canais verdes
gammaBlue
float
Gamma para o coeficiente de canais azuis
Examples
O exemplo a seguir realiza a correção gamma de uma imagem aplicando coeficientes diferentes para os componentes de cor.
string dir = "c:\\temp\\";
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Set individual gamma coefficients for red, green and blue channels.
rasterImage.AdjustGamma(1.5f, 2.5f, 3.5f);
rasterImage.Save(dir + "sample.AdjustGamma.png");
}
AdjustGamma(Flotação)
Correção de Gamma de uma imagem.
public virtual void AdjustGamma(float gamma)
Parameters
gamma
float
Gamma para os canais vermelho, verde e azul coeficiente
Examples
O exemplo a seguir é a correção gamma de uma imagem.
string dir = "c:\\temp\\";
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Set gamma coefficient for red, green and blue channels.
rasterImage.AdjustGamma(2.5f);
rasterImage.Save(dir + "sample.AdjustGamma.png");
}
BinarizeBradley(Dupla)
Binarização de uma imagem usando o algoritmo de limite de adaptação de Bradley usando o limite de imagem integral
public virtual void BinarizeBradley(double brightnessDifference)
Parameters
brightnessDifference
double
A diferença de brilho entre o pixel e a média de uma janela s x s de pixels centrada em torno deste pixel.
BinarizeBradley(duplo, int)
Binarização de uma imagem usando o algoritmo de limite de adaptação de Bradley usando o limite de imagem integral
public virtual void BinarizeBradley(double brightnessDifference, int windowSize)
Parameters
brightnessDifference
double
A diferença de brilho entre o pixel e a média de uma janela s x s de pixels centrada em torno deste pixel.
windowSize
int
O tamanho da janela s x s de pixels centrada em torno deste pixel
Examples
O exemplo a seguir binariza uma imagem de raster com o algoritmo de limite adaptativo de Bradley com o tamanho da janela especificado. imagens binárias contêm apenas 2 cores - preto e branco.
string dir = "c:\\temp\\";
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Binarize the image with a brightness difference of 5. The brightness is a difference between a pixel and the average of an 10 x 10 window of pixels centered around this pixel.
rasterImage.BinarizeBradley(5, 10);
rasterImage.Save(dir + "sample.BinarizeBradley5_10x10.png");
}
BinarizeFixed(em byte)
Binarização de uma imagem com um limiar predefinido
public virtual void BinarizeFixed(byte threshold)
Parameters
threshold
byte
Se o valor cinzento correspondente de um pixel for maior do que o limite, um valor de 255 será atribuído a ele, 0 de outra forma.
Examples
O exemplo a seguir binariza uma imagem raster com o limite predefinido. imagens binárias contêm apenas 2 cores - preto e branco.
string dir = "c:\\temp\\";
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Binarize the image with a threshold value of 127.
// If a corresponding gray value of a pixel is greater than 127, a value of 255 will be assigned to it, 0 otherwise.
rasterImage.BinarizeFixed(127);
rasterImage.Save(dir + "sample.BinarizeFixed.png");
}
BinarizeOtsu()
Binarização de uma imagem com o limite Otsu
public virtual void BinarizeOtsu()
Examples
O exemplo a seguir binariza uma imagem de raster com o limite Otsu. imagens binárias contêm apenas 2 cores - preto e branco.
string dir = "c:\\temp\\";
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Binarize the image with Otsu thresholding.
rasterImage.BinarizeOtsu();
rasterImage.Save(dir + "sample.BinarizeOtsu.png");
}
Blend(Ponto, RasterImage, Rectangle, byte)
Misture esta imagem com a imagem overlay".
public virtual void Blend(Point origin, RasterImage overlay, Rectangle overlayArea, byte overlayAlpha = 255)
Parameters
origin
Point
A imagem de fundo misturando a origem.
overlay
RasterImage
A imagem sobrecarregada.
overlayArea
Rectangle
Área de Overlay.
overlayAlpha
byte
A superfície da alfa.
Blend(Ponto, RasterImage, byte)
Misture esta imagem com a imagem overlay".
public void Blend(Point origin, RasterImage overlay, byte overlayAlpha = 255)
Parameters
origin
Point
A imagem de fundo misturando a origem.
overlay
RasterImage
A imagem sobrecarregada.
overlayAlpha
byte
A superfície da alfa.
Dither(Método de Dithering, int)
Exercícios que se dividem na imagem atual.
public void Dither(DitheringMethod ditheringMethod, int bitsCount)
Parameters
ditheringMethod
DitheringMethod
Metodologia do Dilúvio.
bitsCount
int
Os bits finais contam para dithering.
Examples
O exemplo a seguir carrega uma imagem de raster e realiza o limite e o fluxo de dithering usando diferentes profundidades de paleta.
string dir = "c:\\temp\\";
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Perform threshold dithering using 4-bit color palette which contains 16 colors.
// The more bits specified the higher quality and the bigger size of the output image.
// Note that only 1-bit, 4-bit and 8-bit palettes are supported at the moment.
rasterImage.Dither(Aspose.Imaging.DitheringMethod.ThresholdDithering, 4);
rasterImage.Save(dir + "sample.ThresholdDithering4.png");
}
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Perform floyd dithering using 1-bit color palette which contains only 2 colors - black and white.
// The more bits specified the higher quality and the bigger size of the output image.
// Note that only 1-bit, 4-bit and 8-bit palettes are supported at the moment.
rasterImage.Dither(Aspose.Imaging.DitheringMethod.FloydSteinbergDithering, 1);
rasterImage.Save(dir + "sample.FloydSteinbergDithering1.png");
}
Dither(DitheringMétodo, int, IColorPalette)
Exercícios que se dividem na imagem atual.
public abstract void Dither(DitheringMethod ditheringMethod, int bitsCount, IColorPalette customPalette)
Parameters
ditheringMethod
DitheringMethod
Metodologia do Dilúvio.
bitsCount
int
Os bits finais contam para dithering.
customPalette
IColorPalette
A paleta custom para dithering.
Filter(Rectangle, FilterOptionsBase)
Filtra o rectangulo especificado.
public virtual void Filter(Rectangle rectangle, FilterOptionsBase options)
Parameters
rectangle
Rectangle
do rectangulo.
options
FilterOptionsBase
As opções .
Examples
O exemplo a seguir aplica vários tipos de filtros a uma imagem de raster.
string dir = "c:\\temp\\";
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Apply a median filter with a rectangle size of 5 to the entire image.
rasterImage.Filter(rasterImage.Bounds, new Aspose.Imaging.ImageFilters.FilterOptions.MedianFilterOptions(5));
rasterImage.Save(dir + "sample.MedianFilter.png");
}
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Apply a bilateral smoothing filter with a kernel size of 5 to the entire image.
rasterImage.Filter(rasterImage.Bounds, new Aspose.Imaging.ImageFilters.FilterOptions.BilateralSmoothingFilterOptions(5));
rasterImage.Save(dir + "sample.BilateralSmoothingFilter.png");
}
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Apply a Gaussian blur filter with a radius of 5 and a sigma value of 4.0 to the entire image.
rasterImage.Filter(rasterImage.Bounds, new Aspose.Imaging.ImageFilters.FilterOptions.GaussianBlurFilterOptions(5, 4.0));
rasterImage.Save(dir + "sample.GaussianBlurFilter.png");
}
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Apply a Gauss-Wiener filter with a radius of 5 and a smooth value of 4.0 to the entire image.
rasterImage.Filter(rasterImage.Bounds, new Aspose.Imaging.ImageFilters.FilterOptions.GaussWienerFilterOptions(5, 4.0));
rasterImage.Save(dir + "sample.GaussWienerFilter.png");
}
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Apply a motion wiener filter with a length of 5, a smooth value of 4.0 and an angle of 90.0 degrees to the entire image.
rasterImage.Filter(rasterImage.Bounds, new Aspose.Imaging.ImageFilters.FilterOptions.MotionWienerFilterOptions(10, 1.0, 90.0));
rasterImage.Save(dir + "sample.MotionWienerFilter.png");
}
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Apply a sharpen filter with a kernel size of 5 and a sigma value of 4.0 to the entire image.
rasterImage.Filter(rasterImage.Bounds, new Aspose.Imaging.ImageFilters.FilterOptions.SharpenFilterOptions(5, 4.0));
rasterImage.Save(dir + "sample.SharpenFilter.png");
}
GetArgb32Pixel(Int, Int)
Obtenha uma imagem com 32 bits de pixel ARGB.
public int GetArgb32Pixel(int x, int y)
Parameters
x
int
Localização do pixel x.
y
int
O pixel e a localização.
Returns
O pixel ARGB 32 bits para a localização especificada.
Examples
O exemplo a seguir carrega uma imagem raster e obtém a cor de um pixel arbitrário representado como um valor inteiro de 32 bits.
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(@"c:\temp\sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Get an integer representation of the color of the top-left pixel of the image.
int color = rasterImage.GetArgb32Pixel(0, 0);
// To obtain the values of the individual color components, shift the color value by a corresponding number of bits
int alpha = (color >> 24) & 0xff;
int red = (color >> 16) & 0xff;
int green = (color >> 8) & 0xff;
int blue = (color >> 0) & 0xff;
System.Console.WriteLine("The color of the pixel(0,0) is A={0},R={1},G={2},B={3}", alpha, red, green, blue);
}
O exemplo a seguir mostra como o caching de imagem afeta o desempenho.Em geral, a leitura de dados cache é realizada mais rápido do que a leitura de dados não cache.
string dir = "c:\\temp\\";
// Load an image from a PNG file.
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
// Cache all pixel data so that no additional data loading will be performed from the underlying data stream
image.CacheData();
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
// Reading all pixels is pretty fast.
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
for (int y = 0; y < image.Height; y++)
{
for (int x = 0; x < image.Width; x++)
{
int color = rasterImage.GetArgb32Pixel(x, y);
}
}
stopwatch.Stop();
System.Console.WriteLine("Reading all cached pixels took {0} ms.", stopwatch.ElapsedMilliseconds);
}
// Load an image from a PNG file
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
// Reading all pixels is not as fast as when caching
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
for (int y = 0; y < image.Height; y++)
{
for (int x = 0; x < image.Width; x++)
{
int color = rasterImage.GetArgb32Pixel(x, y);
}
}
stopwatch.Stop();
System.Console.WriteLine("Reading all pixels without preliminary caching took {0} ms.", stopwatch.ElapsedMilliseconds);
}
// The output may look like this:
// Reading all cached pixels took 1500 ms.
// Reading all pixels without preliminary caching took 150000 ms.
GetDefaultArgb32Pixels(Rectangle)
Recebe o array padrão de 32 bits de pixels ARGB.
public int[] GetDefaultArgb32Pixels(Rectangle rectangle)
Parameters
rectangle
Rectangle
O rectangulo para obter pixels para.
Returns
int [ ]
Os pixels padrão são array.
GetDefaultPixels(Rectangle, IPartialArgb32PixelLoader)
Obtenha os pixels padrão array usando um carregador de pixels parciais.
public void GetDefaultPixels(Rectangle rectangle, IPartialArgb32PixelLoader partialPixelLoader)
Parameters
rectangle
Rectangle
O rectangulo para obter pixels para.
partialPixelLoader
IPartialArgb32PixelLoader
O carregador de pixel parcial.
GetDefaultRawData(Rectangle, IPartialRawDataLoader e RawDataSettings)
Obtenha a sequência de dados crus padrão usando um carregador de pixel parcial.
public void GetDefaultRawData(Rectangle rectangle, IPartialRawDataLoader partialRawDataLoader, RawDataSettings rawDataSettings)
Parameters
rectangle
Rectangle
O rectangulo para obter pixels para.
partialRawDataLoader
IPartialRawDataLoader
O carregador de dados crus parcial.
rawDataSettings
RawDataSettings
As configurações de dados crus.
GetDefaultRawData(Rectangle e RawDataSettings)
Obtenha o array de dados crus padrão.
public byte[] GetDefaultRawData(Rectangle rectangle, RawDataSettings rawDataSettings)
Parameters
rectangle
Rectangle
O rectangulo para obter dados crus para.
rawDataSettings
RawDataSettings
As configurações de dados crus.
Returns
byte [ ]
O padrão de dados crus.
GetModifyDate(Bolha)
Recebe a data e a hora que a imagem da fonte foi modificada pela última vez.
public virtual DateTime GetModifyDate(bool useDefault)
Parameters
useDefault
bool
Se configurado para “verdadeiro”, use as informações do FileInfo como valor padrão.
Returns
A data e a hora da imagem da fonte foi modificada pela última vez.
GetPixel(Int, Int)
Obtenha um pixel de imagem.
public Color GetPixel(int x, int y)
Parameters
x
int
Localização do pixel x.
y
int
O pixel e a localização.
Returns
A cor do pixel para a localização especificada.
Examples
O exemplo a seguir carrega uma imagem raster e obtém a cor de um pixel arbitrário.
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(@"c:\temp\sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Get the color of the top-left pixel of the image.
Color color = rasterImage.GetPixel(0, 0);
// Obtain the values of the individual color components
byte alpha = color.A;
byte red = color.R;
int green = color.G;
int blue = color.B;
System.Console.WriteLine("The color of the pixel(0,0) is A={0},R={1},G={2},B={3}", alpha, red, green, blue);
}
GetSkewAngle()
Conheça o ângulo escudo.Este método é aplicável aos documentos de texto escaneados, para determinar o ângulo de esquiva ao escanear.
public float GetSkewAngle()
Returns
O ângulo da escova, em graus.
Grayscale()
Transformação de uma imagem em sua representação grauscale
public virtual void Grayscale()
Examples
O exemplo a seguir transforma uma imagem de raster colorida em sua representação de grayscale. imagens de grayscale são compostas exclusivamente de sombras de cinza e carregam apenas informações de intensidade.
string dir = "c:\\temp\\";
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
rasterImage.Grayscale();
rasterImage.Save(dir + "sample.Grayscale.png");
}
LoadArgb32Pixels(Rectangle)
Carrega 32 bits de pixels ARGB.
public int[] LoadArgb32Pixels(Rectangle rectangle)
Parameters
rectangle
Rectangle
O rectangulo para carregar pixels de.
Returns
int [ ]
O array de 32 bits de pixels ARGB carregado.
Examples
O exemplo a seguir mostra como carregar e processar pixels de uma imagem raster. Os pixels são representados como valores inteiros de 32 bits. Por exemplo, considere um problema de contar pixels totalmente transparentes de uma imagem.
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(@"c:\temp\alpha.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Load pixels for the whole image. Any rectangular part of the image can be specified as a parameter of the Aspose.Imaging.RasterImage.LoadArgb32Pixels method.
int[] pixels = rasterImage.LoadArgb32Pixels(rasterImage.Bounds);
int count = 0;
foreach (int pixel in pixels)
{
int alpha = (pixel >> 24) & 0xff;
if (alpha == 0)
{
count++;
}
}
System.Console.WriteLine("The number of fully transparent pixels is {0}", count);
System.Console.WriteLine("The total number of pixels is {0}", image.Width * image.Height);
}
LoadArgb64Pixels(Rectangle)
Carrega 64 bits de pixels ARGB.
public long[] LoadArgb64Pixels(Rectangle rectangle)
Parameters
rectangle
Rectangle
O rectangulo para carregar pixels de.
Returns
long [ ]
O array de 64 bits de pixels ARGB carregado.
Examples
O exemplo a seguir mostra como carregar e processar pixels de uma imagem raster. Os pixels são representados como valores inteiros de 64 bits. Por exemplo, considere um problema de contar pixels totalmente transparentes de uma imagem.
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(@"c:\temp\16rgba.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Load pixels for the whole image. Any rectangular part of the image can be specified as a parameter of the Aspose.Imaging.RasterImage.LoadArgb64Pixels method.
// Note that the image itself must have 16 bits per sample, because Aspose.Imaging.RasterImage.LoadArgb64Pixels doesn't work with 8 bit per sample.
// In order to work with 8 bits per sample please use the good old Aspose.Imaging.RasterImage.LoadArgb32Pixels method.
long[] pixels = rasterImage.LoadArgb64Pixels(rasterImage.Bounds);
int count = 0;
foreach (int pixel in pixels)
{
// Note that all color components including alpha are represented by 16-bit values, so their allowed values are in the range [0, 63535].
int alpha = (pixel >> 48) & 0xffff;
if (alpha == 0)
{
count++;
}
}
System.Console.WriteLine("The number of fully transparent pixels is {0}", count);
System.Console.WriteLine("The total number of pixels is {0}", image.Width * image.Height);
}
LoadCmyk32Pixels(Rectangle)
Carregar pixels em formato CMYK.
public int[] LoadCmyk32Pixels(Rectangle rectangle)
Parameters
rectangle
Rectangle
O rectangulo para carregar pixels de.
Returns
int [ ]
Os pixels CMYK carregados apresentam-se como valores inateger de 32 bits.
LoadCmykPixels(Rectangle)
Carregar pixels em formato CMYK.Por favor, use mais eficazmente o método Aspose.Imaging.RasterImage.LoadCmyk32Pixels(Aspose.Imaging.Rectangle).
[Obsolete("Method is obsolete")]
public CmykColor[] LoadCmykPixels(Rectangle rectangle)
Parameters
rectangle
Rectangle
O rectangulo para carregar pixels de.
Returns
CmykColor [ ]
O array de pixels CMYK carregado.
LoadPartialArgb32Pixels(Rectangle, IPartialArgb32PixelLoader)
Carrega 32 bits de pixels ARGB parcialmente por pacotes.
public void LoadPartialArgb32Pixels(Rectangle rectangle, IPartialArgb32PixelLoader partialPixelLoader)
Parameters
rectangle
Rectangle
O rectangulo desejado.
partialPixelLoader
IPartialArgb32PixelLoader
O carregador de pixels ARGB de 32 bits.
Examples
O exemplo a seguir mostra como carregar e processar pixels de uma imagem raster usando seu próprio processador parcial. Por exemplo, considerar um problema de contar pixels totalmente transparentes de uma imagem. Para contar pixels transparentes usando mecanismo de carregamento parcial, uma classe separada TransparentArgb32PixelCounter implementando Aspose.Imaging.IPartialArgb32PixelLoader é introduzido.
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(@"c:\temp\alpha.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Create an instance of the Aspose.Imaging.IPartialArgb32PixelLoader and pass it to the Aspose.Imaging.RasterImage.LoadPartialArgb32Pixels
TransparentArgb32PixelCounter counter = new TransparentArgb32PixelCounter();
// Load pixels for the whole image. Any rectangular part of the image can be specified as the first parameter of the Aspose.Imaging.RasterImage.LoadPartialArgb32Pixels method.
rasterImage.LoadPartialArgb32Pixels(rasterImage.Bounds, counter);
System.Console.WriteLine("The number of fully transparent pixels is {0}", counter.Count);
System.Console.WriteLine("The total number of pixels is {0}", image.Width * image.Height);
}
// The counter may look like this:
/// <summary>
/// Counts the number of fully transparent pixels with alpha channel value of 0.
/// </summary>
private class TransparentArgb32PixelCounter : IPartialArgb32PixelLoader
{
/// <summary>
/// The number of fully transparent pixels.
/// </summary>
private int count;
/// <summary>
/// Gets the number of fully transparent pixels.
/// </summary>
public int Count
{
get { return this.count; }
}
/// <summary>
/// Processes the loaded pixels. This method is called back every time when a new portion of pixels is loaded.
/// </summary>
/// <param name="pixelsRectangle"/>The pixels rectangle.
/// <param name="pixels"/>The 32-bit ARGB pixels.
/// <param name="start"/>The start pixels point.
/// <param name="end"/>The end pixels point.
public void Process(Aspose.Imaging.Rectangle pixelsRectangle, int[] pixels, Aspose.Imaging.Point start, Aspose.Imaging.Point end)
{
foreach (int pixel in pixels)
{
int alpha = (pixel >> 24) & 0xff;
if (alpha == 0)
{
this.count++;
}
}
}
}
LoadPartialArgb64Pixels(Rectangle, IPartialArgb64PixelLoader)
Carrega 64 bits de pixels ARGB parcialmente por pacotes.
public void LoadPartialArgb64Pixels(Rectangle rectangle, IPartialArgb64PixelLoader partialPixelLoader)
Parameters
rectangle
Rectangle
O rectangulo desejado.
partialPixelLoader
IPartialArgb64PixelLoader
O carregador de pixels ARGB de 64 bits.
LoadPartialPixels(Rectangle e IPartialPixelLoader)
Carrega os pixels parcialmente por pacotes.
public void LoadPartialPixels(Rectangle desiredRectangle, IPartialPixelLoader pixelLoader)
Parameters
desiredRectangle
Rectangle
O rectangulo desejado.
pixelLoader
IPartialPixelLoader
O carregador de pixel.
Examples
O exemplo a seguir mostra como carregar e processar pixels de uma imagem raster usando seu próprio processador parcial. Por exemplo, considerar um problema de contar pixels totalmente transparentes de uma imagem. Para contar transparentes usando mecanismo de carregamento parcial, uma classe separada TransparentPixelCounter implementando Aspose.Imaging.IPartialPixelLoader é introduzido.
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(@"c:\temp\alpha.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Create an instance of the Aspose.Imaging.IPartialPixelLoader and pass it to the Aspose.Imaging.RasterImage.LoadPartialPixels
TransparentPixelCounter counter = new TransparentPixelCounter();
// Load pixels for the whole image. Any rectangular part of the image can be specified as the first parameter of the Aspose.Imaging.RasterImage.LoadPartialPixels method.
rasterImage.LoadPartialPixels(rasterImage.Bounds, counter);
System.Console.WriteLine("The number of fully transparent pixels is {0}", counter.Count);
System.Console.WriteLine("The total number of pixels is {0}", image.Width * image.Height);
}
// The counter may look like this:
/// <summary>
/// Counts the number of fully transparent pixels with alpha channel value of 0.
/// </summary>
private class TransparentPixelCounter : IPartialPixelLoader
{
/// <summary>
/// The number of fully transparent pixels.
/// </summary>
private int count;
/// <summary>
/// Gets the number of fully transparent pixels.
/// </summary>
public int Count
{
get { return this.count; }
}
/// <summary>
/// Processes the loaded pixels. This method is called back every time when a new portion of pixels is loaded.
/// </summary>
/// <param name="pixelsRectangle"/>The pixels rectangle.
/// <param name="pixels"/>The 32-bit ARGB pixels.
/// <param name="start"/>The start pixels point.
/// <param name="end"/>The end pixels point.
public void Process(Aspose.Imaging.Rectangle pixelsRectangle, Aspose.Imaging.Color[] pixels, Aspose.Imaging.Point start, Aspose.Imaging.Point end)
{
foreach (Color pixel in pixels)
{
if (pixel.A == 0)
{
this.count++;
}
}
}
}
LoadPixels(Rectangle)
carregando os pixels.
public Color[] LoadPixels(Rectangle rectangle)
Parameters
rectangle
Rectangle
O rectangulo para carregar pixels de.
Returns
Color [ ]
Os pixels carregados.
Examples
O exemplo a seguir mostra como carregar e processar pixels de uma imagem raster. Por exemplo, considere um problema de contar pixels totalmente transparentes de uma imagem.
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(@"c:\temp\alpha.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Load pixels for the whole image. Any rectangular part of the image can be specified as a parameter of the Aspose.Imaging.RasterImage.LoadPixels method.
Color[] pixels = rasterImage.LoadPixels(rasterImage.Bounds);
int count = 0;
foreach (Color pixel in pixels)
{
if (pixel.A == 0)
{
count++;
}
}
System.Console.WriteLine("The number of fully transparent pixels is {0}", count);
System.Console.WriteLine("The total number of pixels is {0}", image.Width * image.Height);
}
Este exemplo mostra como carregar informações do Pixel em um Array de Tipo de Cor, manipula o array e a coloca de volta à imagem. Para executar essas operações, este exemplo cria um novo arquivo de imagem (em formato GIF) uisng Objeto MemoryStream.
//Create an instance of MemoryStream
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
//Create an instance of GifOptions and set its various properties including the Source property
Aspose.Imaging.ImageOptions.GifOptions gifOptions = new Aspose.Imaging.ImageOptions.GifOptions();
gifOptions.Source = new Aspose.Imaging.Sources.StreamSource(stream);
//Create an instance of Image
using (Aspose.Imaging.RasterImage image = (Aspose.Imaging.RasterImage)Aspose.Imaging.Image.Create(gifOptions, 500, 500))
{
//Get the pixels of image by specifying the area as image boundary
Aspose.Imaging.Color[] pixels = image.LoadPixels(image.Bounds);
//Loop over the Array and sets color of alrenative indexed pixel
for (int index = 0; index < pixels.Length; index++)
{
if (index % 2 == 0)
{
//Set the indexed pixel color to yellow
pixels[index] = Aspose.Imaging.Color.Yellow;
}
else
{
//Set the indexed pixel color to blue
pixels[index] = Aspose.Imaging.Color.Blue;
}
}
//Apply the pixel changes to the image
image.SavePixels(image.Bounds, pixels);
// save all changes.
image.Save();
}
// Write MemoryStream to File
using (System.IO.FileStream fileStream = new System.IO.FileStream(@"C:\temp\output.gif", System.IO.FileMode.Create))
{
stream.WriteTo(fileStream);
}
}
LoadRawData(Rectangle, RawDataSettings, IPartialRawDataLoader)
Carga de dados crus.
public void LoadRawData(Rectangle rectangle, RawDataSettings rawDataSettings, IPartialRawDataLoader rawDataLoader)
Parameters
rectangle
Rectangle
O rectangulo para carregar dados crus de.
rawDataSettings
RawDataSettings
As configurações de dados crus para usar para dados carregados. Observe se os dados não estão no formato especificado, então a conversão de dados será realizada.
rawDataLoader
IPartialRawDataLoader
O carregador de dados crus.
Examples
O exemplo a seguir mostra como extrair pixels dos dados da imagem cru usando RawDataSettings. por exemplo, considere um problema de contar pixels totalmente transparentes de uma imagem.
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(@"c:\temp\GrayscaleWithAlpha.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
Aspose.Imaging.RawDataSettings settings = rasterImage.RawDataSettings;
TransparentPixelRawDataCounter rawDataLoader = new TransparentPixelRawDataCounter(settings);
// Load pixels for the whole image. Any rectangular part of the image can be specified as a parameter of the Aspose.Imaging.RasterImage.LoadRawData method.
rasterImage.LoadRawData(rasterImage.Bounds, settings, rawDataLoader);
System.Console.WriteLine("The number of fully transparent pixels is {0}", rawDataLoader.Count);
System.Console.WriteLine("The total number of pixels is {0}", image.Width * image.Height);
}
// In case of raw data, the counter may look like this:
/// <summary>
/// Counts the number of fully transparent pixels with alpha channel value of 0.
/// </summary>
private class TransparentPixelRawDataCounter : IPartialRawDataLoader
{
/// <summary>
/// The number of fully transparent pixels.
/// </summary>
private int count;
/// <summary>
/// The raw data settings of the loaded image.
/// </summary>
private Aspose.Imaging.RawDataSettings rawDataSettings;
/// <summary>
/// Gets the number of fully transparent pixels.
/// </summary>
public int Count
{
get { return this.count; }
}
/// <summary>
/// Initializes a new instance of the <see transparentpixelrawdatacounter=""></see> class.
/// </summary>
/// <param name="settings"/>The raw data settings allow to extract color components from raw data.
public TransparentPixelRawDataCounter(Aspose.Imaging.RawDataSettings settings)
{
this.rawDataSettings = settings;
this.count = 0;
}
/// <summary>
/// Processes the loaded raw data. This method is called back every time when a new portion of raw data is loaded.
/// </summary>
/// <param name="dataRectangle"/>The raw data rectangle.
/// <param name="data"/>The raw data.
/// <param name="start"/>The start data point.
/// <param name="end"/>The end data point.
public void Process(Aspose.Imaging.Rectangle dataRectangle, byte[] data, Aspose.Imaging.Point start, Aspose.Imaging.Point end)
{
int[] channelBits = this.rawDataSettings.PixelDataFormat.ChannelBits;
// Only simple formats are consdired here to simplify the code.
// Let's consider only images with 8 bits per sample.
for (int i = 0; i < channelBits.Length; i++)
{
if (channelBits[i] != 8)
{
throw new System.NotSupportedException();
}
}
switch (this.rawDataSettings.PixelDataFormat.PixelFormat)
{
case PixelFormat.Rgb:
case PixelFormat.Bgr:
{
if (channelBits.Length == 4)
{
// ARGB
for (int i = 0; i < data.Length; i += 4)
{
// The alpha channel is stored last, after the color components.
if (data[i + 3] == 0)
{
this.count++;
}
}
}
}
break;
case PixelFormat.Grayscale:
{
if (channelBits.Length == 2)
{
// Grayscale Alpha
for (int i = 0; i < data.Length; i += 2)
{
// The alpha channel is stored last, after the color components.
if (data[i + 1] == 0)
{
this.count++;
}
}
}
}
break;
default:
throw new System.ArgumentOutOfRangeException("PixelFormat");
}
}
/// <summary>
/// Processes the loaded raw data. This method is called back every time when a new portion of raw data is loaded.
/// </summary>
/// <param name="dataRectangle"/>The raw data rectangle.
/// <param name="data"/>The raw data.
/// <param name="start"/>The start data point.
/// <param name="end"/>The end data point.
/// <param name="loadOptions"/>The load options.
public void Process(Aspose.Imaging.Rectangle dataRectangle, byte[] data, Aspose.Imaging.Point start, Aspose.Imaging.Point end, Aspose.Imaging.LoadOptions loadOptions)
{
this.Process(dataRectangle, data, start, end);
}
}
LoadRawData(Rectangle, Rectangle, RawDataSettings, IPartialRawDataLoader)
Carga de dados crus.
public void LoadRawData(Rectangle rectangle, Rectangle destImageBounds, RawDataSettings rawDataSettings, IPartialRawDataLoader rawDataLoader)
Parameters
rectangle
Rectangle
O rectangulo para carregar dados crus de.
destImageBounds
Rectangle
A imagem é limitada.
rawDataSettings
RawDataSettings
As configurações de dados crus para usar para dados carregados. Observe se os dados não estão no formato especificado, então a conversão de dados será realizada.
rawDataLoader
IPartialRawDataLoader
O carregador de dados crus.
NormalizeAngle()
Normalize o ângulo.Este método é aplicável aos documentos de texto escaneados para se livrar do escaneamento esquecido.Este método usa os métodos Aspose.Imaging.RasterImage.GetSkewAngle e Aspose.Imaging.RasterImage.Rotate(System.Single).
public void NormalizeAngle()
NormalizeAngle(Bool, Coloração)
Normalize o ângulo.Este método é aplicável aos documentos de texto escaneados para se livrar do escaneamento esquecido.Este método usa os métodos Aspose.Imaging.RasterImage.GetSkewAngle e Aspose.Imaging.RasterImage.Rotate(System.Single,System.Boolean,Aspose.Imaging.Color).
public virtual void NormalizeAngle(bool resizeProportionally, Color backgroundColor)
Parameters
resizeProportionally
bool
Se configurado para “verdadeiro”, você terá o seu tamanho da imagem alterado de acordo com as projeções de rectangular rotado (punto de corno) noutro caso que deixa as dimensões não tocadas e apenas os conteúdos da imagem interna são rotados.
backgroundColor
Color
A cor do fundo.
Examples
Skew é um artefato que pode aparecer durante o processo de escaneamento de documentos quando o texto/imagens do documento são girados em um ângulo leve. Pode ter várias causas, mas o mais comum é que o papel é errado durante um escaneamento. Portanto, deskew é o processo de detectar e corrigir este problema em arquivos escaneados (ou seja, bitmap) para que os documentos deskewed tenham o texto/imagens corretamente e horizontalmente ajustados.
string dir = "c:\\aspose.imaging\\issues\\net\\3567\\";
string inputFilePath = dir + "skewed.png";
string outputFilePath = dir + "skewed.out.png";
// Get rid of the skewed scan with default parameters
using (Aspose.Imaging.RasterImage image = (Aspose.Imaging.RasterImage)Aspose.Imaging.Image.Load(inputFilePath))
{
// Deskew
image.NormalizeAngle(false /*do not resize*/, Aspose.Imaging.Color.LightGray /*background color*/);
image.Save(outputFilePath);
}
NormalizeHistogram()
Normalize o histograma da imagem — ajuste os valores de pixel para usar todas as faixas disponíveis.
public virtual void NormalizeHistogram()
ReadArgb32ScanLine(Int)
Leia toda a linha de escaneamento pelo índice de linha de escaneamento especificado.
public int[] ReadArgb32ScanLine(int scanLineIndex)
Parameters
scanLineIndex
int
Índice baseado em zero da linha de escaneamento.
Returns
int [ ]
A linha de escaneamento 32-bit ARGB valores de cor array.
ReadScanLine(Int)
Leia toda a linha de escaneamento pelo índice de linha de escaneamento especificado.
public Color[] ReadScanLine(int scanLineIndex)
Parameters
scanLineIndex
int
Índice baseado em zero da linha de escaneamento.
Returns
Color [ ]
A linha de scan pixel valores de cor array.
ReleaseManagedResources()
Assegure-se de que os recursos não gerenciados não sejam liberados aqui, uma vez que eles podem já ter sido liberados.
protected override void ReleaseManagedResources()
RemoveMetadata()
Remove este exemplo de imagem metadados configurando este Aspose.Imaging.Xmp.IHasXMPData. Nula.
public override void RemoveMetadata()
ReplaceColor(Coloração, byte e cor)
Substitui uma cor para outra com a diferença permitida e preserva o valor alfa original para salvar os lados suaves.
public void ReplaceColor(Color oldColor, byte oldColorDiff, Color newColor)
Parameters
oldColor
Color
As cores antigas devem ser substituídas.
oldColorDiff
byte
Permite a diferença na cor antiga para ser capaz de ampliar o tom de cor substituído.
newColor
Color
Uma nova cor para substituir a velha.
ReplaceColor(Int, byte e int)
Substitui uma cor para outra com a diferença permitida e preserva o valor alfa original para salvar os lados suaves.
public virtual void ReplaceColor(int oldColorArgb, byte oldColorDiff, int newColorArgb)
Parameters
oldColorArgb
int
O antigo valor de cor ARGB deve ser substituído.
oldColorDiff
byte
Permite a diferença na cor antiga para ser capaz de ampliar o tom de cor substituído.
newColorArgb
int
Nova cor ARGB valor para substituir a cor velha com.
ReplaceNonTransparentColors(Color)
Substitui todas as cores não transparentes com uma nova cor e conserva o valor alfa original para salvar os lados suaves.Nota: se você usá-lo em imagens sem transparência, todas as cores serão substituídas por uma única.
public void ReplaceNonTransparentColors(Color newColor)
Parameters
newColor
Color
Novas cores para substituir as cores não transparentes.
ReplaceNonTransparentColors(Int)
Substitui todas as cores não transparentes com uma nova cor e conserva o valor alfa original para salvar os lados suaves.Nota: se você usá-lo em imagens sem transparência, todas as cores serão substituídas por uma única.
public virtual void ReplaceNonTransparentColors(int newColorArgb)
Parameters
newColorArgb
int
Novo valor de cor ARGB para substituir as cores não transparentes com.
Resize(Int, Int, ImagemResizeSettings)
Recuperar a imagem com opções extensas.
public override void Resize(int newWidth, int newHeight, ImageResizeSettings settings)
Parameters
newWidth
int
A nova amplitude.
newHeight
int
A nova altura.
settings
ImageResizeSettings
As definições de recessão.
Examples
Este exemplo carrega uma imagem de raster e a resisa usando várias configurações de resisação.
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");
}
Rotate(Float, Bool, Coloração)
Rotando a imagem ao redor do centro.
public virtual void Rotate(float angle, bool resizeProportionally, Color backgroundColor)
Parameters
angle
float
O ângulo de rotação em graus. valores positivos girarão de maneira horária.
resizeProportionally
bool
Se configurado para “verdadeiro”, você terá o seu tamanho da imagem alterado de acordo com as projeções de rectangular rotado (punto de corno) noutro caso que deixa as dimensões não tocadas e apenas os conteúdos da imagem interna são rotados.
backgroundColor
Color
A cor do fundo.
Exceptions
Exceção não implementada
Rotate(Flotação)
Rotando a imagem ao redor do centro.
public override void Rotate(float angle)
Parameters
angle
float
O ângulo de rotação em graus. valores positivos girarão de maneira horária.
Save(Stream, Opções de imagemBase, Rectangle)
Salve os dados da imagem para o fluxo especificado no formato de arquivo especificado de acordo com as opções de salvo.
public override void Save(Stream stream, ImageOptionsBase optionsBase, Rectangle boundsRectangle)
Parameters
stream
Stream
O fluxo para salvar os dados da imagem para.
optionsBase
ImageOptionsBase
As opções de poupança.
boundsRectangle
Rectangle
A imagem de destino limita o rectangulo. Configura o rectangulo vazio para usar os limites de fonte.
SaveArgb32Pixels(Direção, int[])
Conserva os 32 bits de pixels ARGB.
public void SaveArgb32Pixels(Rectangle rectangle, int[] pixels)
Parameters
rectangle
Rectangle
O rectangulo para salvar pixels para.
pixels
int
[ ]
O 32-bit ARGB pixels array.
Examples
O exemplo a seguir enche a área central de uma imagem de raster com pixels negros usando o método Aspose.Imaging.RasterImage.SaveArgb32Pixels.
string dir = "c:\\temp\\";
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// The black square
int[] pixels = new int[(rasterImage.Width / 2) * (rasterImage.Height / 2)];
for (int i = 0; i < pixels.Length; i++)
{
pixels[i] = Color.Black.ToArgb();
}
// Draw the black square at the center of the image.
Aspose.Imaging.Rectangle area = new Aspose.Imaging.Rectangle(rasterImage.Width / 4, rasterImage.Height / 4, rasterImage.Width / 2, rasterImage.Height / 2);
rasterImage.SaveArgb32Pixels(area, pixels);
rasterImage.Save(dir + "sample.SaveArgb32Pixels.png");
}
SaveCmyk32Pixels(Direção, int[])
Salve os pixels.
public void SaveCmyk32Pixels(Rectangle rectangle, int[] pixels)
Parameters
rectangle
Rectangle
O rectangulo para salvar pixels para.
pixels
int
[ ]
Os pixels CMYK apresentados como os valores inteiros de 32 bits.
Examples
O exemplo a seguir enche a área central de uma imagem de raster com pixels negros usando o método Aspose.Imaging.RasterImage.SaveCmyk32Pixels.
string dir = @"c:\temp\";
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Get an integer representation of black in the CMYK color space.
int blackCmyk = Aspose.Imaging.CmykColorHelper.ToCmyk(Color.Black);
// The black square.
int[] pixels = new int[(rasterImage.Width / 2) * (rasterImage.Height / 2)];
for (int i = 0; i < pixels.Length; i++)
{
pixels[i] = blackCmyk;
}
// Draw the black square at the center of the image.
Aspose.Imaging.Rectangle area = new Aspose.Imaging.Rectangle(rasterImage.Width / 4, rasterImage.Height / 4, rasterImage.Width / 2, rasterImage.Height / 2);
rasterImage.SaveCmyk32Pixels(area, pixels);
rasterImage.Save(dir + "sample.SaveCmyk32Pixels.png");
}
SaveCmykPixels(Rectangle e CmykColor[])
Salve os pixels.Por favor, use mais eficazmente o método Aspose.Imaging.RasterImage.SaveCmyk32Pixels(Aspose.Imaging.Rectangle,System.Int32[]).
[Obsolete("Method is obsolete")]
public void SaveCmykPixels(Rectangle rectangle, CmykColor[] pixels)
Parameters
rectangle
Rectangle
O rectangulo para salvar pixels para.
pixels
CmykColor
[ ]
Os pixels CMYK são array.
SavePixels(Rectangle, Coloração[])
Salve os pixels.
public void SavePixels(Rectangle rectangle, Color[] pixels)
Parameters
rectangle
Rectangle
O rectangulo para salvar pixels para.
pixels
Color
[ ]
Os pixels são arrasados.
Examples
O exemplo a seguir enche a área central de uma imagem de raster com pixels negros usando o método Aspose.Imaging.RasterImage.SavePixels.
string dir = "c:\\temp\\";
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// The black square
Color[] pixels = new Color[(rasterImage.Width / 2) * (rasterImage.Height / 2)];
for (int i = 0; i < pixels.Length; i++)
{
pixels[i] = Color.Black;
}
// Draw the black square at the center of the image.
Aspose.Imaging.Rectangle area = new Aspose.Imaging.Rectangle(rasterImage.Width / 4, rasterImage.Height / 4, rasterImage.Width / 2, rasterImage.Height / 2);
rasterImage.SavePixels(area, pixels);
rasterImage.Save(dir + "sample.SavePixels.png");
}
Este exemplo mostra como carregar informações do Pixel em um Array de Tipo de Cor, manipula o array e a coloca de volta à imagem. Para executar essas operações, este exemplo cria um novo arquivo de imagem (em formato GIF) uisng Objeto MemoryStream.
//Create an instance of MemoryStream
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
//Create an instance of GifOptions and set its various properties including the Source property
Aspose.Imaging.ImageOptions.GifOptions gifOptions = new Aspose.Imaging.ImageOptions.GifOptions();
gifOptions.Source = new Aspose.Imaging.Sources.StreamSource(stream);
//Create an instance of Image
using (Aspose.Imaging.RasterImage image = (Aspose.Imaging.RasterImage)Aspose.Imaging.Image.Create(gifOptions, 500, 500))
{
//Get the pixels of image by specifying the area as image boundary
Aspose.Imaging.Color[] pixels = image.LoadPixels(image.Bounds);
//Loop over the Array and sets color of alrenative indexed pixel
for (int index = 0; index < pixels.Length; index++)
{
if (index % 2 == 0)
{
//Set the indexed pixel color to yellow
pixels[index] = Aspose.Imaging.Color.Yellow;
}
else
{
//Set the indexed pixel color to blue
pixels[index] = Aspose.Imaging.Color.Blue;
}
}
//Apply the pixel changes to the image
image.SavePixels(image.Bounds, pixels);
// save all changes.
image.Save();
}
// Write MemoryStream to File
using (System.IO.FileStream fileStream = new System.IO.FileStream(@"C:\temp\output.gif", System.IO.FileMode.Create))
{
stream.WriteTo(fileStream);
}
}
SaveRawData(em byte[ ], int, Rectangle, RawDataSettings)
Acompanhe os dados crus.
public void SaveRawData(byte[] data, int dataOffset, Rectangle rectangle, RawDataSettings rawDataSettings)
Parameters
data
byte
[ ]
Os dados crus.
dataOffset
int
O início dos dados crus é reembolsado.
rectangle
Rectangle
O rectangulo dos dados.
rawDataSettings
RawDataSettings
As configurações de dados crus que os dados estão em.
SetArgb32Pixel(Int, int, int)
Crie um pixel ARGB de imagem de 32 bits para a posição especificada.
public void SetArgb32Pixel(int x, int y, int argb32Color)
Parameters
x
int
Localização do pixel x.
y
int
O pixel e a localização.
argb32Color
int
O pixel ARGB de 32 bits para a posição especificada.
Examples
O exemplo a seguir carrega uma imagem raster, e coloca a cor de um pixel arbitrário.
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(@"c:\temp\sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Sets the color of the top-left pixel.
rasterImage.SetArgb32Pixel(0, 0, Aspose.Imaging.Color.Aqua.ToArgb());
// Another way is to pass an instance of the Aspose.Imaging.Color directly
rasterImage.SetPixel(0, 0, Aspose.Imaging.Color.Aqua);
}
SetPalette(Coloração, Bool)
Faça a paleta de imagem.
public override void SetPalette(IColorPalette palette, bool updateColors)
Parameters
palette
IColorPalette
A paleta para definir.
updateColors
bool
se configurado para “verdadeira” cores será atualizado de acordo com a nova paleta; caso contrário, os índices de cores permanecem inalterados. note que os índices inalterados podem quebrar a imagem no carregamento se alguns índices não têm entradas de paleta correspondentes.
SetPixel(int, int, cor)
Crie um pixel de imagem para a posição especificada.
public void SetPixel(int x, int y, Color color)
Parameters
x
int
Localização do pixel x.
y
int
O pixel e a localização.
color
Color
A cor do pixel para a posição especificada.
Examples
O exemplo a seguir carrega uma imagem raster, e coloca a cor de um pixel arbitrário.
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(@"c:\temp\sample.png"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Sets the color of the top-left pixel.
rasterImage.SetArgb32Pixel(0, 0, Aspose.Imaging.Color.Aqua.ToArgb());
// Another way is to pass an instance of the Aspose.Imaging.Color directly
rasterImage.SetPixel(0, 0, Aspose.Imaging.Color.Aqua);
}
SetResolution(duplo, duplo)
Configura a resolução para este Aspose.Imaging.RasterImage.
public virtual void SetResolution(double dpiX, double dpiY)
Parameters
dpiX
double
A resolução horizontal, em pontos por polegada, do Aspose.Imaging.RasterImage.
dpiY
double
A resolução vertical, em pontos por polegada, do Aspose.Imaging.RasterImage.
Examples
O exemplo a seguir mostra como definir a resolução horizontal/vertical de uma imagem de raster.
string dir = "c:\\temp\\";
using (Aspose.Imaging.Image image = Aspose.Imaging.Image.Load(dir + "sample.jpg"))
{
Aspose.Imaging.RasterImage rasterImage = (Aspose.Imaging.RasterImage)image;
// Get horizontal and vertical resolution of the image
double horizontalResolution = rasterImage.HorizontalResolution;
double verticalResolution = rasterImage.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");
rasterImage.SetResolution(96.0, 96.0);
System.Console.WriteLine("The horizontal resolution, in pixels per inch: {0}", rasterImage.HorizontalResolution);
System.Console.WriteLine("The vertical resolution, in pixels per inch: {0}", rasterImage.VerticalResolution);
}
// The output may look like this:
// The horizontal resolution, in pixels per inch: 300
// The vertical resolution, in pixels per inch: 300
// Set resolution values to 96 dpi
// The horizontal resolution, in pixels per inch: 96
// The vertical resolution, in pixels per inch: 96
}
ToBitmap()
Converte a imagem de raster para o bitmap.Este método não é suportado em versões de .Net7.0 ou superior
public virtual Bitmap ToBitmap()
Returns
O Bitmap
UpdateDimensions(Int, Int)
Atualiza as dimensões da imagem.
protected abstract void UpdateDimensions(int newWidth, int newHeight)
Parameters
newWidth
int
A nova imagem de largura.
newHeight
int
O novo tamanho da imagem.
UpdateMetadata()
Atualiza os metadados da imagem.
protected virtual void UpdateMetadata()
WriteArgb32ScanLine(Int, Int[])
Escreva toda a linha de escaneamento para o índice de linha de escaneamento especificado.
public void WriteArgb32ScanLine(int scanLineIndex, int[] argb32Pixels)
Parameters
scanLineIndex
int
Índice baseado em zero da linha de escaneamento.
argb32Pixels
int
[ ]
As cores ARGB de 32 bits permitem escrever.
WriteScanLine(Int, Coloração[])
Escreva toda a linha de escaneamento para o índice de linha de escaneamento especificado.
public void WriteScanLine(int scanLineIndex, Color[] pixels)
Parameters
scanLineIndex
int
Índice baseado em zero da linha de escaneamento.
pixels
Color
[ ]
As cores do pixel estão preparadas para escrever.