Biblioteca de mapas de bits de C# para reemplazar System.Drawing.Common en .NET

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronDrawing es gratuito, de código abierto y compatible con la mayoría de los formatos de biblioteca de dibujo .NET.

IronDrawing es una biblioteca de código abierto desarrollada originalmente por Iron Software que ayuda a los ingenieros de software en C# a reemplazar System.Drawing.Common en proyectos .NET en las plataformas Windows, macOS y Linux.

Desarrollar bibliotecas de clases y paquetes NuGet para .NET 5, 6, 7 y 8 que admitan gráficos, imágenes y fuentes debería ser fácil.

IronDrawing actúa como un puente sin fisuras entre todos los nuevos estándares de gráficos propuestos para .NET 5, 6, 7 y 8 a medida que evolucionan, por lo que solo necesitas desarrollar para el que prefieras.

IronDrawing es gratuito, de código abierto y compatible con la mayoría de los formatos de biblioteca de dibujo .NET.

Contexto

Microsoft .NET es un marco de software multiplataforma y altamente compatible utilizado por millones de desarrolladores de software en todo el mundo. Microsoft ha anunciado un cambio importante en el que System.Drawing.Common solo será compatible en plataformas Windows.

Esto es problemático para los desarrolladores de bibliotecas .NET que mantienen bibliotecas multiplataforma que usan System.Drawing.Common, porque la acción recomendada de Microsoft requiere que reconstruyas tu biblioteca para dar soporte a usuarios no Windows. Se espera que voluntarios y académicos reconstruyan cada paquete NuGet y biblioteca de clases para usar cada una de las nuevas bibliotecas gráficas sugeridas a medida que surgen, lo que causa una deuda técnica que ralentizará la adopción del .NET moderno.

En última instancia, cuando usamos .NET, usamos NuGet.

Los desarrolladores de paquetes NuGet nos están haciendo un favor a todos al avanzar en .NET y en el código preempaquetado que nos llevaría miles de horas escribir nosotros mismos cada día.

Este cambio importante ralentizará el desarrollo de NuGet y podría conducir a bibliotecas de código abandonadas u obsoletas de las que dependen los desarrolladores de .NET. ¡Necesitamos actuar ahora!

Nuestra solución

Un formato gráfico intermediario que convierta entre todas las bibliotecas gráficas antiguas y nuevas.

Como desarrollador de bibliotecas de clases, tus entradas y salidas públicas Bitmap, Color, Rectangle, Font y Size pueden ser de solo un tipo que soporte todos los nuevos estándares. Internamente, puedes continuar haciendo lo que te guste.

IronDrawing es compatible con versiones anteriores de .NET Framework 4.62 y admite todas las versiones de .NET (incluido .NET 8).

El desarrollo y lanzamiento de IronDrawing resuelve este problema al proporcionar una solución de código abierto a la falta de un formato uniforme para clases importantes como Bitmap, Color, Rectangle, Font y Size. Iron Software.Drawing convertirá sin problemas entre las implementaciones de estos tipos en System.Drawing, Microsoft.Maui, SkiaSharp y SixLabors para ti. Esto te permite a ti, el desarrollador, no tener que reemplazar todas las instancias de estas clases dentro de tu biblioteca.

Por ejemplo, si estás usando System.Drawing.Bitmap, puedes usar la clase AnyBitmap de IronDrawing, que tiene conversiones implícitas a cualquiera de estos tipos: System.Drawing.Bitmap, System.Drawing.Image, SkiaSharp.SKBitmap, SkiaSharp.SKImage, SixLabors.ImageSharp, Microsoft.Maui.Graphics.Platform.PlatformImage.

¿Por qué hacemos esto gratis?

Hemos desarrollado IronDrawing porque en Iron Software somos desarrolladores senior de .NET a largo plazo que nos preocupamos por la evolución de .NET y queremos que crezca y tenga éxito. Nos encanta ver que .NET está creciendo y evolucionando, como se ve con .NET 7. Usamos NuGet todo el día, y estoy seguro de que tú también. Apoyamos y esperamos fomentar una fácil transición al futuro y alejarse de System.Drawing.

Queremos que todo el desarrollo de bibliotecas de clases y NuGet de .NET sea más fácil, para que el Ecosistema NuGet continúe prosperando, y para que todos los desarrolladores de .NET se beneficien.

