Add watermark information to the image in ES0en.net and save as Jpg type

  • 2020-12-21 18:01:26
  • OfStack


using System.Drawing;
using System.IO;
using System.Drawing.Imaging;

private void AddTextToImg(string fileName,string text)
{
if(!File.Exists(MapPath(fileName)))
{
throw new FileNotFoundException("The file don't exist!");
}

if( text == string.Empty )
{
return;
}
// You also need to determine whether the file type is an image type, and I won't go into details here 

System.Drawing.Image image = System.Drawing.Image.FromFile(MapPath(fileName));
Bitmap bitmap = new Bitmap(image,image.Width,image.Height);
Graphics g = Graphics.FromImage(bitmap);

float fontSize = 12.0f; // The font size 
float textWidth = text.Length*fontSize; // Length of text 
// The following definitions 1 Rectangle area, and then draw black words on a white background in the rectangle 
float rectX = 0; 
float rectY = 0;
float rectWidth = text.Length*(fontSize+8);
float rectHeight = fontSize+8;
// Declare rectangular domain 
RectangleF textArea = new RectangleF(rectX,rectY,rectWidth,rectHeight);

Font font = new Font(" Song typeface ",fontSize); // Define the font 
Brush whiteBrush = new SolidBrush(Color.White); // Use a white brush to draw words 
Brush blackBrush = new SolidBrush(Color.Black); // Black brush for background 

g.FillRectangle(blackBrush,rectX,rectY,rectWidth,rectHeight); 

g.DrawString(text,font,whiteBrush,textArea);
MemoryStream ms = new MemoryStream( );
// Save as Jpg type 
bitmap.Save(ms,ImageFormat.Jpeg);

// Output the processed image, here for demonstration convenience, I will display the image in the page 
Response.Clear();
Response.ContentType = "image/jpeg";
Response.BinaryWrite( ms.ToArray() );

g.Dispose();
bitmap.Dispose();
image.Dispose();
}

When I call it, it's very simple,


AddTextToImg("me.jpg"," The program life http://www.manong123.com/");

1 cut OK, net is really powerful, these functions in Asp is a luxury, but in the.Net environment can be done easily!


Related articles: