Rob van der Woude's Scripting Pages
Powered by GeSHi

Source code for barcode.cs

(view source code of barcode.cs as plain text)

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Drawing;
  5. using System.Drawing.Imaging;
  6. using System.IO;
  7. using System.Windows.Forms;
  8.  
  9.  
  10. namespace RobvanderWoude
  11. {
  12. 	class Barcode
  13. 	{
  14. 		static readonly string progver = "1.01";
  15.  
  16.  
  17. 		// BlanchedAlmond is an invalid color for this program, and is used to signal an error
  18. 		static readonly Brush errorbrush = Brushes.BlanchedAlmond;
  19. 		static readonly Color errorcolor = Color.BlanchedAlmond;
  20.  
  21.  
  22. 		static int Main( string[] args )
  23. 		{
  24. 			#region Set Defaults
  25.  
  26. 			string imgfile = String.Empty;
  27. 			string text = String.Empty;
  28. 			Color bgcolor = Color.White;
  29. 			Brush fgcolor = Brushes.Black;
  30. 			RotateFlipType rotation = RotateFlipType.RotateNoneFlipNone;
  31. 			ImageFormat format = ImageFormat.Jpeg;
  32. 			int degrees;
  33. 			int fontsize = 48;
  34.  
  35. 			#endregion Set Defaults
  36.  
  37.  
  38. 			#region Parse Command Line
  39.  
  40. 			if ( args.Length < 2 )
  41. 			{
  42. 				return ShowHelp( );
  43. 			}
  44.  
  45. 			foreach ( string arg in args )
  46. 			{
  47. 				if ( arg[0] == '/' )
  48. 				{
  49. 					#region Named Switches
  50.  
  51. 					switch ( arg.ToLower( )[1] )
  52. 					{
  53. 						case '?':
  54. 							return ShowHelp( );
  55. 						case 'b':
  56. 							if ( bgcolor != Color.White )
  57. 							{
  58. 								return ShowHelp( "Duplicate command line switch /B" );
  59. 							}
  60. 							bgcolor = GetColor( arg.Substring( 3 ).ToLower( ) );
  61. 							if( bgcolor == errorcolor )
  62. 							{
  63. 								return ShowHelp( "Invalid background color specified: \"{0}\"", arg );
  64. 							}
  65. 							break;
  66. 						case 'f':
  67. 							if ( fgcolor != Brushes.Black )
  68. 							{
  69. 								return ShowHelp( "Duplicate command line switch /F" );
  70. 							}
  71. 							fgcolor = GetBrush( arg.Substring( 3 ).ToLower( ) );
  72. 							if ( fgcolor == errorbrush )
  73. 							{
  74. 								return ShowHelp( "Invalid foreground color specified: \"{0}\"", arg );
  75. 							}
  76. 							break;
  77. 						case 'r':
  78. 							if ( rotation != RotateFlipType.RotateNoneFlipNone )
  79. 							{
  80. 								return ShowHelp( "Duplicate command line switch /R" );
  81. 							}
  82. 							if ( arg.Length < 5 || arg.Length > 7 )
  83. 							{
  84. 								return ShowHelp( "Invalid rotation specified: \"{0}\"", arg );
  85. 							}
  86. 							try
  87. 							{
  88. 								degrees = Convert.ToInt32( arg.Substring( 3 ) );
  89. 								if ( degrees % 90 != 0 )
  90. 								{
  91. 									return ShowHelp( "Invalid rotation specified: \"{0}\"", arg );
  92. 								}
  93. 								degrees %= 360;
  94. 							}
  95. 							catch
  96. 							{
  97. 								return ShowHelp( "Invalid rotation specified: \"{0}\"", arg );
  98. 							}
  99. 							rotation = (RotateFlipType) ( degrees / 90 );
  100. 							break;
  101. 						case 's':
  102. 							if ( fontsize != 48 )
  103. 							{
  104. 								return ShowHelp( "Duplicate command line switch /S" );
  105. 							}
  106. 							try
  107. 							{
  108. 								fontsize = Convert.ToInt32( arg.Substring( 3 ) );
  109. 							}
  110. 							catch
  111. 							{
  112. 								return ShowHelp( "Invalid rotation specified: \"{0}\"", arg );
  113. 							}
  114. 							break;
  115. 						default:
  116. 							return ShowHelp( "Invalid command line argument: \"{0}\"", arg );
  117. 					}
  118.  
  119. 					#endregion Named Switches
  120. 				}
  121. 				else // Unnamed switches
  122. 				{
  123. 					#region Unnamed Switches
  124.  
  125. 					if ( String.IsNullOrWhiteSpace( imgfile ) )
  126. 					{
  127. 						if ( Directory.Exists( Directory.GetParent( arg ).FullName ) )
  128. 						{
  129. 							imgfile = Path.GetFullPath( arg );
  130. 							string ext = Path.GetExtension( imgfile ).ToLower( );
  131. 							switch ( ext )
  132. 							{
  133. 								case ".bmp":
  134. 									format = ImageFormat.Bmp;
  135. 									break;
  136. 								case ".gif":
  137. 									format = ImageFormat.Gif;
  138. 									break;
  139. 								case ".jpg":
  140. 								case ".jpeg":
  141. 									format = ImageFormat.Jpeg;
  142. 									break;
  143. 								case ".png":
  144. 									format = ImageFormat.Png;
  145. 									break;
  146. 								case ".tif":
  147. 								case ".tiff":
  148. 									format = ImageFormat.Tiff;
  149. 									break;
  150. 								default:
  151. 									return ShowHelp( "Invalid file type: \"{0}\"", imgfile );
  152. 							}
  153. 						}
  154. 						else
  155. 						{
  156. 							return ShowHelp( "Invalid path for outputfile: \"{0}\"", arg );
  157. 						}
  158. 					}
  159. 					else if ( String.IsNullOrWhiteSpace( text ) )
  160. 					{
  161. 						text = arg;
  162. 					}
  163. 					else
  164. 					{
  165. 						return ShowHelp( );
  166. 					}
  167.  
  168. 					#endregion Unnamed Switches
  169. 				}
  170. 			}
  171.  
  172. 			#endregion Parse Command Line
  173.  
  174.  
  175. 			#region Check Font EAN-13
  176.  
  177. 			if ( !CheckFont( fontsize ) )
  178. 			{
  179. 				if ( CheckFont( ) )
  180. 				{
  181. 					return ShowHelp( "{0} is not a valid font size for the EAN-13 TrueType font.", fontsize.ToString( ) );
  182. 				}
  183. 				else
  184. 				{
  185. 					string url = "http://www.fontpalace.com/font-download/EAN-13/";
  186. 					string msg = String.Format( "This program uses the EAN-13 TrueType Font, available at\n\n{0}\n\nDo you want to download this font?", url );
  187. 					string title = "Download Missing Font";
  188. 					if ( MessageBox.Show( msg, title, MessageBoxButtons.YesNo ) == DialogResult.Yes )
  189. 					{
  190. 						Process browser = new Process
  191. 						{
  192. 							StartInfo = new ProcessStartInfo( url )
  193. 						};
  194. 						browser.Start( );
  195. 					}
  196. 					return ShowHelp( );
  197. 				}
  198. 			}
  199.  
  200. 			#endregion Check Font EAN-13
  201.  
  202.  
  203. 			Bitmap bitmap = new Bitmap( 1, 1 );
  204. 			Graphics graphics = Graphics.FromImage( bitmap );
  205. 			Font font = new Font( "EAN-13", fontsize );
  206. 			// Instantiating object of bitmap image again with the correct size for the text and font.
  207. 			SizeF stringsize = graphics.MeasureString( text, font );
  208. 			bitmap = new Bitmap( bitmap, (int) stringsize.Width, (int) stringsize.Height );
  209. 			graphics = Graphics.FromImage( bitmap );
  210. 			// Set background color
  211. 			graphics.Clear( bgcolor );
  212. 			graphics.DrawString( text, font, fgcolor, 0, 0 );
  213. 			font.Dispose( );
  214. 			graphics.Flush( );
  215. 			graphics.Dispose( );
  216. 			// Rotate bitmap image
  217. 			bitmap.RotateFlip( rotation );
  218. 			// Save bitmap image 
  219. 			bitmap.Save( imgfile, format );
  220. 			int rc = (int) stringsize.Width;
  221. 			return rc;
  222. 		}
  223.  
  224.  
  225. 		public static bool CheckFont( int size = 48 )
  226. 		{
  227. 			// Font test by Jeff Hillman
  228. 			// https://stackoverflow.com/a/114003
  229. 			using ( Font fonttest = new Font( "EAN-13", size, FontStyle.Regular, GraphicsUnit.Pixel ) )
  230. 			{
  231. 				return ( fonttest.Name == "EAN-13" );
  232. 			}
  233. 		}
  234.  
  235.  
  236. 		public static Brush GetBrush( string colorstring )
  237. 		{
  238. 			Brush brush;
  239. 			switch ( colorstring.ToLower( ) )
  240. 			{
  241. 				case "black":
  242. 					brush = Brushes.Black;
  243. 					break;
  244. 				case "blue":
  245. 					brush = Brushes.Blue;
  246. 					break;
  247. 				case "brown":
  248. 					brush = Brushes.Brown;
  249. 					break;
  250. 				case "cyan":
  251. 					brush = Brushes.Cyan;
  252. 					break;
  253. 				case "darkblue":
  254. 					brush = Brushes.DarkBlue;
  255. 					break;
  256. 				case "darkcyan":
  257. 					brush = Brushes.DarkCyan;
  258. 					break;
  259. 				case "darkgray":
  260. 				case "darkgrey":
  261. 					brush = Brushes.DarkGray;
  262. 					break;
  263. 				case "darkgreen":
  264. 					brush = Brushes.DarkGreen;
  265. 					break;
  266. 				case "darkmagenta":
  267. 					brush = Brushes.DarkMagenta;
  268. 					break;
  269. 				case "darkorange":
  270. 					brush = Brushes.DarkOrange;
  271. 					break;
  272. 				case "dark":
  273. 					brush = Brushes.DarkRed;
  274. 					break;
  275. 				case "gold":
  276. 					brush = Brushes.Gold;
  277. 					break;
  278. 				case "gray":
  279. 				case "grey":
  280. 					brush = Brushes.Gray;
  281. 					break;
  282. 				case "green":
  283. 					brush = Brushes.Green;
  284. 					break;
  285. 				case "lightblue":
  286. 					brush = Brushes.LightBlue;
  287. 					break;
  288. 				case "lightcyan":
  289. 					brush = Brushes.LightCyan;
  290. 					break;
  291. 				case "lightgray":
  292. 				case "lightgrey":
  293. 					brush = Brushes.LightGray;
  294. 					break;
  295. 				case "lightgreen":
  296. 					brush = Brushes.LightGreen;
  297. 					break;
  298. 				case "lightyellow":
  299. 					brush = Brushes.LightYellow;
  300. 					break;
  301. 				case "magenta":
  302. 					brush = Brushes.Magenta;
  303. 					break;
  304. 				case "orange":
  305. 					brush = Brushes.Orange;
  306. 					break;
  307. 				case "pink":
  308. 					brush = Brushes.Pink;
  309. 					break;
  310. 				case "red":
  311. 					brush = Brushes.Red;
  312. 					break;
  313. 				case "silver":
  314. 					brush = Brushes.Silver;
  315. 					break;
  316. 				case "white":
  317. 					brush = Brushes.White;
  318. 					break;
  319. 				case "yellow":
  320. 					brush = Brushes.Yellow;
  321. 					break;
  322. 				case "yellowgreen":
  323. 					brush = Brushes.YellowGreen;
  324. 					break;
  325. 				default:
  326. 					brush = errorbrush;
  327. 					break;
  328. 			}
  329. 			return brush;
  330. 		}
  331.  
  332.  
  333. 		public static Color GetColor( string colorstring )
  334. 		{
  335. 			try
  336. 			{
  337. 				return Color.FromName( colorstring );
  338. 			}
  339. 			catch
  340. 			{
  341. 				return errorcolor;
  342. 			}
  343. 		}
  344.  
  345.  
  346. 		#region Error handling
  347.  
  348. 		public static int ShowHelp( params string[] errmsg )
  349. 		{
  350. 			#region Error Message
  351.  
  352. 			if ( errmsg.Length > 0 )
  353. 			{
  354. 				List<string> errargs = new List<string>( errmsg );
  355. 				errargs.RemoveAt( 0 );
  356. 				Console.Error.WriteLine( );
  357. 				Console.ForegroundColor = ConsoleColor.Red;
  358. 				Console.Error.Write( "ERROR:\t" );
  359. 				Console.ForegroundColor = ConsoleColor.White;
  360. 				Console.Error.WriteLine( errmsg[0], errargs.ToArray( ) );
  361. 				Console.ResetColor( );
  362. 			}
  363.  
  364. 			#endregion Error Message
  365.  
  366.  
  367. 			#region Help Text
  368.  
  369. 			/*
  370. 			Barcode.exe,  Version 1.01
  371. 			Generate barcode bitmaps using EAN-13 TrueType font
  372.  
  373. 			Usage:    BARCODE   outfile   text   [ options ]
  374.  
  375. 			Where:    outfile   is the output file path (type: bmp, gif, jpg, png or tif)
  376. 			          text      is the text to be converted to barcode
  377.  
  378. 			Options:  /R:deg    Rotate by number of degrees (multiple of 90; default: 0)
  379. 			          /S:size   font Size in pt  (default: 48)
  380. 			          /B:color  Background color (default: white)
  381. 			          /F:color  Foreground color (default: black)
  382.  
  383. 			Credits:  Code to convert text to bitmap by RaviRanjanKr:
  384. 			          https://www.codeproject.com/Tips/184102/Convert-Text-to-Image
  385. 			          Font test by Jeff Hillman:
  386. 			          https://stackoverflow.com/a/114003
  387. 			          EAN-13 font made available by Fontpalace.com:
  388. 			          http://www.fontpalace.com/font-download/EAN-13/
  389.  
  390. 			Notes:    If the required EAN-13 TrueType font is not installed, you will be
  391. 			          prompted to download it.
  392. 			          Though the font name may suggest that the barcode conforms to the
  393. 			          EAN-13 standard, it does not! You have to validate the specified
  394. 			          text yourself to make sure it is a valid EAN-13 code.
  395. 			          Supported background and foreground colors are: Black, Blue *, Brown,
  396. 			          Cyan *, Gold, Gray *, Grey *, Green *, LightYellow, Magenta *,
  397. 			          Orange *, Pink, Red *, Silver, White, Yellow and YellowGreen (* means
  398. 			          Dark and Light variants are also supported, e.g. DarkBlue, LightGreen).
  399. 			          Return code ("errorlevel") equals the output image width in pixels,
  400. 			          or -1 in case of errors.
  401.  
  402. 			Written by Rob van der Woude
  403. 			http://www.robvanderwoude.com
  404. 			*/
  405.  
  406. 			Console.Error.WriteLine( );
  407.  
  408. 			Console.Error.WriteLine( "Barcode.exe,  Version {0}", progver );
  409.  
  410. 			Console.Error.WriteLine( "Generate barcode bitmaps using EAN-13 TrueType font" );
  411.  
  412. 			Console.Error.WriteLine( );
  413.  
  414. 			Console.Error.Write( "Usage:    " );
  415.  
  416. 			Console.ForegroundColor = ConsoleColor.White;
  417. 			Console.Error.WriteLine( "BARCODE   outfile   text   [ options ]" );
  418. 			Console.ResetColor( );
  419.  
  420. 			Console.Error.WriteLine( );
  421.  
  422. 			Console.Error.Write( "Where:    " );
  423. 			Console.ForegroundColor = ConsoleColor.White;
  424. 			Console.Error.Write( "outfile" );
  425. 			Console.ResetColor( );
  426. 			Console.Error.WriteLine( "   is the output file path (type: bmp, gif, jpg, png or tif)" );
  427.  
  428. 			Console.ForegroundColor = ConsoleColor.White;
  429. 			Console.Error.Write( "          text" );
  430. 			Console.ResetColor( );
  431. 			Console.Error.WriteLine( "      is the text to be converted to barcode" );
  432.  
  433. 			Console.Error.WriteLine( );
  434.  
  435. 			Console.Error.Write( "Options:" );
  436. 			Console.ForegroundColor = ConsoleColor.White;
  437. 			Console.Error.Write( "  /R:deg    R" );
  438. 			Console.ResetColor( );
  439. 			Console.Error.Write( "otate by number of " );
  440. 			Console.ForegroundColor = ConsoleColor.White;
  441. 			Console.Error.Write( "deg" );
  442. 			Console.ResetColor( );
  443. 			Console.Error.WriteLine( "rees (multiple of 90; default: 0)" );
  444.  
  445. 			Console.ForegroundColor = ConsoleColor.White;
  446. 			Console.Error.Write( "          /S:size" );
  447. 			Console.ResetColor( );
  448. 			Console.Error.Write( "   font " );
  449. 			Console.ForegroundColor = ConsoleColor.White;
  450. 			Console.Error.Write( "S" );
  451. 			Console.ResetColor( );
  452. 			Console.Error.WriteLine( "ize in pt  (default: 48)" );
  453.  
  454. 			Console.ForegroundColor = ConsoleColor.White;
  455. 			Console.Error.Write( "          /B:color  B" );
  456. 			Console.ResetColor( );
  457. 			Console.Error.Write( "ackground " );
  458. 			Console.ForegroundColor = ConsoleColor.White;
  459. 			Console.Error.Write( "color" );
  460. 			Console.ResetColor( );
  461. 			Console.Error.WriteLine( " (default: white)" );
  462.  
  463. 			Console.ForegroundColor = ConsoleColor.White;
  464. 			Console.Error.Write( "          /F:color  F" );
  465. 			Console.ResetColor( );
  466. 			Console.Error.Write( "oreground " );
  467. 			Console.ForegroundColor = ConsoleColor.White;
  468. 			Console.Error.Write( "color" );
  469. 			Console.ResetColor( );
  470. 			Console.Error.WriteLine( " (default: black)" );
  471.  
  472. 			Console.Error.WriteLine( );
  473.  
  474. 			Console.Error.WriteLine( "Credits:  Code to convert text to bitmap by RaviRanjanKr:" );
  475.  
  476. 			Console.ForegroundColor = ConsoleColor.DarkGray;
  477. 			Console.Error.WriteLine( "          https://www.codeproject.com/Tips/184102/Convert-Text-to-Image" );
  478. 			Console.ResetColor( );
  479.  
  480. 			Console.Error.WriteLine( "          Font test by Jeff Hillman:" );
  481.  
  482. 			Console.ForegroundColor = ConsoleColor.DarkGray;
  483. 			Console.Error.WriteLine( "          https://stackoverflow.com/a/114003" );
  484. 			Console.ResetColor( );
  485.  
  486. 			Console.Error.WriteLine( "          EAN-13 font made available by Fontpalace.com:" );
  487.  
  488. 			Console.ForegroundColor = ConsoleColor.DarkGray;
  489. 			Console.Error.WriteLine( "          http://www.fontpalace.com/font-download/EAN-13/" );
  490. 			Console.ResetColor( );
  491.  
  492. 			Console.Error.WriteLine( );
  493.  
  494. 			Console.Error.WriteLine( "Notes:    If the required EAN-13 TrueType font is not installed, you will be" );
  495.  
  496. 			Console.Error.WriteLine( "          prompted to download it." );
  497.  
  498. 			Console.Error.WriteLine( "          Though the font name may suggest that the barcode conforms to the" );
  499.  
  500. 			Console.Error.WriteLine( "          EAN-13 standard, it does not! You have to validate the specified" );
  501.  
  502. 			Console.Error.WriteLine( "          text yourself to make sure it is a valid EAN-13 code." );
  503.  
  504. 			Console.Error.WriteLine( "          Supported background and foreground colors are: Black, Blue *, Brown," );
  505.  
  506. 			Console.Error.WriteLine( "          Cyan *, Gold, Gray *, Grey *, Green *, LightYellow, Magenta *," );
  507.  
  508. 			Console.Error.WriteLine( "          Orange *, Pink, Red *, Silver, White, Yellow and YellowGreen (* means" );
  509.  
  510. 			Console.Error.WriteLine( "          Dark and Light variants are also supported, e.g. DarkBlue)." );
  511.  
  512. 			Console.Error.WriteLine( "          Return code (\"errorlevel\") equals the output image width in pixels," );
  513.  
  514. 			Console.Error.WriteLine( "          or -1 in case of errors." );
  515.  
  516. 			Console.Error.WriteLine( );
  517.  
  518. 			Console.Error.WriteLine( "Written by Rob van der Woude" );
  519.  
  520. 			Console.Error.WriteLine( "http://www.robvanderwoude.com" );
  521.  
  522. 			#endregion Help Text
  523.  
  524. 			return -1;
  525. 		}
  526.  
  527. 		#endregion Error handling
  528. 	}
  529. }
  530.  

page last modified: 2024-04-16; loaded in 0.0116 seconds