Características IronSoftware.Drawing

  • AnyBitmap: Una clase de Bitmap universalmente compatible. Conversión implícita entre Iron Software.Drawing.AnyBitmap y los siguientes soportados:
    • System.Drawing.Bitmap
    • System.Drawing.Image
    • SkiaSharp.SKBitmap
    • SkiaSharp.SKImage
    • SixLabors.ImageSharp
    • Microsoft.Maui.Graphics.Platform.PlatformImage
  • Color: Una clase de Color universalmente compatible. Conversión implícita entre Iron Software.Drawing.Color y los siguientes soportados:
    • System.Drawing.Color
    • SkiaSharp.SKColor
    • SixLabors.ImageSharp.Color
    • SixLabors.ImageSharp.PixelFormats
  • Rectangle: Una clase de Rectangle universalmente compatible. Conversión implícita entre Iron Software.Drawing.Rectangle y los siguientes soportados:
    • System.Drawing.Rectangle
    • SkiaSharp.SKRect
    • SkiaSharp.SKRectI
    • SixLabors.ImageSharp.Rectangle
  • Font: Una clase de Font universalmente compatible. Conversión implícita entre Iron Software.Drawing.Font y los siguientes soportados:
    • System.Drawing.Font
    • SkiaSharp.SKFont
    • SixLabors.Fonts.Font

Compatibilidad

Iron Software.Drawing tiene compatibilidad de soporte multiplataforma con:

  • .NET 8, .NET 7, .NET 6, .NET 5, .NET Core, .NET Standard y .NET Framework 4.62+
  • Windows, macOS, Linux, Docker, Azure y AWS

Instalación

Instalar el paquete NuGet de IronDrawing (Iron Software.Drawing) es rápido y fácil. Por favor, instala el paquete de esta manera:

Install-Package IronSoftware.System.Drawing

Alternativamente, descarga directamente desde el sitio web oficial de NuGet.

Una vez instalado, puedes comenzar agregando using Iron Software.Drawing; en la parte superior de tu código C#.

Ejemplos de código

Ejemplo de AnyBitmap

:path=/static-assets/drawing/content-code-examples/get-started/anybitmap.cs
using IronSoftware.Drawing;
using System.IO;
using System.Drawing;

// Create a new AnyBitmap object from a file
// Replace "FILE_PATH" with the actual path of the image you want to process
var bitmap = AnyBitmap.FromFile("FILE_PATH");

// Save the AnyBitmap object as a JPEG file
bitmap.SaveAs("result.jpg");

// Export the AnyBitmap as a byte array
// This can be useful if you want to send the image data over a network or save it in a database
var bytes = bitmap.ExportBytes();

// Create a memory stream to export the AnyBitmap as a JPEG stream with 100% quality
using (var resultExport = new MemoryStream())
{
    // This exports the image to the stream with the specified format and quality
    bitmap.ExportStream(resultExport, AnyBitmap.ImageFormat.Jpeg, 100);
    // Be sure to use 'using' or manually close the stream to release resources
}

// Casting between System.Drawing.Bitmap and IronSoftware.Drawing.AnyBitmap
// Load a System.Drawing.Bitmap from the same file
System.Drawing.Bitmap image = new System.Drawing.Bitmap("FILE_PATH");

// This is an implicit conversion from System.Drawing.Bitmap to IronSoftware.Drawing.AnyBitmap
// This step is necessary if you are working with System.Drawing.Bitmap and need to convert to IronSoftware.Drawing.AnyBitmap for processing
IronSoftware.Drawing.AnyBitmap anyBitmap = AnyBitmap.FromBitmap(image);

// Save the resulting AnyBitmap from casting as a PNG file
anyBitmap.SaveAs("result-from-casting.png");
Imports IronSoftware.Drawing
Imports System.IO
Imports System.Drawing

' Create a new AnyBitmap object from a file
' Replace "FILE_PATH" with the actual path of the image you want to process
Private bitmap = AnyBitmap.FromFile("FILE_PATH")

' Save the AnyBitmap object as a JPEG file
bitmap.SaveAs("result.jpg")

' Export the AnyBitmap as a byte array
' This can be useful if you want to send the image data over a network or save it in a database
Dim bytes = bitmap.ExportBytes()

' Create a memory stream to export the AnyBitmap as a JPEG stream with 100% quality
Using resultExport = New MemoryStream()
	' This exports the image to the stream with the specified format and quality
	bitmap.ExportStream(resultExport, AnyBitmap.ImageFormat.Jpeg, 100)
	' Be sure to use 'using' or manually close the stream to release resources
End Using

' Casting between System.Drawing.Bitmap and IronSoftware.Drawing.AnyBitmap
' Load a System.Drawing.Bitmap from the same file
Dim image As New System.Drawing.Bitmap("FILE_PATH")

' This is an implicit conversion from System.Drawing.Bitmap to IronSoftware.Drawing.AnyBitmap
' This step is necessary if you are working with System.Drawing.Bitmap and need to convert to IronSoftware.Drawing.AnyBitmap for processing
Dim anyBitmap As IronSoftware.Drawing.AnyBitmap = AnyBitmap.FromBitmap(image)

