如何用ImageResizer API调整Azure图片大小并兼顾磁盘缓存?
Hey there! Great question—you’re already using ImageResizer with Azure and DiskCache effectively in your web app, so extending that to PDF generation while keeping the cache benefits is totally doable. Let’s break down two solid approaches:
This leverages ImageResizer’s built-in pipeline, which automatically handles cache checks, blob fetching, resizing, and cache storage—no manual work needed. Here’s how to make it work for PDF generation:
- Confirm your existing configuration: Ensure your Azure Blob Reader and DiskCache plugins are properly set up (either in
Web.configor your startup code). For example, your Azure plugin should map a virtual path prefix (like~/azure/) to your blob container. - Construct a virtual path for your blob: Instead of downloading the blob directly, use the virtual path format ImageResizer recognizes. For a blob named
report-image.jpgin containerpdf-assets, this would be~/azure/pdf-assets/report-image.jpg. - Use ImageBuilder with the virtual path: Pass this virtual path to the
ImageBuilder.Current.Buildmethod along with your resize settings. ImageResizer will automatically check the DiskCache first—if the resized image exists, it pulls it from cache; if not, it fetches the blob, resizes it, saves it to cache, and returns the result.
Example code snippet:
// Virtual path pointing to your Azure Blob (match your plugin's prefix) string virtualBlobPath = "~/azure/pdf-assets/report-image.jpg"; // Define your resize requirements var resizeSettings = new ResizeSettings("width=1000&height=750&mode=max&format=jpg"); // Let ImageResizer handle the rest—cache included! using (Bitmap resizedImage = ImageBuilder.Current.Build(virtualBlobPath, resizeSettings)) { // Pass the resized bitmap to your PDF generator (e.g., iTextSharp, QuestPDF) pdfDocument.AddImage(resizedImage); }
If you need more control over cache logic (like custom cache keys or pre-processing), you can directly interact with the DiskCache API to check for cached images before fetching from Azure:
- Get the DiskCache instance: Use the same configuration as your web app to ensure cache consistency.
- Generate a unique cache key: Combine the blob’s unique identifier and your resize settings to create a key that uniquely identifies the resized image.
- Check for existing cache: If the cached file exists, load it directly. If not, fetch the blob, resize it, save it to cache, then use it.
Example code snippet:
// Initialize DiskCache with your web app's configuration var diskCache = new DiskCache(new DiskCacheConfiguration { VirtualCachePath = "~/cache", // Match your web app's cache path MaxCacheSize = 1000 // Adjust based on your storage needs }); string blobIdentifier = "pdf-assets/report-image.jpg"; var resizeSettings = new ResizeSettings("width=1000&height=750"); // Create a unique cache key using blob ID and resize settings string cacheKey = $"{blobIdentifier}_{resizeSettings.Serialize()}"; Bitmap resizedImage; string cachedFilePath = diskCache.GetCachedPath(cacheKey); if (!string.IsNullOrEmpty(cachedFilePath)) { // Cache exists—load directly from disk resizedImage = new Bitmap(cachedFilePath); } else { // No cache—fetch blob from Azure, resize, then save to cache CloudBlobContainer container = GetYourBlobContainer(); // Your existing container retrieval method CloudBlockBlob blob = container.GetBlockBlobReference(blobIdentifier); using (var blobStream = new MemoryStream()) { blob.DownloadToStream(blobStream); blobStream.Position = 0; // Resize the image resizedImage = ImageBuilder.Current.Build(blobStream, resizeSettings); // Save the resized image to DiskCache diskCache.Add(cacheKey, stream => resizedImage.Save(stream, ImageFormat.Jpeg), "image/jpeg"); } } // Use the resized image in your PDF generator pdfDocument.AddImage(resizedImage); resizedImage.Dispose();
- Cache consistency: Ensure your PDF generation environment uses the exact same DiskCache configuration as your web app (cache directory, expiration rules, etc.) to share cached images across both workflows.
- Cache invalidation: If your blobs get updated, remember to clear the corresponding cache entries (or configure DiskCache’s expiration policy) to avoid serving outdated images in reports.
- Memory efficiency: For large images, prefer returning a
Streaminstead of aBitmapfromImageBuilder.Buildto reduce memory usage—just adjust the method call to return a stream instead.
内容的提问来源于stack exchange,提问作者Akinzekeel

