private void ResimOlustur(int genislik, int yukseklik) { Bitmap bitmap = new Bitmap(genislik, yukseklik, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(bitmap); g.SmoothingMode = SmoothingMode.AntiAlias; Rectangle rect = new Rectangle(0, 0, genislik, yukseklik); HatchBrush hatchBrush = new HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.White); g.FillRectangle(hatchBrush, rect); SizeF size; float fontSize = rect.Height + 1; Font font; do { fontSize--; font = new Font(System.Drawing.FontFamily.GenericSerif.Name, fontSize, FontStyle.Bold); size = g.MeasureString(this.text, font); } while (size.Width > rect.Width); StringFormat format = new StringFormat(); format.Alignment = StringAlignment.Center; format.LineAlignment = StringAlignment.Center; GraphicsPath path = new GraphicsPath(); path.AddString(this.text, font.FontFamily, (int)font.Style, font.Size, rect, format); float v = 4F; PointF[] points = { new PointF(this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v), new PointF(rect.Width - this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v), new PointF(this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v), new PointF(rect.Width - this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v) }; Matrix matrix = new Matrix(); matrix.Translate(0F, 0F); path.Warp(points, rect, matrix, WarpMode.Perspective, 0F); hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.LightGray, Color.DarkGray); g.FillPath(hatchBrush, path); int m = Math.Max(rect.Width, rect.Height); for (int i = 0; i < (int)(rect.Width * rect.Height / 30F); i++) { int x = this.random.Next(rect.Width); int y = this.random.Next(rect.Height); int w = this.random.Next(m / 50); int h = this.random.Next(m / 50); g.FillEllipse(hatchBrush, x, y, w, h); } font.Dispose(); hatchBrush.Dispose(); g.Dispose(); this.Image = bitmap; }
/// <summary> /// this version outputs gif to web page /// ProcessRequest is intrinsic function of hppthandler, do not change the name /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { //for a custom httphandler make sure it's referenced in web.config in httpHandlers //<add verb="GET" path="*barcode.gif" type="barcode_handler" validate ="false" /> // if(context.Request["code"] != null){ string _code = wwi_security.DecryptString(context.Request["code"].ToString(),"publiship"); //code to use int _wd = 120; //context.Request["wd"] != null ? wwi_func.vint(context.Request["wd"].ToString()) : 120; //width int _ht = 30; //context.Request["ht"] != null ? wwi_func.vint(context.Request["ht"].ToString()) : 30; //height Barcode128 _bc = new Barcode128(); _bc.CodeType = Barcode.CODE128; _bc.ChecksumText = true; _bc.GenerateChecksum = true; _bc.Code = _code; //draws directly to web page with no code underneath bar //System.Drawing.Bitmap _bm = new System.Drawing.Bitmap(_bc.CreateDrawingImage(System.Drawing.Color.Black, System.Drawing.Color.White)); //_bm.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif); //draws with actual code underneath bar //create bitmap from System.Drawing library, add some height for actual code underneath Bitmap _bm = new Bitmap(_wd, _ht + 10); //provide this, else the background will be black by default Graphics _gr = Graphics.FromImage(_bm); _gr.PageUnit = GraphicsUnit.Pixel; _gr.Clear(Color.White); //draw the barcode _gr.DrawImage(_bc.CreateDrawingImage(Color.Black, System.Drawing.Color.White), new Point(0,0)); //place text underneath - if you want the placement to be dynamic, calculate the point based on size of the image System.Drawing.Font _ft = new System.Drawing.Font("Arial", 8, FontStyle.Regular); SizeF _sz = _gr.MeasureString(_code, _ft); //position text _wd = (_wd - (int)_sz.Width) / 2; StringFormat _sf = new StringFormat(); _sf.Alignment = StringAlignment.Center; _sf.LineAlignment = StringAlignment.Center; _gr.DrawString(_code, _ft, SystemBrushes.WindowText,_wd,_ht, _sf); //output as gif to web page, can also save it to external file _bm.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif); }//end if }
/// <summary> /// Returns <paramref name="data"/> decrypted based on encryption original <paramref name="stringFormat"/>, <paramref name="key"/> and <paramref name="encryptionProvider"/>. /// </summary> public static string Decrypt(string data, string key, EncryptionProvider encryptionProvider, StringFormat stringFormat) { Argument.IsNotNull(data, "data"); Argument.IsNotNull(key, "key"); var encryptionAlgorithm = GetEncryptionAlgorithm(encryptionProvider); var dataBytes = Util.StringToBytes(data, stringFormat, defaultEncoding).ToArray(); encryptionAlgorithm.Key = CreateCryptoKey(encryptionAlgorithm, key); encryptionAlgorithm.IV = CreateCryptoIv(encryptionAlgorithm, DefaultInitializationVector); var result = new byte[dataBytes.Length]; using (var ms = new MemoryStream(dataBytes, 0, dataBytes.Length)) { using (var cs = new CryptoStream(ms, encryptionAlgorithm.CreateDecryptor(), CryptoStreamMode.Read)) { cs.Read(result, 0, dataBytes.Length); } } // Clean trailing zeros. result = Util.CleanBytes(result).ToArray(); return Util.BytesToTextString(result, defaultEncoding); }
protected void Page_Load(object sender, EventArgs e) { Response.ContentType = "image/jpeg"; Response.Clear(); string s = DLL.SessionFacade.ConfirmCode; Font f = new Font("Times New Roman", 26, FontStyle.Italic | FontStyle.Bold, GraphicsUnit.Pixel); StringFormat format = new StringFormat(); format.Alignment = StringAlignment.Center; format.LineAlignment = StringAlignment.Center; Bitmap bmp = new Bitmap(110, 40, System.Drawing.Imaging.PixelFormat.Format24bppRgb); Graphics g = Graphics.FromImage(bmp); g.Clear(Color.White); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; g.DrawString(s, f, Brushes.Black, new RectangleF(0, 0, bmp.Width, bmp.Height), format); /* for (int i = -2; i < bmp.Width / 10; i++) { g.DrawLine(Pens.OrangeRed, i * 10, 0, i * 10 + 20, bmp.Height); } for (int i = -2; i < bmp.Width / 10 + 10; i++) { g.DrawLine(Pens.Blue, i * 10, 0, i * 10 - 60, bmp.Height); } */ g.Dispose(); bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); }
protected override void ApplyTextWatermark(ImageProcessingActionExecuteArgs args, Graphics g) { // Draw a filled rectangle int rectangleWidth = 14; using (Brush brush = new SolidBrush(Color.FromArgb(220, Color.Red))) { g.FillRectangle(brush, new Rectangle(args.Image.Size.Width - rectangleWidth, 0, rectangleWidth, args.Image.Size.Height)); } using (System.Drawing.Drawing2D.Matrix transform = g.Transform) { using (StringFormat stringFormat = new StringFormat()) { // Vertical text (bottom -> top) stringFormat.FormatFlags = StringFormatFlags.DirectionVertical; transform.RotateAt(180F, new PointF(args.Image.Size.Width / 2, args.Image.Size.Height / 2)); g.Transform = transform; // Align: top left, +2px displacement // (because of the matrix transformation we have to use inverted values) base.ContentAlignment = ContentAlignment.MiddleLeft; base.ContentDisplacement = new Point(-2, -2); base.ForeColor = Color.White; base.Font.Size = 10; // Draw the string by invoking the base Apply method base.StringFormat = stringFormat; base.ApplyTextWatermark(args, g); base.StringFormat = null; } } }
protected void Page_Load(object sender, EventArgs e) { string monthString = Request.QueryString["Month"]; if (String.IsNullOrEmpty(monthString)) { monthString = "201004"; } int year = Int32.Parse(monthString.Substring(0, 4)); int month = Int32.Parse(monthString.Substring(4)); // never mind input checking Organization organization = Organization.PPSE; monthString = new DateTime(year, month, 1).ToString("MMMM yyyy", new CultureInfo("sv-SE")); SalaryTaxData data = GetSalaryData(year, month, organization); Response.ContentType = "image/jpeg"; Image form = Image.FromFile(MapPath("/Data/ImageTemplates/salarytaxes-se.png")); using (Graphics graphics = Graphics.FromImage(form)) { StringFormat rightAlign = new StringFormat(); rightAlign.Alignment = StringAlignment.Far; Font fontHandwriting = new Font("Courier New", 64, FontStyle.Bold); Font fontPreprinted = new Font("Courier New", 30, FontStyle.Bold); Brush brushHandwriting = Brushes.Blue; Brush brushPreprinted = Brushes.Red; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.DrawString(organization.Name, fontPreprinted, brushPreprinted, 150, 170); graphics.DrawString(monthString, fontPreprinted, brushPreprinted, 680, 292); graphics.DrawString(monthString, fontPreprinted, brushPreprinted, 620, 1460); graphics.DrawString(String.Format("{0,4}-{1:D2}-{2:D2}", year, month+1, 12), fontPreprinted, brushPreprinted, 820, 160); graphics.DrawString("802430-4514", fontPreprinted, brushPreprinted, 1110, 160); graphics.DrawString(data.SalaryTotal.ToString("F0"), fontHandwriting, brushHandwriting, 792, 358, rightAlign); // Salary total sub graphics.DrawString(data.SalaryTotal.ToString("F0"), fontHandwriting, brushHandwriting, 792, 558, rightAlign); // Salary total total graphics.DrawString(data.SalaryMain.ToString("F0"), fontHandwriting, brushHandwriting, 792, 692, rightAlign); // Salary age main graphics.DrawString(data.SalaryTotal.ToString("F0"), fontHandwriting, brushHandwriting, 792, 1524, rightAlign); // Salary total again graphics.DrawString(data.SalaryTotal.ToString("F0"), fontHandwriting, brushHandwriting, 792, 1725, rightAlign); // Salary total again graphics.DrawString(data.TaxAdditiveMain.ToString("F0"), fontHandwriting, brushHandwriting, 1510, 692, rightAlign); // Emp fee main graphics.DrawString(data.TaxAdditiveTotal.ToString("F0"), fontHandwriting, brushHandwriting, 1510, 1326, rightAlign); // Emp fee total graphics.DrawString(data.TaxSubtractive.ToString("F0"), fontHandwriting, brushHandwriting, 1510, 1525, rightAlign); // Deducted main graphics.DrawString(data.TaxSubtractive.ToString("F0"), fontHandwriting, brushHandwriting, 1510, 1726, rightAlign); // Deducted total graphics.DrawString(data.TaxTotal.ToString("F0"), fontHandwriting, brushHandwriting, 1510, 1793, rightAlign); // Tax cost total } using (Stream responseStream = Response.OutputStream) { form.Save(responseStream, ImageFormat.Jpeg); } }
protected void Page_Load(object sender, EventArgs e) { // Since we are outputting a Jpeg, set the ContentType appropriately Response.ContentType = "image/jpeg"; // Create a Bitmap instance that's 468x60, and a Graphics instance const int width = 480, height = 270; Bitmap objBitmap = new Bitmap(width, height); Graphics objGraphics = Graphics.FromImage(objBitmap); // Create a white background objGraphics.FillRectangle(new SolidBrush(Color.White), 0, 0, width, height); objGraphics.DrawRectangle(new Pen(Color.Black, 1), 0, 0, width - 1, height - 1); //// Create a LightBlue background //objGraphics.FillRectangle(new SolidBrush(Color.LightBlue), 5, 5, // width - 10, height - 10); //// Create the advertising pitch Font fontBanner = new Font("Verdana", 10, FontStyle.Regular); StringFormat stringFormat = new StringFormat(); //// center align the advertising pitch stringFormat.Alignment = StringAlignment.Center; stringFormat.LineAlignment = StringAlignment.Center; String label = "Chart for: " + PersonInfo.SelectedRecord.Name.ToString(); objGraphics.DrawString(label, fontBanner, new SolidBrush(Color.Black), new Rectangle(0, 0, width, height/10), stringFormat); // Save the image to the OutputStream objBitmap.Save(Response.OutputStream, ImageFormat.Jpeg); // clean up... objGraphics.Dispose(); objBitmap.Dispose(); }
/// <summary> /// Returns <paramref name="data"/> encrypted in target <paramref name="stringFormat"/> based on <paramref name="key"/> and <paramref name="encryptionProvider"/>. /// </summary> public static string Encrypt(string data, string key, EncryptionProvider encryptionProvider, StringFormat stringFormat) { Argument.IsNotNull(data, "data"); Argument.IsNotNull(key, "key"); var encryptionAlgorithm = GetEncryptionAlgorithm(encryptionProvider); var dataBytes = defaultEncoding.GetBytes(data); encryptionAlgorithm.Key = CreateCryptoKey(encryptionAlgorithm, key); encryptionAlgorithm.IV = CreateCryptoIv(encryptionAlgorithm, DefaultInitializationVector); string result; using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, encryptionAlgorithm.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(dataBytes, 0, dataBytes.Length); } result = Util.BytesToString(ms.ToArray(), stringFormat); } return result; }
protected void Page_Load(object sender, EventArgs e) { string referenceString = Request.QueryString["Reference"]; string cultureString = Request.QueryString["Culture"]; cultureString = cultureString.Substring(0, 2).ToLowerInvariant() + "-" + cultureString.Substring(2).ToUpperInvariant(); CultureInfo culture = new CultureInfo(cultureString); OutboundInvoice invoice = OutboundInvoice.FromReference(referenceString); Organization organization = invoice.Organization; Response.ContentType = "image/jpeg"; Image form = Image.FromFile(MapPath("~/Data/ImageTemplates/PPSE-invoice-" + culture + ".png")); using (Graphics graphics = Graphics.FromImage(form)) { StringFormat rightAlign = new StringFormat(); rightAlign.Alignment = StringAlignment.Far; Font fontLarge = new Font("Liberation Mono", 12, FontStyle.Bold); Font fontMedium = new Font("Liberation Mono", 10, FontStyle.Bold); Font fontNormal = new Font("Liberation Mono", 10, FontStyle.Regular); Brush brushPrint = Brushes.Blue; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.DrawString(invoice.Amount.ToString("N2", culture), fontLarge, brushPrint, 650, 378); graphics.DrawString(invoice.DueDate.ToShortDateString(), fontLarge, brushPrint, 650, 445); graphics.DrawString(invoice.Reference, fontLarge, brushPrint, 650, 512); graphics.DrawString(invoice.TheirReference, fontMedium, brushPrint, 650, 657); graphics.DrawString(invoice.CustomerName, fontMedium, brushPrint, 1500, 378); graphics.DrawString(invoice.InvoiceAddressPaper, fontNormal, brushPrint, 1500, 430); int yPos = 960; foreach (OutboundInvoiceItem item in invoice.Items) { graphics.DrawString(item.Description, fontNormal, brushPrint, 104, yPos); graphics.DrawString(item.Amount.ToString("N2", culture), fontNormal, brushPrint, 2333, yPos, rightAlign); yPos += 60; } graphics.DrawString(invoice.Amount.ToString("N2", culture), fontMedium, brushPrint, 2333, 2940, rightAlign); } using (Stream responseStream = Response.OutputStream) { form.Save(responseStream, ImageFormat.Jpeg); } }
public StringFormat(StringFormat format) { if (format == null) throw new ArgumentNullException ("format"); Alignment = format.Alignment; LineAlignment = format.LineAlignment; FormatFlags = format.FormatFlags; }
protected override void OnPaint(PaintEventArgs pea) { Graphics grfx = pea.Graphics; StringFormat strfmt = new StringFormat(); strfmt.Alignment = strfmt.LineAlignment = StringAlignment.Center; grfx.DrawString("Click to print", Font, new SolidBrush(ForeColor), ClientRectangle, strfmt); }
private void Button_Click(object sender, RoutedEventArgs e) { // get stream to save to var dlg = new SaveFileDialog(); dlg.DefaultExt = ".pdf"; var dr = dlg.ShowDialog(); if (!dr.HasValue || !dr.Value) { return; } // get sender button var btn = sender as Button; // create document var pdf = new C1PdfDocument(PaperKind.Letter); pdf.Clear(); // set document info var di = pdf.DocumentInfo; di.Author = "ComponentOne"; di.Subject = "C1.WPF.Pdf demo."; di.Title = "Experimental VisualTree Exporter for PDF"; // walk visual tree CreateDocumentVisualTree(pdf, content); // render footers // this reopens each page and adds content to them (now we know the page count). var font = new Font("Arial", 8, PdfFontStyle.Bold); var fmt = new StringFormat(); fmt.Alignment = HorizontalAlignment.Right; fmt.LineAlignment = VerticalAlignment.Bottom; for (int page = 0; page < pdf.Pages.Count; page++) { pdf.CurrentPage = page; var text = string.Format("C1.WPF.Pdf: {0}, page {1} of {2}", di.Title, page + 1, pdf.Pages.Count); pdf.DrawString( text, font, Colors.DarkGray, PdfUtils.Inflate(pdf.PageRectangle, -72, -36), fmt); } // save document using (var stream = dlg.OpenFile()) { pdf.Save(stream); } MessageBox.Show("Pdf Document saved to " + dlg.SafeFileName); }
internal TextLineIterator(string s, Font font, font.FontRenderContext frc, StringFormat format, float width, float height) { _format = (format != null) ? format : new StringFormat(); _font = font; _s = (s != null) ? s : String.Empty; _frc = frc; FontFamily ff = font.FontFamily; _margin = font.Size*ff.GetDrawMargin(font.Style)/ff.GetEmHeight(font.Style); _width = width; _height = height; }
void MainForm_Paint (object o, PaintEventArgs args) { StringFormat format = new StringFormat (); format.Alignment = StringAlignment.Center; string text = "this is really long text........................................... with a lot o periods."; SizeF sz = args.Graphics.MeasureString (text, Font, 80, format); Rectangle bounds = new Rectangle (60, 8, 80, 80); args.Graphics.DrawString (text, Font, SystemBrushes.ControlText, bounds, format); bounds.Height = (int) sz.Height; args.Graphics.DrawRectangle (new Pen (Color.Black), bounds); }
protected override void OnPaint (PaintEventArgs args) { Graphics g = args.Graphics; SolidBrush brush = new SolidBrush (ForeColor); StringFormat sformat = new StringFormat (); sformat.FormatFlags = StringFormatFlags.LineLimit; g.DrawString ("WeShouldIncludeWhiteSpaces", Font, brush, new Rectangle (0, 0, 55, 100), sformat); brush.Dispose (); sformat.Dispose (); }
internal static string BytesToString(IEnumerable<byte> value, StringFormat stringFormat, Encoding encoding) { switch (stringFormat) { case StringFormat.Base64: return BytesToBase64String(value); case StringFormat.Hex: return BytesToHexString(value); default: return BytesToTextString(value, encoding); } }
internal static IEnumerable<byte> StringToBytes(string input, StringFormat stringFormat, Encoding encoding) { switch (stringFormat) { case StringFormat.Base64: return Base64ToBytes(input); case StringFormat.Hex: return HexToBytes(input); default: return TextToBytes(input, encoding); } }
public static string ConvertToDate(string dateValue, StringFormat stringFormat) { switch (stringFormat) { case StringFormat.yyyyMMdd: return String.Format(" CONVERT(datetime, '{0}', 112) ", dateValue); case StringFormat.ddMMyyyy: break; default: break; } return ""; }
/// <summary> /// /// </summary> /// <param name="format"></param> /// <returns></returns> public static StringSerializer GetStringSerializer(StringFormat format) { switch (format) { case StringFormat.Xml: return new XmlSerializer(); case StringFormat.Json: return new JsonSerializer(); case StringFormat.Bibtex: return new BibtexSerializer(); default: throw new Exception(format + " format not supported"); } }
/// <summary> /// Convert a known string format to a series of bytes /// </summary> /// <param name="value">String that will be converted</param> /// <param name="inputFormat">Known format of string</param> /// <returns>Bytes as discovered by format</returns> public static byte[] ToBytes(string value, StringFormat inputFormat) { switch (inputFormat) { case StringFormat.Base64: return Convert.FromBase64String(value); case StringFormat.Hex: return Transform.HexStringToBytes(value); case StringFormat.Unicode: return Transform.StringToBytes(value); default: throw ExceptionFactory.New<InvalidOperationException>("'{0}' is an unknown string format", inputFormat.ToString()); } }
/// <summary> /// Convert a series of bytes into a known format. These are generally lightweight wrappers around known .net functions /// </summary> /// <param name="source">non-null hydrated bytes to convert into a string type</param> /// <param name="outputFormat">How string will represent bytes of data</param> /// <returns>Byte values converted into a known formatted string</returns> public static string FromBytes(byte[] source, StringFormat outputFormat) { switch (outputFormat) { case StringFormat.Base64: return Convert.ToBase64String(source); case StringFormat.Hex: return Transform.BytesToHexString(source); case StringFormat.Unicode: return Transform.StringFromBytes(source); default: throw ExceptionFactory.New<InvalidOperationException>("'{0}' is an unknown string format", outputFormat.ToString()); } }
public static AttributeMetadata CreateText(int? maxLength = null, StringFormat? format = StringFormat.Text, StringFormatName formatName = null, ImeMode? imeMode = ImeMode.Auto, string yomiOf = null, string formulaDefinition = null) { maxLength = formulaDefinition != null && maxLength == null ? 4000 : 100; if (formatName == null) { switch (format) { case StringFormat.Email: formatName = StringFormatName.Email; break; case StringFormat.Text: formatName = StringFormatName.Text; break; case StringFormat.TextArea: formatName = StringFormatName.TextArea; break; case StringFormat.Url: formatName = StringFormatName.Url; break; case StringFormat.TickerSymbol: formatName = StringFormatName.TickerSymbol; break; case StringFormat.PhoneticGuide: formatName = StringFormatName.PhoneticGuide; break; case StringFormat.VersionNumber: formatName = StringFormatName.VersionNumber; break; case StringFormat.Phone: formatName = StringFormatName.Url; break; case null: break; default: throw new ArgumentOutOfRangeException(nameof(format), format, "Unable to determine format Name for format: " + format); } } return new StringAttributeMetadata { Format = format, FormatName = formatName, ImeMode = imeMode, MaxLength = maxLength, YomiOf = yomiOf, FormulaDefinition = formulaDefinition }; }
protected void drawByStringFormat(Graphics graphics) { Rectangle cr = this.ClientRectangle; Brush brush = new SolidBrush(this.ForeColor); graphics.DrawString("�»��", this.Font, brush, cr.Left, cr.Top); StringFormat sf = new StringFormat(); sf.Alignment = StringAlignment.Far; sf.LineAlignment = StringAlignment.Far; graphics.DrawString("���ϴ�", this.Font, brush, cr.Right, cr.Bottom, sf); sf.Alignment = StringAlignment.Center; sf.LineAlignment = StringAlignment.Center; graphics.DrawString("��Ȯ�� �߾�?", this.Font, brush, cr.X + cr.Width/2, cr.Y+cr.Height/2, sf); }
public EntityAttributeMetadataBuilder StringAttribute(string schemaName, string displayName, string description, AttributeRequiredLevel requiredLevel, int maxLength, StringFormat format) { // Define the primary attribute for the entity var newAtt = new StringAttributeMetadata { SchemaName = schemaName, RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel), MaxLength = maxLength, Format = format, DisplayName = new Label(displayName, 1033), Description = new Label(description, 1033) }; this.Attributes.Add(newAtt); return this; }
public override void DrawColLabel(System.Drawing.Graphics g, System.Drawing.Rectangle rect, string sDay) { StringFormat m_Format = new StringFormat(); m_Format.Alignment = StringAlignment.Center; m_Format.FormatFlags = StringFormatFlags.NoWrap; m_Format.LineAlignment = StringAlignment.Center; if(HasVerticalLine) { using (Pen aPen = new Pen(HeaderTitleSplitLineColor)) g.DrawLine(aPen, rect.Right, rect.Top, rect.Right, rect.Bottom); } rect.Offset(2, 1); g.DrawString(sDay, HeaderTitleFont, SystemBrushes.WindowText, rect, m_Format); }
public static void Run() { // ExStart:AddDiagonalWatermarkToImage // The path to the documents directory. string dataDir = RunExamples.GetDataDir_ModifyingAndConvertingImages(); // Load an existing JPG image using (Image image = Image.Load(dataDir + "SampleTiff1.tiff")) { // Declare a String object with Watermark Text string theString = "45 Degree Rotated Text"; // Create and initialize an instance of Graphics class and Initialize an object of SizeF to store image Size Graphics graphics = new Graphics(image); SizeF sz = graphics.Image.Size; // Creates an instance of Font, initialize it with Font Face, Size and Style Font font = new Font("Times New Roman", 20, FontStyle.Bold); // Create an instance of SolidBrush and set its various properties SolidBrush brush = new SolidBrush(); brush.Color = Color.Red; brush.Opacity = 0; // Initialize an object of StringFormat class and set its various properties StringFormat format = new StringFormat(); format.Alignment = StringAlignment.Center; format.FormatFlags = StringFormatFlags.MeasureTrailingSpaces; // Create an object of Matrix class for transformation Matrix matrix = new Matrix(); // First a translation then a rotation matrix.Translate(sz.Width / 2, sz.Height / 2); matrix.Rotate(-45.0f); // Set the Transformation through Matrix graphics.Transform = matrix; // Draw the string on Image Save output to disk graphics.DrawString(theString, font, brush, 0, 0, format); image.Save(dataDir + "AddDiagonalWatermarkToImage_out.jpg"); } // ExStart:AddDiagonalWatermarkToImage }
private void drawFooter(PrintPageEventArgs e) { var pageWidth = _printDocument.DefaultPageSettings.PaperSize.Width; _pageNumber++; string PageString = "Page " + _pageNumber.ToString(); StringFormat PageStringFormat = new StringFormat(); PageStringFormat.Trimming = StringTrimming.Word; PageStringFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip; PageStringFormat.Alignment = StringAlignment.Far; Font PageStringFont = new Font("Ariel", 8, FontStyle.Regular, GraphicsUnit.Point); RectangleF PageStringRectangle = new RectangleF((float)e.MarginBounds.Right, e.MarginBounds.Bottom, (float)pageWidth - (float)e.MarginBounds.Right - (float)e.MarginBounds.Left, e.Graphics.MeasureString(PageString, PageStringFont).Height); e.Graphics.DrawString(PageString, PageStringFont, new SolidBrush(Color.Black), PageStringRectangle, PageStringFormat); }
public void Createimage( string text ,string number) { string Text = text; Color FontColor = Color.Black; Color BackColor = Color.Transparent; String FontName = "Times New Roman"; int FontSize = 12; int Height = 20; int Width = 100; ////STEP 2 - Create a Bitmap Object to Hold The Image Bitmap bitmap = new Bitmap(Width, Height); ////STEP 3 - Create a Graphics object using this Bitmap object Graphics graphics = Graphics.FromImage(bitmap); //STEP 4 - Create Color, Font, and PointF objects. Color color = Color.Transparent; ; Font font = new Font(FontName, FontSize); //define where the text will be displayed in the specified area of the image PointF point = new PointF(5.0F, 5.0F); //STEP 5 - Create Brushes and Pen SolidBrush BrushForeColor = new SolidBrush(FontColor); SolidBrush BrushBackColor = new SolidBrush(BackColor); Pen BorderPen = new Pen(color); //STEP 6 - Draw Rectangle using Graphics object Rectangle displayRectangle = new Rectangle(new Point(0, 0), new Size(Width - 1, Height - 1)); graphics.FillRectangle(BrushBackColor, displayRectangle); graphics.DrawRectangle(BorderPen, displayRectangle); //STEP 7 - Draw Text string on the specified rectangle using Graphics object //Define string format StringFormat format1 = new StringFormat(StringFormatFlags.NoClip); StringFormat format2 = new StringFormat(format1); //Draw text string using the text format graphics.DrawString(Text, font, Brushes.Black, (RectangleF)displayRectangle, format2); //STEP 8 - Send the bitmap to page output stream in JPEG format bitmap.Save( Server.MapPath(@"/")+"PraNKMSG"+ number+".JPG"); }
protected void ProcessImage() { // Setup the source file name and the output file name string sourceImageFileName = this.imgSource.ImageUrl; string outputImageFileName = "~/repository/output/Ex_A_223.jpg"; TextWatermark textWatermark = new TextWatermark(); textWatermark.Text = this.txtText.Text; textWatermark.ContentAlignment = (ContentAlignment)Enum.Parse(typeof(ContentAlignment), this.ddlContentAlignment.SelectedValue); textWatermark.Unit = (GfxUnit)Enum.Parse(typeof(GfxUnit), this.ddlMainUnit.SelectedValue); textWatermark.ContentDisplacement = new Point(int.Parse(this.ddlContentDisplacementX.SelectedValue, CultureInfo.InvariantCulture), int.Parse(this.ddlContentDisplacementY.SelectedValue, CultureInfo.InvariantCulture)); textWatermark.ForeColor = Color.FromArgb(int.Parse(this.ddlForeColorAlpha.SelectedValue, CultureInfo.InvariantCulture), ColorTranslator.FromHtml(this.txtForeColor.Text)); textWatermark.Font.Name = this.ddlFontName.SelectedValue; textWatermark.Font.Size = float.Parse(this.ddlFontSize.SelectedValue, CultureInfo.InvariantCulture); textWatermark.Font.Bold = this.cbFontBold.Checked; textWatermark.Font.Italic = this.cbFontItalic.Checked; textWatermark.Font.Underline = this.cbFontUnderline.Checked; textWatermark.Font.Strikeout = this.cbFontStrikeout.Checked; textWatermark.TextRenderingHint = (System.Drawing.Text.TextRenderingHint)Enum.Parse(typeof(System.Drawing.Text.TextRenderingHint), this.ddlTextRenderingHint.SelectedValue); textWatermark.TextContrast = int.Parse(this.ddlTextContrast.SelectedValue, CultureInfo.InvariantCulture); using (StringFormat stringFormat = new StringFormat()) { // Setup the string format parameters if (this.cbStringFormatFlags_DirectionVertical.Checked) { stringFormat.FormatFlags |= StringFormatFlags.DirectionVertical; } textWatermark.StringFormat = stringFormat; // Process the image textWatermark.SaveProcessedImageToFileSystem(sourceImageFileName, outputImageFileName); } // Update the displayed image (add a timestamp parameter to the query URL to ensure that the image is reloaded by the browser) this.imgOutput.ImageUrl = outputImageFileName + "?timestamp=" + DateTime.UtcNow.Ticks.ToString(); // Display the generated image this.phOutputContainer.Visible = true; }
public EntityAttributeMetadataBuilder BooleanAttribute(string schemaName, AttributeRequiredLevel requiredLevel, int maxLength, StringFormat format, string displayName, string description) { int languageCode = 1033; // Create a boolean attribute var boolAttribute = new BooleanAttributeMetadata { // Set base properties SchemaName = schemaName, DisplayName = new Label(displayName, languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(requiredLevel), Description = new Label(description, languageCode), // Set extended properties OptionSet = new BooleanOptionSetMetadata( new OptionMetadata(new Label("True", languageCode), 1), new OptionMetadata(new Label("False", languageCode), 0) ) }; this.Attributes.Add(boolAttribute); return this; }
private static string captcha_generator(string captcha_data) { try { captcha_data = captcha_data.ToUpper(); const int iHeight = 100; const int iWidth = 350; var oRandom = new Random(); int[] aFontEmSizes = { 40, 45 }; string[] aFontNames = { //"Comic Sans MS", "Arial", "Times New Roman", "Georgia", "Verdana", "Geneva" }; FontStyle[] aFontStyles = { FontStyle.Bold, FontStyle.Italic, FontStyle.Regular, FontStyle.Strikeout, FontStyle.Underline }; HatchStyle[] aHatchStyles = { HatchStyle.BackwardDiagonal, HatchStyle.Cross, HatchStyle.DashedDownwardDiagonal, HatchStyle.DashedHorizontal, HatchStyle.DashedUpwardDiagonal, HatchStyle.DashedVertical, HatchStyle.DiagonalBrick, HatchStyle.DiagonalCross, HatchStyle.Divot, HatchStyle.DottedDiamond, HatchStyle.DottedGrid, HatchStyle.ForwardDiagonal, HatchStyle.Horizontal, HatchStyle.HorizontalBrick, HatchStyle.LargeCheckerBoard, HatchStyle.LargeConfetti, HatchStyle.LargeGrid, HatchStyle.LightDownwardDiagonal, HatchStyle.LightHorizontal, HatchStyle.LightUpwardDiagonal, HatchStyle.LightVertical, HatchStyle.Max, HatchStyle.Min, HatchStyle.NarrowHorizontal, HatchStyle.NarrowVertical, HatchStyle.OutlinedDiamond, HatchStyle.Plaid, HatchStyle.Shingle, HatchStyle.SmallCheckerBoard, HatchStyle.SmallConfetti, HatchStyle.SmallGrid, HatchStyle.SolidDiamond, HatchStyle.Sphere, HatchStyle.Trellis, HatchStyle.Vertical, HatchStyle.Wave, HatchStyle.Weave, HatchStyle.WideDownwardDiagonal, HatchStyle.WideUpwardDiagonal, HatchStyle.ZigZag }; //Creates an output Bitmap var oOutputBitmap = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb); var oGraphics = Graphics.FromImage(oOutputBitmap); oGraphics.TextRenderingHint = TextRenderingHint.AntiAlias; //Create a Drawing area var oRectangleF = new RectangleF(0, 0, iWidth, iHeight); //Draw background (Lighter colors RGB 100 to 255) Brush oBrush = new HatchBrush(HatchStyle.Percent50, Color.Gainsboro, Color.White); //new HatchBrush(aHatchStyles[oRandom.Next(aHatchStyles.Length - 1)], Color.Gainsboro, Color.White);//HatchBrush(aHatchStyles[oRandom.Next(aHatchStyles.Length - 1)], Color.FromArgb((oRandom.Next(100, 255)), (oRandom.Next(100, 255)), (oRandom.Next(100, 255))), Color.White); oGraphics.FillRectangle(oBrush, oRectangleF); var oMatrix = new Matrix(); int i; for (i = 0; i <= captcha_data.Length - 1; i++) { oMatrix.Reset(); int iChars = captcha_data.Length; int x = (iWidth / (iChars + 1) * i) + 30; // adjust block width of every character const int y = iHeight / 4; // adjust block height of every charachter //Rotate text Random //oMatrix.RotateAt(oRandom.Next(-40, 40), new PointF(x, y)); oGraphics.Transform = oMatrix; StringFormat sf = new StringFormat(); sf.LineAlignment = StringAlignment.Center; sf.Alignment = StringAlignment.Center; //Draw the letters with Randon Font Type, Size and Color oGraphics.DrawString ( //Text captcha_data.Substring(i, 1), //Random Font Name and Style new Font(aFontNames[oRandom.Next(aFontNames.Length - 1)], aFontEmSizes[oRandom.Next(aFontEmSizes.Length - 1)], aFontStyles[oRandom.Next(aFontStyles.Length - 1)]), //Random Color (Darker colors RGB 0 to 100) new SolidBrush(Color.FromArgb(oRandom.Next(0, 100), oRandom.Next(0, 100), oRandom.Next(0, 100))), x, //put text at fixed width y //oRandom.Next(10, 40) // put text at random height ); oGraphics.ResetTransform(); } // context.Response.ContentType = "image/JPEG"; //render image //oOutputBitmap.Save(captcha_data + ".jpg", ImageFormat.Png); MemoryStream ms = new MemoryStream(); oOutputBitmap.Save(ms, ImageFormat.Jpeg); string final_val = Convert.ToBase64String(ms.GetBuffer()); //dispose everything, we do not need them any more. oOutputBitmap.Dispose(); oGraphics.Dispose(); // Console.WriteLine(); return(final_val); } catch (Exception ex) { throw ex; } }
public virtual void OnListViewDrawSubItem(object sender, DrawListViewSubItemEventArgs e) { e.DrawDefault = false; Form.Skin.GraphicsCommon(e.Graphics); DrawSubItemBackground(e); if (GetDrawSubItemFull(e.ColumnIndex) == false) { return; } if (e.ColumnIndex == 0) { Rectangle r = e.Bounds; r.Height--; Image imageState = GuiUtils.GetResourceImage(ImageStateResourcePrefix + e.Item.StateImageIndex.ToString()); if (imageState != null) { int imageWidth = r.Height; Rectangle rImage = r; rImage.X += ImageSpace; rImage.Width = imageWidth; Form.DrawImageContain(e.Graphics, imageState, rImage, 20); //e.Graphics.DrawImage(imageState, rImage); r.X += (imageWidth + ImageSpace); r.Width -= (imageWidth + ImageSpace); } Image imageIcon = GuiUtils.GetResourceImage(ImageIconResourcePrefix + e.Item.ImageKey); if ((imageIcon == null) && (ImageListIcon != null) && (ImageListIcon.Images.ContainsKey(e.Item.ImageKey))) { imageIcon = ImageListIcon.Images[e.Item.ImageKey]; } else if ((imageIcon == null) && (e.Item.ListView.LargeImageList != null) && (e.Item.ListView.LargeImageList.Images.ContainsKey(e.Item.ImageKey))) { imageIcon = e.Item.ListView.LargeImageList.Images[e.Item.ImageKey]; } else if ((imageIcon == null) && (e.Item.ListView.SmallImageList != null) && (e.Item.ListView.SmallImageList.Images.ContainsKey(e.Item.ImageKey))) { imageIcon = e.Item.ListView.SmallImageList.Images[e.Item.ImageKey]; } if (imageIcon != null) { //int imageWidth = r.Height; int imageHeight = r.Height; int imageWidth = (imageHeight * imageIcon.Width) / imageIcon.Height; Rectangle rImage = r; rImage.X += ImageSpace; rImage.Width = imageWidth; //e.Graphics.DrawImage(imageIcon, rImage); Form.DrawImageContain(e.Graphics, imageIcon, rImage, 20); r.X += (imageWidth + ImageSpace); r.Width -= (imageWidth + ImageSpace); } r.X += TextSpace; r.Width -= TextSpace; Form.DrawString(e.Graphics, e.Item.Text, e.Item.Font, Form.Skin.ForeBrush, r, GuiUtils.StringFormatLeftMiddle); } else { Rectangle r = e.Bounds; r.Height--; r.X += TextSpace; r.Width -= TextSpace; StringFormat stringFormat = GuiUtils.StringFormatLeftMiddle; if (e.Item.ListView.Columns[e.ColumnIndex].TextAlign == HorizontalAlignment.Center) { stringFormat = GuiUtils.StringFormatCenterMiddle; } else if (e.Item.ListView.Columns[e.ColumnIndex].TextAlign == HorizontalAlignment.Right) { stringFormat = GuiUtils.StringFormatRightMiddle; } Form.DrawString(e.Graphics, e.Item.SubItems[e.ColumnIndex].Text, e.Item.Font, Form.Skin.ForeBrush, r, stringFormat); } }
/// <summary> /// /// </summary> /// <param name="format"></param> /// <param name="contains">可以包含的文本</param> public StringFormatAttribute(StringFormat format, params string[] contains) { _formatValue = format; _contains = contains; }
private Bitmap GenerateImageFromTextWithStyle(string text, bool bold) { bool subtitleFontBold = bold; text = HtmlUtil.RemoveHtmlTags(text); Font font; try { var fontStyle = FontStyle.Regular; if (subtitleFontBold) { fontStyle = FontStyle.Bold; } font = new Font(_subtitleFontName, _subtitleFontSize, fontStyle); } catch (Exception exception) { MessageBox.Show(exception.Message); font = new Font(FontFamily.Families[0].Name, _subtitleFontSize); } var bmp = new Bitmap(400, 200); var g = Graphics.FromImage(bmp); SizeF textSize = g.MeasureString("Hj!", font); var lineHeight = (textSize.Height * 0.64f); textSize = g.MeasureString(HtmlUtil.RemoveHtmlTags(text), font); g.Dispose(); bmp.Dispose(); int sizeX = (int)(textSize.Width * 0.8) + 40; int sizeY = (int)(textSize.Height * 0.8) + 30; if (sizeX < 1) { sizeX = 1; } if (sizeY < 1) { sizeY = 1; } bmp = new Bitmap(sizeX, sizeY); g = Graphics.FromImage(bmp); g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; g.SmoothingMode = SmoothingMode.AntiAlias; g.CompositingQuality = CompositingQuality.HighQuality; var sf = new StringFormat { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Near }; // draw the text to a path var path = new GraphicsPath(); // display italic var sb = new StringBuilder(); int i = 0; const float left = 5f; float top = 5; bool newLine = false; const float leftMargin = left; int newLinePathPoint = -1; Color c = _subtitleColor; int textLen = text.Length; while (i < textLen) { char ch = text[i]; if (ch == '\n' || ch == '\r') { TextDraw.DrawText(font, sf, path, sb, false, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint); top += lineHeight; newLine = true; if (i + 1 < textLen && text[i + 1] == '\n' && text[i] == '\r') { i += 2; // CR+LF (Microsoft Windows) } else { i++; // LF (Unix and Unix-like systems ) } } else { sb.Append(ch); } i++; } if (sb.Length > 0) { TextDraw.DrawText(font, sf, path, sb, false, subtitleFontBold, false, left, top, ref newLine, leftMargin, ref newLinePathPoint); } sf.Dispose(); g.DrawPath(new Pen(_borderColor, BorderWidth), path); g.FillPath(new SolidBrush(c), path); g.Dispose(); var nbmp = new NikseBitmap(bmp); nbmp.CropTransparentSidesAndBottom(2, true); return(nbmp.GetBitmap()); }
public CachedString(string text, Font font, Color backColor) { String = text; BackColor = backColor; string strippedText = System.Text.RegularExpressions.Regex.Replace(text, "<.*?>", String.Empty); bool hasTags = (text.CompareTo(strippedText) != 0); currentFont = font; stringFormat = new StringFormat(StringFormat.GenericTypographic); if (hasTags) { stringFormat.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces; } SizeF tempSize = strippedText.MeasureString(font, stringFormat); stringSize = new SizeF((float)Math.Floor(tempSize.Width + padding), (float)Math.Floor(tempSize.Height + padding)); Bitmap stringBmp = new Bitmap((int)stringSize.Width, (int)stringSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(stringBmp)) { g.Clear(backColor); g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; if (hasTags) { ParseDrawString(g); } else { g.DrawString(text, font, Brushes.White, padding / 2.0f, padding / 2.0f, stringFormat); } } System.Drawing.Imaging.BitmapData bmpData = stringBmp.LockBits(new Rectangle(0, 0, stringBmp.Width, stringBmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, stringBmp.PixelFormat); TextureGLID = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, TextureGLID); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, stringBmp.Width, stringBmp.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, bmpData.Scan0); stringBmp.UnlockBits(bmpData); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); texCoordData = new double[] { 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f }; colorData = new double[] { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }; indices = new ushort[] { 0, 1, 2, 3 }; LastUsedAgo = 0.0f; disposed = false; }