' Save the resulting AnyBitmap from casting as a PNG file
anyBitmap.SaveAs("result-from-casting.png")
$vbLabelText   $csharpLabel

Ejemplo de color

:path=/static-assets/drawing/content-code-examples/get-started/color.cs
using IronSoftware.Drawing;
using System;

// The IronSoftware.Drawing library provides enhanced color manipulation features.
// This example demonstrates creating color objects and converting between
// System.Drawing.Color and IronSoftware.Drawing.Color.

// Create a new Color object from a hex string.
Color fromHex = Color.FromHex("#191919");

// Create a new Color object from RGB values.
Color fromRgb = Color.FromRgb(255, 255, 0);

// Create a new Color object using an enumeration.
Color fromEnum = Color.Crimson;

// Casting between System.Drawing.Color and IronSoftware.Drawing.Color.
System.Drawing.Color drawingColor = System.Drawing.Color.Red;

// Convert System.Drawing.Color to IronSoftware.Drawing.Color.
IronSoftware.Drawing.Color ironColor = Color.FromSystemColor(drawingColor);

// Access the alpha, red, green, and blue components of the IronSoftware.Drawing.Color.
byte alpha = ironColor.A;
byte red = ironColor.R;
byte green = ironColor.G;
byte blue = ironColor.B;

// Calculate the luminance of the color.
// Luminance is a value from 0 (black) to 100 (white) where 50 is the perceptual "middle grey".
double luminance = ironColor.GetLuminance();

// Log the calculated attributes to the console.
Console.WriteLine($"Color Details - ARGB: ({alpha}, {red}, {green}, {blue}), Luminance: {luminance}");
Imports IronSoftware.Drawing
Imports System

' The IronSoftware.Drawing library provides enhanced color manipulation features.
' This example demonstrates creating color objects and converting between
' System.Drawing.Color and IronSoftware.Drawing.Color.

' Create a new Color object from a hex string.
Private fromHex As Color = Color.FromHex("#191919")

' Create a new Color object from RGB values.
Private fromRgb As Color = Color.FromRgb(255, 255, 0)

' Create a new Color object using an enumeration.
Private fromEnum As Color = Color.Crimson

' Casting between System.Drawing.Color and IronSoftware.Drawing.Color.
Private drawingColor As System.Drawing.Color = System.Drawing.Color.Red

' Convert System.Drawing.Color to IronSoftware.Drawing.Color.
Private ironColor As IronSoftware.Drawing.Color = Color.FromSystemColor(drawingColor)

' Access the alpha, red, green, and blue components of the IronSoftware.Drawing.Color.
Private alpha As Byte = ironColor.A
Private red As Byte = ironColor.R
Private green As Byte = ironColor.G
Private blue As Byte = ironColor.B

' Calculate the luminance of the color.
' Luminance is a value from 0 (black) to 100 (white) where 50 is the perceptual "middle grey".
Private luminance As Double = ironColor.GetLuminance()

' Log the calculated attributes to the console.
Console.WriteLine($"Color Details - ARGB: ({alpha}, {red}, {green}, {blue}), Luminance: {luminance}")
$vbLabelText   $csharpLabel

Ejemplo de rectángulo

:path=/static-assets/drawing/content-code-examples/get-started/rectangle.cs
using IronSoftware.Drawing;
using System.Drawing;

// Declare an IronSoftware.Drawing.Rectangle object
IronSoftware.Drawing.Rectangle ironRectangle = new IronSoftware.Drawing.Rectangle(5, 5, 50, 50);

// Declare a System.Drawing.Rectangle object
System.Drawing.Rectangle systemRectangle = new System.Drawing.Rectangle(10, 10, 150, 150);

// Implicitly convert System.Drawing.Rectangle to IronSoftware.Drawing.Rectangle
// Note: Uncomment and use appropriate conversion methods if available in the IronSoftware.Drawing library
// ironRectangle = (IronSoftware.Drawing.Rectangle)systemRectangle;

// Output the properties of IronSoftware.Drawing.Rectangle if conversion is successful
// These Console.WriteLine statements assume this code runs in a console environment
Console.WriteLine(ironRectangle.X);
Console.WriteLine(ironRectangle.Y);
Console.WriteLine(ironRectangle.Width);
Console.WriteLine(ironRectangle.Height);
Imports IronSoftware.Drawing
Imports System.Drawing

' Declare an IronSoftware.Drawing.Rectangle object
Private ironRectangle As New IronSoftware.Drawing.Rectangle(5, 5, 50, 50)

' Declare a System.Drawing.Rectangle object
Private systemRectangle As New System.Drawing.Rectangle(10, 10, 150, 150)

