Bibliothèque de Bitmap C# pour remplacer System.Drawing.Common dans .NET

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

IronDrawing est gratuit, open-source et prend en charge la plupart des formats de bibliothèques de dessin .NET

IronDrawing est une bibliothèque open-source initialement développée par Iron Software qui aide les ingénieurs logiciels C# à remplacer System.Drawing.Common dans les projets .NET sur les plateformes Windows, macOS et Linux.

Développer des bibliothèques de classes et des packages NuGet pour .NET 5, 6, 7 et 8 qui supportent les graphiques, les images, et les polices devrait être facile.

IronDrawing agit comme un pont sans faille entre toutes les nouvelles normes graphiques proposées pour .NET 5, 6, 7 et 8 au fur et à mesure de leur évolution - vous n'avez donc besoin de développer que pour celle que vous préférez.

IronDrawing est gratuit, open-source et prend en charge la plupart des formats de bibliothèques de dessin .NET

Contexte

Microsoft .NET est un cadre logiciel multiplateforme et hautement compatible utilisé par des millions de développeurs de logiciels à travers le monde. Microsoft a annoncé un changement majeur dans lequel System.Drawing.Common ne sera pris en charge que sur les plateformes Windows.

C'est problématique pour les développeurs de bibliothèques .NET qui maintiennent des bibliothèques multi-plateformes utilisant System.Drawing.Common car l'action recommandée de Microsoft vous oblige à reconstruire votre bibliothèque pour prendre en charge les utilisateurs non-Windows. Il est prévu que les bénévoles et les universitaires reconstruisent chaque package NuGet et bibliothèque de classes pour utiliser chacune des nouvelles bibliothèques graphiques suggérées à mesure qu'elles émergent, créant une dette technique qui ralentira l'adoption de la modernité de .NET.

En fin de compte, lorsque nous utilisons .NET, nous utilisons NuGet.

Les développeurs de packages NuGet nous rendent service à tous en faisant progresser .NET et le code préemballé qui prendrait des milliers d'heures à écrire par nous-mêmes chaque jour.

Ce changement majeur ralentira le développement de NuGet et pourrait mener à l'abandon ou à l'obsolescence des bibliothèques de code sur lesquelles les développeurs .NET dépendent. Nous devons agir maintenant !

Notre Solution

Un format graphique intermédiaire qui convertit entre toutes les anciennes et nouvelles bibliothèques graphiques.

En tant que développeur de bibliothèque de classes, vos entrées et sorties publique Bitmap, Color, Rectangle, Font, et Size peuvent être d'un seul type qui supporte toutes les nouvelles normes. En interne, vous pouvez continuer à faire comme vous l'entendez.

IronDrawing est rétrocompatible avec .NET Framework 4.62, prend en charge toutes les versions de .NET (y compris .NET 8).

Le développement et la sortie d'IronDrawing résolvent ce problème en offrant une solution open-source à l'absence d'un format uniforme pour des classes importantes telles que Bitmap, Color, Rectangle, Font, et Size. IronSoftware.Drawing convertira sans problème entre les implémentations de ces types dans System.Drawing, Microsoft.Maui, SkiaSharp, et SixLabors pour vous. Cela vous permet, en tant que développeur, de ne pas avoir à remplacer toutes les instances de ces classes au sein de votre bibliothèque.

Par exemple, si vous utilisez System.Drawing.Bitmap, vous pouvez utiliser la classe AnyBitmap d'IronDrawing qui a des conversions implicites vers n'importe lequel de ces types : System.Drawing.Bitmap, System.Drawing.Image, SkiaSharp.SKBitmap, SkiaSharp.SKImage, SixLabors.ImageSharp, Microsoft.Maui.Graphics.Platform.PlatformImage.

Pourquoi faisons-nous cela gratuitement

Nous avons développé IronDrawing car nous, chez Iron Software, sommes des développeurs .NET seniors à long terme qui se soucient de l'évolution de .NET et voulons qu'il croisse et réussisse. Nous aimons voir que .NET grandit et évolue, comme on le voit avec .NET 7. Nous utilisons NuGet toute la journée, et je suis sûr que vous aussi. Nous soutenons et espérons encourager une transition facile vers l'avenir et loin de System.Drawing.

Nous voulons que tout le développement de bibliothèques de classes .NET et NuGet soit plus facile, pour que l'écosystème NuGet continue de prospérer, et pour que tous les développeurs .NET en bénéficient.

Fonctionnalités de IronSoftware.Drawing

  • AnyBitmap : Une classe Bitmap universellement compatible. Conversion implicite entre IronSoftware.Drawing.AnyBitmap et les suivants pris en charge :
  • System.Drawing.Bitmap
  • System.Drawing.Image
  • SkiaSharp.SKBitmap
  • SkiaSharp.SKImage
  • SixLabors.ImageSharp
  • Microsoft.Maui.Graphics.Platform.PlatformImage
  • Color : Une classe Color universellement compatible. Conversion implicite entre IronSoftware.Drawing.Color et les suivants pris en charge :
  • System.Drawing.Color
  • SkiaSharp.SKColor
  • SixLabors.ImageSharp.Color
  • SixLabors.ImageSharp.PixelFormats
  • Rectangle : Une classe Rectangle universellement compatible. Conversion implicite entre IronSoftware.Drawing.Rectangle et les suivants pris en charge :
  • System.Drawing.Rectangle
  • SkiaSharp.SKRect
  • SkiaSharp.SKRectI
  • SixLabors.ImageSharp.Rectangle
  • Font : Une classe Font universellement compatible. Conversion implicite entre IronSoftware.Drawing.Font et les suivants pris en charge :
  • System.Drawing.Font
  • SkiaSharp.SKFont
  • SixLabors.Fonts.Font

Compatibilité

IronSoftware.Drawing a une compatibilité multiplateforme avec :

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

Installation

Installer le package NuGet IronDrawing (IronSoftware.Drawing) est rapide et facile. Veuillez installer le package comme ceci :

Install-Package IronSoftware.System.Drawing

Sinon, téléchargez directement depuis le site NuGet officiel.

Une fois installé, vous pouvez commencer en ajoutant using IronSoftware.Drawing; en haut de votre code C#.

Exemples de Code

Exemple 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

Exemple de Couleur

: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

Exemple de Rectangle

: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

Exemple de Police

: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

Support Disponible

Licence

Les informations de licence se trouvent ici : LICENSE.txt

Contribuer

Si vous souhaitez contribuer au projet open-source IronDrawing, veuillez lire la licence avant de faire une demande de fusion sur le dépôt sur GitHub.

Informations

Pour plus d'informations sur Iron Software veuillez visiter notre site web : https://ironsoftware.com/

Soutien d'Iron Software

Pour un support général et des questions techniques, veuillez nous envoyer un email à : mailto:support@ironsoftware.com

Curtis Chau
Rédacteur technique

Curtis Chau détient un baccalauréat en informatique (Université de Carleton) et se spécialise dans le développement front-end avec expertise en Node.js, TypeScript, JavaScript et React. Passionné par la création d'interfaces utilisateur intuitives et esthétiquement plaisantes, Curtis aime travailler avec des frameworks modernes ...

Lire la suite
Prêt à commencer?
Nuget Téléchargements 13,852,431 | Version: 2025.3 vient de sortir