Crear els àlbums TIFF de múltiples pàgines directament des de l’emmagatzematge en núvol és una bona manera d’arxiu o intercanviar grans grups d’imatges (escans, fotografies de producte, imatges de pàgina). Amb Aspose.Imaging per .NET, es poden stream imatges a partir de Azure Blob Storage (o S3), convertir-los en els quadres TifF, i guardar un únic, compresos multi-pàgins de tiff - no requereixen arxius de temp.
Aquest article reemplaça el gel amb un exemple complet, en línia, còpia-paste i afegeix detalls exactes per a les opcions TIFF, compressió , DPI o ús de la memòria.
Exemple complet (Inline, Copy-Paste Ready)
Què fa aquest programa:
- Llista d’imatges en un contenidor Azure Blob Storage (filtrant per extensió).
- Streams cada blob a la memòria (no arxius temp).
- Construeix un multi-page TIFF mitjançant la compressió LZW a 300 DPI.
- Salva el TIFF al disc local ** i** (opcionalment) el carrega de nou al contenidor.
Requisits →
- .NET 8 (o 6+)
- Els paquets de NuGet:-
Aspose.Imaging
Azure.Storage.Blobs
// File: Program.cs
// Build deps:
// dotnet add package Aspose.Imaging
// dotnet add package Azure.Storage.Blobs
//
// Run (example):
// setx AZURE_STORAGE_CONNECTION_STRING "<your-connection-string>"
// dotnet run -- "<container-name>" "album-output.tiff" // uploads album-output.tiff back to same container
//
// Notes:
// - Streams JPEG/PNG/BMP/TIFF/GIF web-safe inputs and assembles a multi-page LZW RGB TIFF at 300 DPI.
// - If there are no images, the program exits gracefully.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Azure;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Aspose.Imaging;
using Aspose.Imaging.FileFormats.Tiff;
using Aspose.Imaging.FileFormats.Tiff.Enums;
using Aspose.Imaging.ImageOptions;
class Program
{
// Accepted extensions (case-insensitive)
private static readonly string[] ImageExts = new[]
{
".jpg", ".jpeg", ".png", ".bmp", ".gif", ".tif", ".tiff"
};
static async Task<int> Main(string[] args)
{
if (args.Length < 2)
{
Console.Error.WriteLine("Usage: dotnet run -- <containerName> <albumFileName.tiff> [prefix]");
Console.Error.WriteLine("Example: dotnet run -- scans album-2025-07.tiff scans/incoming/");
return 1;
}
string containerName = args[0];
string albumFileName = args[1];
string prefix = args.Length > 2 ? args[2] : string.Empty;
string? conn = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");
if (string.IsNullOrWhiteSpace(conn))
{
Console.Error.WriteLine("AZURE_STORAGE_CONNECTION_STRING is not set.");
return 2;
}
try
{
var container = new BlobContainerClient(conn, containerName);
// 1) Enumerate candidate image blobs (optionally under a prefix)
var images = await ListImageBlobsAsync(container, prefix);
if (images.Count == 0)
{
Console.WriteLine("No images found. Nothing to do.");
return 0;
}
Console.WriteLine($"Found {images.Count} image(s). Building multi-page TIFF…");
// 2) Build multipage TIFF in memory (for safety, stream to file to avoid huge RAM for very large sets)
// We will construct a TiffImage and append frames.
string localAlbumPath = Path.GetFullPath(albumFileName);
BuildMultipageTiffFromBlobs(container, images, localAlbumPath);
Console.WriteLine($"✅ Saved multi-page TIFF locally: {localAlbumPath}");
// 3) Optional: upload back to same container
var albumBlob = container.GetBlobClient(Path.GetFileName(albumFileName));
Console.WriteLine($"Uploading album back to container as: {albumBlob.Name} …");
using (var fs = File.OpenRead(localAlbumPath))
{
await albumBlob.UploadAsync(fs, overwrite: true);
}
Console.WriteLine("✅ Upload complete.");
return 0;
}
catch (RequestFailedException are)
{
Console.Error.WriteLine("Azure error: " + are.Message);
return 3;
}
catch (Exception ex)
{
Console.Error.WriteLine("Error: " + ex.Message);
return 4;
}
}
private static async Task<List<BlobItem>> ListImageBlobsAsync(BlobContainerClient container, string prefix)
{
var result = new List<BlobItem>();
await foreach (var item in container.GetBlobsAsync(prefix: prefix))
{
// Skip virtual folders
if (item.Properties.BlobType != BlobType.Block)
continue;
if (HasImageExtension(item.Name))
result.Add(item);
}
// Optional: stable order by name (e.g., page_001.jpg … page_999.jpg)
result.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase));
return result;
}
private static bool HasImageExtension(string blobName)
{
string ext = Path.GetExtension(blobName) ?? string.Empty;
return ImageExts.Contains(ext, StringComparer.OrdinalIgnoreCase);
}
private static void BuildMultipageTiffFromBlobs(BlobContainerClient container, List<BlobItem> images, string outputTiffPath)
{
// TIFF encoder defaults:
// - LZW compression is a good balance of size & compatibility for RGB images.
// - 300 DPI is print-friendly; change if you need web-only output.
var tiffOptions = new TiffOptions(TiffExpectedFormat.TiffLzwRgb)
{
ResolutionSettings = new ResolutionSetting(300, 300)
};
TiffImage? tiff = null;
try
{
for (int index = 0; index < images.Count; index++)
{
var blobClient = container.GetBlobClient(images[index].Name);
Console.WriteLine($"Downloading & adding: {blobClient.Name}");
using var ms = new MemoryStream();
blobClient.DownloadTo(ms);
ms.Position = 0;
// Load the image with Aspose.Imaging (auto-detects format)
using var src = Image.Load(ms);
// Cache pixel data to speed up frame copy (especially for network streams)
if (src is RasterImage raster)
raster.CacheData();
// Create a TIFF frame by copying from the source image
// NOTE: TiffFrame.CopyFrame(tiffOptions, <RasterImage>) is preferred when available
TiffFrame frame;
if (src is RasterImage rimg)
{
frame = TiffFrame.CopyFrame(tiffOptions, rimg);
}
else
{
// Fallback: render non-raster formats into a rasterized frame
frame = CreateRasterFrameFromAny(src, tiffOptions);
}
if (index == 0)
{
// First frame defines the TiffImage
tiff = new TiffImage(frame);
}
else
{
tiff!.AddFrame(frame);
}
}
if (tiff == null)
throw new InvalidOperationException("No frames were created. Aborting.");
// Save to local TIFF file
tiff.Save(outputTiffPath);
}
finally
{
tiff?.Dispose();
}
}
private static TiffFrame CreateRasterFrameFromAny(Image src, TiffOptions opts)
{
// Create a blank frame and draw the source into it
// This is a compatibility path if the loaded image isn’t a RasterImage
var frame = new TiffFrame(opts, src.Width, src.Height);
using (var graphics = new Aspose.Imaging.Graphics(frame))
{
graphics.Clear(Aspose.Imaging.Color.White);
graphics.DrawImage(src, new Aspose.Imaging.Rectangle(0, 0, src.Width, src.Height));
}
return frame;
}
}
Per què aquestes opcions?
• Compressió :
TiffLzwRgb
dóna compressió ** sense pèrdua* i alta compatibilitat (ideal per a l’arxiu o intercanvi).Les alternatives:
TiffDeflateRgb
( Sovint més petit, necessita suport Deflate); escaneja de bilevel →TiffCcittFax4
.- El DNI *:
ResolutionSetting(300, 300)
És fàcil d’imprimir per a les escanades; triar 150 per web només per reduir la mida.
- El DNI *:
La memòria *:
RasterImage.CacheData()
Millora el rendiment perquè els píxels de font es cacheixen abans de copiar el quadre.Ordre: El sorteig dels noms de blob assegura una ordre estable de la pàgina (per exemple,
page_001…page_999
).
Descarregar l’àlbum de tornada al núvol
L’exemplar * s’envia al disc local * i immediatament * torna a carregar * utilitzant el mateix contenidor. Si el seu flux de treball ha d’evitar completament els fitxers locals, flueix el TIFF a un MemoryStream
i trucar UploadAsync
Per a àlbums molt grans, prefereix estalviar a un fitxer temporari per mantenir l’ús de la memòria previsible.
Amazon S3 variant (snippet)
Si vostè està en S3, la lògica és la mateixa - reemplaçar les trucades de SDK d’Azure amb les de AWS:
// NuGet:
// dotnet add package AWSSDK.S3
using Amazon.S3;
using Amazon.S3.Model;
// Listing:
using var s3 = new AmazonS3Client(Amazon.RegionEndpoint.APSouth1);
var list = await s3.ListObjectsV2Async(new ListObjectsV2Request
{
BucketName = "your-bucket",
Prefix = "images/"
});
foreach (var obj in list.S3Objects.Where(o => HasImageExtension(o.Key)))
{
using var get = await s3.GetObjectAsync("your-bucket", obj.Key);
using var ms = new MemoryStream();
await get.ResponseStream.CopyToAsync(ms);
ms.Position = 0;
using var src = Image.Load(ms);
// (same TiffFrame.CopyFrame logic as above)
}
Mantenir les parts Aspose.Imaging idèntiques; només canvia el codi lista / descàrrega.
Gestió d’errors i resiliència
- Container buit/prefix: l’aplicació surt gràficament amb un missatge.
- Imatge corrompuda: enrere
Image.Load
En eltry/catch
· Evitar els mals quadres i continuar, o l’avortament basat en la política. - Sets molt grans: considereu el xunking (per exemple, crear un TIFF per 1.000 imatges) per limitar les dimensions de fitxers i els límits de l’escanner / eina.
- Nom de fitxer: inclou la data/hora o prefix en el nom de sortida per a la traçabilitat (per exemple,
album-2025-07-03_1500.tiff
).
Les millors pràctiques
- Dimensions consistents: les orientacions / variacions mixtes són fines, però per a resultats uniformes pre-normalitza les imatges (escala / rotació) abans de copiar el quadre.
- Deble de color: els escans de text poden compressar millor si es converteixen a graus abans de l’assemblació de TIFF (utilitzar filtres Aspose.Imaging).
- Metadades: es pot afegir EXIF/IPTC/XMP per quadre abans d’emmagatzemar si cal.
- Testing: verifica la producció en múltiples visualitzadors (Windows Photos, IrfanView, Preview, ImageMagick) i amb consumidors de baix flux (DMS, PACS, etc.).
Conclusió
Ara vostè té un patró testat per a la construcció d’àlbums TIFF de múltiples pàgines** directament des de Azure Blob Storage (i fàcilment portable a S3). L’exemple manté l’ús de la memòria previsible, utilitza compressió LZW sense pèrdua, i estableix una pràctica 300 DPI default - preparat per al arxivament, intercanvi i impressió.
Cloneu el codi anterior al vostre projecte, connecteu-lo a la xarxa de connexió / contenidor i tindreu els àlbums TIFF de grau de producció en minuts.
More in this category
- Optimitzar els gifs animats en .NET utilitzant Aspose.Imaging
- Optimitzar TIFFs multipages per a l'arxiu en .NET amb Aspose
- Animacions de dades en .NET amb Aspose.Imaging
- Comparació Lossy vs. Lossless Image Compression en .NET utilitzant Aspose.Imaging
- Compressió d'imatge sense pèrdues i de qualitat en .NET amb Aspose.Imaging