' Implicitly convert System.Drawing.Rectangle to IronSoftware.Drawing.Rectangle
' Note: Uncomment and use appropriate conversion methods if available in the IronSoftware.Drawing library
' ironRectangle = (IronSoftware.Drawing.Rectangle)systemRectangle;

' Output the properties of IronSoftware.Drawing.Rectangle if conversion is successful
' These Console.WriteLine statements assume this code runs in a console environment
Console.WriteLine(ironRectangle.X)
Console.WriteLine(ironRectangle.Y)
Console.WriteLine(ironRectangle.Width)
Console.WriteLine(ironRectangle.Height)
$vbLabelText   $csharpLabel

Ejemplo de fuente

:path=/static-assets/drawing/content-code-examples/get-started/font.cs
using System;
using System.Drawing;
using IronSoftware.Drawing;

// Create a new Font object with a specified font family, style, and size
IronSoftware.Drawing.Font font = new IronSoftware.Drawing.Font("Times New Roman", FontStyle.Italic | FontStyle.Bold, 30);

// Create a new instance of System.Drawing.Font
System.Drawing.Font drawingFont = new System.Drawing.Font("Courier New", 30);

try
{
    // Attempt to cast System.Drawing.Font to IronSoftware.Drawing.Font
    // Note: This cast may not be directly possible if the libraries do not support each other;
    // additional conversion logic might be required.
    IronSoftware.Drawing.Font ironFont = new IronSoftware.Drawing.Font(drawingFont.FontFamily.Name, drawingFont.Style, drawingFont.Size);

    // Accessing properties of the IronSoftware.Drawing.Font object
    string familyName = ironFont.FamilyName; // Get the font family name
    FontStyle style = ironFont.Style;       // Get the combined font style (italic, bold, etc.)
    float size = ironFont.Size;             // Get the font size
    bool isItalic = ironFont.Italic;        // Determine if the font style includes Italic
    bool isBold = ironFont.Bold;            // Determine if the font style includes Bold

    // Output the font properties to verify correctness
    Console.WriteLine($"Family: {familyName}, Style: {style}, Size: {size}, Italic: {isItalic}, Bold: {isBold}");
}
catch (InvalidCastException)
{
    Console.WriteLine("The conversion between System.Drawing.Font and IronSoftware.Drawing.Font is not directly supported.");
}
catch (Exception ex)
{
    Console.WriteLine($"An error occurred: {ex.Message}");
}
Imports System
Imports System.Drawing
Imports IronSoftware.Drawing

' Create a new Font object with a specified font family, style, and size
Private font As New IronSoftware.Drawing.Font("Times New Roman", FontStyle.Italic Or FontStyle.Bold, 30)

' Create a new instance of System.Drawing.Font
Private drawingFont As New System.Drawing.Font("Courier New", 30)

Try
	' Attempt to cast System.Drawing.Font to IronSoftware.Drawing.Font
	' Note: This cast may not be directly possible if the libraries do not support each other;
	' additional conversion logic might be required.
	Dim ironFont As New IronSoftware.Drawing.Font(drawingFont.FontFamily.Name, drawingFont.Style, drawingFont.Size)

	' Accessing properties of the IronSoftware.Drawing.Font object
	Dim familyName As String = ironFont.FamilyName ' Get the font family name
	Dim style As FontStyle = ironFont.Style ' Get the combined font style (italic, bold, etc.)
	Dim size As Single = ironFont.Size ' Get the font size
	Dim isItalic As Boolean = ironFont.Italic ' Determine if the font style includes Italic
	Dim isBold As Boolean = ironFont.Bold ' Determine if the font style includes Bold

	' Output the font properties to verify correctness
	Console.WriteLine($"Family: {familyName}, Style: {style}, Size: {size}, Italic: {isItalic}, Bold: {isBold}")
Catch e1 As InvalidCastException
	Console.WriteLine("The conversion between System.Drawing.Font and IronSoftware.Drawing.Font is not directly supported.")
Catch ex As Exception
	Console.WriteLine($"An error occurred: {ex.Message}")
End Try
$vbLabelText   $csharpLabel

Soporte disponible

Licencia

La información de la licencia se puede encontrar aquí: LICENSE.txt

Contribuir

Si deseas contribuir al proyecto de código abierto IronDrawing, por favor lee la licencia antes de realizar una solicitud de extracción en el repositorio en GitHub.

Información

Para más información sobre Iron Software, por favor visita nuestro sitio web: https://ironsoftware.com/

Soporte de Iron Software

Para soporte general e inquietudes técnicas, envíanos un correo electrónico a: mailto:support@ironsoftware.com

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Nuget Descargas 13,852,431 | Version: 2025.3 recién lanzado