Insérer un logo et un texte dans une image en .Net
Dans ce poste je vais expliquer comment insérer un logo et un texte dans une image. Ce principe est souvent utilisé a des fins de Copyright.
Résultat désiré:
Image de base :
Logo a insérer :
Texte a insérer :
Hello I am a text on this image
Code de la fonction :
///<summary> /// Setup th copyright ///</summary> ///<param name="fileName">The file name</param> public static void SetCopyright(string fileName) { // Dossier contenant les images string workingFolder = HttpContext.Current.Server.MapPath("~/Images"); Image image = Image.FromFile(workingFolder + "/Content/" + fileName); // Image principal Image logo = Image.FromFile(workingFolder + "/Copyright-Symbol.jpg"); // Logo a insérer string text = "Hello I am a text on this image"; // Texte a insérer Brush textColor = new SolidBrush(Color.FromArgb(255, 214, 65, 95)); // Couleur du texte (Peut-etre simplifié : Brushes.Orange;) Font textFont = new Font("Impact", 12, FontStyle.Bold); // Font family du texte Graphics gImage = Graphics.FromImage(image); // Création d'un objet de type graphic pour pouvoir insérer l'image et le texte float textWidth = gImage.MeasureString(text, textFont).Width; // Obtenir la taille du futur texte pour les calculs de positionnement Bitmap transparentLogo = new Bitmap(logo.Width, logo.Height); // Bitmap pour obtenir le logo transparent Graphics gLogo = Graphics.FromImage(transparentLogo); // Objet graphic pour permettre de dessiner ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.Matrix33 = 0.25F; // Le 3eme élément de la 4eme ligne de la matrice d'une image correspond a la transparence ImageAttributes imgAttributes = new ImageAttributes(); imgAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); // Application de la matrice // Insertion du logo dans l'image de base en haut a droite gLogo.DrawImage(logo, new Rectangle(0, 0, transparentLogo.Width, transparentLogo.Height), 0, 0, transparentLogo.Width, transparentLogo.Height, GraphicsUnit.Pixel, imgAttributes); gLogo.Dispose(); // Insertion du texte dans l'image de base en bas au centre gImage.DrawString(text, textFont, textColor, new PointF((image.Width - textWidth) / 2, image.Height - 20)); gImage.DrawImage(transparentLogo, image.Width - logo.Width, 0); // Sauvegarde (ici dans le dossier Content/Copyright) image.Save(workingFolder+ "/Content/copyright/" + fileName), ImageFormat.Jpeg); }