Thursday, December 4, 2008

HIGHLIGHT STRING IN IMAGE [ DRAW STRING WITH HIGHLIGHT WORD ]

·

Bitmap b = new Bitmap(700, 100);
Graphics g = Graphics.FromImage((System.Drawing.Image)b);

string myString = "This is a string.My highlight word : search highlighted word.";

// Declare the word to highlight.
string searchWord = "search highlighted word";

// Create a CharacterRange array with the searchWord
// location and length.
CharacterRange[] CharRanges =
new CharacterRange[]{new CharacterRange
(myString.IndexOf(searchWord), searchWord.Length)};

// Construct a StringFormat object.
StringFormat stringFormat = new StringFormat();

// Set the ranges on the StringFormat object.
stringFormat.SetMeasurableCharacterRanges(CharRanges);

// Declare the font to write the message in.
Font MyFont = new Font(FontFamily.GenericSansSerif, 20.0F,
GraphicsUnit.Pixel);

// Construct a new Rectangle.
Rectangle MyRectangle = new Rectangle(10, 10, 700, 100);

// Convert the Rectangle to a RectangleF.
RectangleF MyRectangleF = (RectangleF)MyRectangle;

// Get the Region to highlight by calling the
// MeasureCharacterRanges method.
Region[] charRegion = g.MeasureCharacterRanges(myString,
MyFont, MyRectangleF, stringFormat);

// Draw the message string on the form.
g.DrawString(myString, MyFont, Brushes.Red,
MyRectangleF);

// Fill in the region using a semi-transparent color.
g.FillRegion(new SolidBrush(Color.FromArgb(50, Color.Black)),
charRegion[0]);

// save image to the root
b.Save(Server.MapPath("MyImage.png"), System.Drawing.Imaging.ImageFormat.Png);

// write image on the page
//MemoryStream m = new MemoryStream();
//b.Save(m, System.Drawing.Imaging.ImageFormat.Png);
//m.WriteTo(Response.OutputStream);
b.Dispose();
MyFont.Dispose();
g.Dispose();

0 comments: