11// Title: In-Memory Barcode Image Caching Example
2- // Description: Demonstrates how to cache generated barcode images in memory to avoid regenerating identical barcodes, improving performance .
3- // Category-Description: This example belongs to the Aspose.BarCode generation category, illustrating the use of BarcodeGenerator, BaseEncodeType, and image handling classes. Developers often need to generate multiple barcodes with repeated data , and caching reduces redundant processing and resource usage. Ideal for batch processing, reporting, or any scenario where the same barcode may be requested multiple times .
2+ // Description: Demonstrates caching of generated barcode images in memory to avoid redundant regeneration for identical barcode specifications .
3+ // Category-Description: This example belongs to the Aspose.BarCode generation and caching category, showcasing how to use BarcodeGenerator, BaseEncodeType, and BarCodeImageFormat to create barcodes, store them in a dictionary , and reuse them. Developers often need to improve performance when generating many barcodes with repeated parameters, and this pattern provides a simple in‑process cache .
44// Prompt: Cache generated barcode images in memory to avoid redundant regeneration for identical field sets.
5- // Tags: barcode, caching, memory, code128, qr, datamatrix, aspnet, aspose.barcode, image generation
5+ // Tags: barcode, caching, memory, code128, qr, datamatrix, generation, aspnet, aspose.barcode
66
77using System ;
88using System . Collections . Generic ;
9+ using System . IO ;
910using Aspose . BarCode ;
1011using Aspose . BarCode . Generation ;
11- using Aspose . Drawing ;
12- using Aspose . Drawing . Imaging ;
12+ using Aspose . BarCode . BarCodeRecognition ;
1313
1414/// <summary>
15- /// Demonstrates in‑memory caching of barcode images to prevent duplicate generation .
15+ /// Provides an in‑memory cache for barcode images generated with Aspose.BarCode .
1616/// </summary>
17- class Program
17+ class BarcodeCache
1818{
19+ // Internal dictionary that maps a unique key (encode type + text) to the generated PNG bytes.
20+ private static readonly Dictionary < string , byte [ ] > _cache = new Dictionary < string , byte [ ] > ( ) ;
21+
1922 /// <summary>
20- /// Retrieves a barcode image from the cache or generates a new one if it does not exist.
23+ /// Retrieves a cached barcode image or generates a new one if it does not exist.
2124 /// </summary>
22- /// <param name="encodeType">The barcode symbology to use.</param>
23- /// <param name="codeText">The text or data to encode.</param>
24- /// <param name="cache">Dictionary that stores previously generated images keyed by symbology and text.</param>
25- /// <returns>A <see cref="Bitmap"/> containing the generated barcode.</returns>
26- static Bitmap GetBarcodeImage ( BaseEncodeType encodeType , string codeText , Dictionary < string , Bitmap > cache )
25+ /// <param name="encodeType">The barcode symbology to use (e.g., Code128, QR).</param>
26+ /// <param name="codeText">The text or data to encode in the barcode.</param>
27+ /// <returns>A byte array containing the PNG image of the barcode.</returns>
28+ public static byte [ ] GetOrCreate ( BaseEncodeType encodeType , string codeText )
2729 {
28- // Build a unique cache key from the encode type and the text.
29- string key = $ "{ encodeType } :{ codeText } ";
30+ // Build a unique cache key based on the encode type's full name, its enum value, and the text.
31+ string key = $ "{ encodeType . GetType ( ) . FullName } : { encodeType } :{ codeText } ";
3032
3133 // Return the cached image if it already exists.
32- if ( cache . TryGetValue ( key , out Bitmap cachedImage ) )
34+ if ( _cache . TryGetValue ( key , out byte [ ] cachedData ) )
3335 {
34- Console . WriteLine ( $ "Cache hit for key: { key } ") ;
35- return cachedImage ;
36+ Console . WriteLine ( $ "Cache hit for [ { encodeType } ] \" { codeText } \" ") ;
37+ return cachedData ;
3638 }
3739
38- // No cached image – generate a new barcode.
39- Console . WriteLine ( $ "Generating barcode for key: { key } ") ;
40+ // Cache miss – generate a new barcode image .
41+ Console . WriteLine ( $ "Generating barcode for [ { encodeType } ] \" { codeText } \" ") ;
4042 using ( var generator = new BarcodeGenerator ( encodeType , codeText ) )
4143 {
42- Bitmap image = generator . GenerateBarCodeImage ( ) ;
43- cache [ key ] = image ; // Store the newly generated image for future requests.
44- return image ;
44+ // Example: set a higher resolution for better image quality.
45+ generator . Parameters . Resolution = 300 ;
46+
47+ using ( var ms = new MemoryStream ( ) )
48+ {
49+ // Save the barcode to the memory stream in PNG format.
50+ generator . Save ( ms , BarCodeImageFormat . Png ) ;
51+ byte [ ] data = ms . ToArray ( ) ;
52+
53+ // Store the generated image in the cache for future requests.
54+ _cache [ key ] = data ;
55+ return data ;
56+ }
4557 }
4658 }
59+ }
4760
61+ /// <summary>
62+ /// Demonstrates the use of <see cref="BarcodeCache"/> to generate and cache barcode images.
63+ /// </summary>
64+ class Program
65+ {
4866 /// <summary>
49- /// Entry point of the example. Generates several barcodes, some of which are duplicates,
50- /// to demonstrate caching. Saves each image to disk and disposes resources afterwards .
67+ /// Entry point of the example. Generates a series of barcodes, some of which are duplicates,
68+ /// to illustrate caching behavior, and writes the images to disk .
5169 /// </summary>
5270 static void Main ( )
5371 {
54- // In‑memory cache: maps a unique key to a barcode bitmap.
55- var barcodeCache = new Dictionary < string , Bitmap > ( ) ;
56-
57- // Define a set of barcode requests; duplicates are intentional to test caching.
58- var requests = new ( BaseEncodeType type , string text ) [ ]
72+ // Define a list of barcode generation requests; duplicates test the cache.
73+ var requests = new List < ( BaseEncodeType type , string text ) >
5974 {
60- ( EncodeTypes . Code128 , "123ABC " ) ,
75+ ( EncodeTypes . Code128 , "ABC123 " ) ,
6176 ( EncodeTypes . QR , "https://example.com" ) ,
62- ( EncodeTypes . Code128 , "123ABC " ) , // duplicate
77+ ( EncodeTypes . Code128 , "ABC123 " ) , // duplicate
6378 ( EncodeTypes . DataMatrix , "DataMatrixSample" ) ,
6479 ( EncodeTypes . QR , "https://example.com" ) // duplicate
6580 } ;
6681
67- // Process each request, retrieving from cache or generating as needed.
68- for ( int i = 0 ; i < requests . Length ; i ++ )
82+ int index = 1 ;
83+ foreach ( var ( type , text ) in requests )
6984 {
70- var ( type , text ) = requests [ i ] ;
71- Bitmap barcodeImage = GetBarcodeImage ( type , text , barcodeCache ) ;
85+ // Retrieve the barcode image, using the cache when possible.
86+ byte [ ] imageData = BarcodeCache . GetOrCreate ( type , text ) ;
7287
73- // Save each image with a unique filename for verification.
74- string fileName = $ "barcode_{ i + 1 } .png";
75- using ( var fileStream = System . IO . File . OpenWrite ( fileName ) )
76- {
77- barcodeImage . Save ( fileStream , ImageFormat . Png ) ;
78- }
88+ // Construct a file name that includes the request order and barcode type.
89+ string fileName = $ "barcode_{ index } _{ type } .png";
7990
91+ // Write the PNG bytes to disk.
92+ File . WriteAllBytes ( fileName , imageData ) ;
8093 Console . WriteLine ( $ "Saved barcode to { fileName } ") ;
94+ index ++ ;
8195 }
8296
83- // Dispose all cached bitmaps before exiting to free unmanaged resources.
84- foreach ( var kvp in barcodeCache )
85- {
86- kvp . Value . Dispose ( ) ;
87- }
88-
89- Console . WriteLine ( "All barcodes processed. Press any key to exit." ) ;
90- Console . ReadKey ( ) ;
97+ Console . WriteLine ( "Processing completed." ) ;
9198 }
9299}
0 commit comments