今日のデジタル時代では、効率的な画像処理はウェブアプリケーションおよびAPIにとって重要です 画像管理の重要な側面の1つは、ファイルサイズを大幅に損なうことなく削減するのに役立つコンプレッシャーです このガイドはアスポーズ.Imaging for .NET を使用してダイナミックな画像圧縮 API を構築することによってあなたを導きます 最終的には、画像を受け入れ、検索パラメーター(フォーマット、品質、リサイクルなど)に従って压縮された出力を返します。
Aspose.Imaging は .NET の画像で動作するための強力なライブラリであり、多くのフォーマットをサポートし、損失(JPEG)および無損(PNG)のワークフローを含む堅固な操作機能を提供します。
あなたが作るもの
- ●「終点」:
POST /api/images/compress?format=jpeg&quality=75&maxWidth=1280&maxHeight=1280
- 入力:複数のファイル(画像)、フォーマット/品質/サイズのオプション検索パラメーター
- 出力:正しい画像ストリームを圧縮
Content-Type
キャッチヘッダー - セキュリティ:コンテンツタイプの認証、サイズ制限、および保存されたデコード/エクソード
原則
- ・NET 8(または .NET 6+)
- ASP.NET Core Web API プロジェクト
- ニュージーランド:
Aspose.Imaging
- オプション:アプリスタートアップにおけるライセンスの開始(許可された構造を使用している場合)
プロジェクト構造(最小限)
/Controllers
ImageController.cs
/Services
ImageCompressionService.cs
/Models
CompressionRequest.cs
Program.cs
appsettings.json
完全例(サービス + コントローラー)
あなたのプロジェクトの名称スペースで場所所有者名空間を置き換える。
/Models/CompressionRequest.cs
namespace ImageApi.Models;
public sealed class CompressionRequest
{
// "jpeg" or "png"
public string Format { get; init; } = "jpeg";
// 1..100 (applies to JPEG only; PNG is lossless)
public int? Quality { get; init; } = 80;
// Optional resize bounds; image is resized preserving aspect ratio if either is provided.
public int? MaxWidth { get; init; }
public int? MaxHeight { get; init; }
// If true, strip metadata (EXIF, IPTC) where applicable to reduce size further.
public bool StripMetadata { get; init; } = true;
// Guardrails
public void Validate()
{
var fmt = Format?.ToLowerInvariant();
if (fmt is not "jpeg" and not "png")
throw new ArgumentException("Unsupported format. Use 'jpeg' or 'png'.");
if (Quality is { } q && (q < 1 || q > 100))
throw new ArgumentException("Quality must be between 1 and 100.");
if (MaxWidth is { } w && w <= 0) throw new ArgumentException("MaxWidth must be positive.");
if (MaxHeight is { } h && h <= 0) throw new ArgumentException("MaxHeight must be positive.");
}
}
/Services/ImageCompressionService.cs
using Aspose.Imaging;
using Aspose.Imaging.ImageOptions;
using ImageApi.Models;
namespace ImageApi.Services;
public interface IImageCompressionService
{
Task<(MemoryStream output, string contentType, string fileExt)> CompressAsync(
Stream input, CompressionRequest req, CancellationToken ct = default);
}
public sealed class ImageCompressionService : IImageCompressionService
{
private readonly ILogger<ImageCompressionService> _logger;
public ImageCompressionService(ILogger<ImageCompressionService> logger)
{
_logger = logger;
}
public async Task<(MemoryStream output, string contentType, string fileExt)> CompressAsync(
Stream input, CompressionRequest req, CancellationToken ct = default)
{
req.Validate();
// Defensive copy to a seekable stream
var inbound = new MemoryStream();
await input.CopyToAsync(inbound, ct).ConfigureAwait(false);
inbound.Position = 0;
// Load image via Aspose.Imaging
using var image = Image.Load(inbound);
// Optional: strip metadata (where applicable)
if (req.StripMetadata)
{
TryStripMetadata(image);
}
// Optional resize (preserve aspect ratio)
if (req.MaxWidth.HasValue || req.MaxHeight.HasValue)
{
ResizeInPlace(image, req.MaxWidth, req.MaxHeight);
}
// Choose encoder and options
string fmt = req.Format.ToLowerInvariant();
var (options, contentType, ext) = BuildOptions(fmt, req.Quality);
// Save to output
var output = new MemoryStream();
image.Save(output, options);
output.Position = 0;
_logger.LogInformation("Compressed image to {Bytes} bytes as {Ext}", output.Length, ext);
return (output, contentType, ext);
}
private static void ResizeInPlace(Image image, int? maxW, int? maxH)
{
var w = image.Width;
var h = image.Height;
double scaleW = maxW.HasValue ? (double)maxW.Value / w : 1.0;
double scaleH = maxH.HasValue ? (double)maxH.Value / h : 1.0;
double scale = Math.Min(scaleW, scaleH);
if (scale < 1.0)
{
int newW = Math.Max(1, (int)Math.Round(w * scale));
int newH = Math.Max(1, (int)Math.Round(h * scale));
image.Resize(newW, newH);
}
}
private static (ImageOptionsBase options, string contentType, string ext) BuildOptions(string fmt, int? quality)
{
switch (fmt)
{
case "jpeg":
{
var q = quality ?? 80;
var jpeg = new JpegOptions { Quality = q };
return (jpeg, "image/jpeg", "jpg");
}
case "png":
{
// PNG is lossless; using defaults ensures broad compatibility.
// Many PNG tunables exist, but defaults are safe and effective.
var png = new PngOptions();
return (png, "image/png", "png");
}
default:
throw new ArgumentOutOfRangeException(nameof(fmt), "Unsupported format.");
}
}
private static void TryStripMetadata(Image image)
{
try
{
// Not every format exposes EXIF/IPTC the same way; a best-effort clear:
if (image is RasterImage raster)
{
raster.RemoveAllFonts();
raster.SetPropertyItems(Array.Empty<PropertyItem>());
}
}
catch
{
// Non-fatal; ignore if format doesn't support these operations
}
}
}
Notes
JpegOptions.Quality
(1〜100)損失圧縮を制御します。- PNG デフォルトは通常、最初のバージョンのためのフィンです; あなたがより小さなPNGを必要とする場合は、後で高度なトゥニングを追加することができます。
TryStripMetadata
最善のアプローチであり、メタデータはソース形式によって異なります。
/Controllers/ImageController.cs
using ImageApi.Models;
using ImageApi.Services;
using Microsoft.AspNetCore.Mvc;
namespace ImageApi.Controllers;
[ApiController]
[Route("api/images")]
public sealed class ImageController : ControllerBase
{
private static readonly HashSet<string> AllowedContentTypes = new(StringComparer.OrdinalIgnoreCase)
{
"image/jpeg", "image/png", "image/gif", "image/webp", "image/bmp", "image/tiff"
};
private readonly IImageCompressionService _svc;
private readonly ILogger<ImageController> _logger;
public ImageController(IImageCompressionService svc, ILogger<ImageController> logger)
{
_svc = svc;
_logger = logger;
}
// POST /api/images/compress?format=jpeg&quality=75&maxWidth=1280&maxHeight=1280
[HttpPost("compress")]
[RequestSizeLimit(25_000_000)] // 25 MB cap; adjust to your needs
public async Task<IActionResult> Compress(
[FromQuery] string? format,
[FromQuery] int? quality,
[FromQuery] int? maxWidth,
[FromQuery] int? maxHeight,
[FromQuery] bool stripMetadata = true,
IFormFile? file = null,
CancellationToken ct = default)
{
if (file is null || file.Length == 0)
return BadRequest("No file uploaded.");
if (!AllowedContentTypes.Contains(file.ContentType))
return BadRequest("Unsupported content type. Upload a common raster image (JPEG, PNG, GIF, WebP, BMP, TIFF).");
var req = new CompressionRequest
{
Format = string.IsNullOrWhiteSpace(format) ? "jpeg" : format!,
Quality = quality,
MaxWidth = maxWidth,
MaxHeight = maxHeight,
StripMetadata = stripMetadata
};
await using var input = file.OpenReadStream();
var (output, contentType, ext) = await _svc.CompressAsync(input, req, ct);
// Strong caching for immutable responses (tune for your app/CDN)
Response.Headers.CacheControl = "public,max-age=31536000,immutable";
return File(output, contentType, fileDownloadName: BuildDownloadName(file.FileName, ext));
}
private static string BuildDownloadName(string originalName, string newExt)
{
var baseName = Path.GetFileNameWithoutExtension(originalName);
return $"{baseName}-compressed.{newExt}";
}
}
Program.cs
(DI登録 + オプションライセンス)
using Aspose.Imaging;
using ImageApi.Services;
var builder = WebApplication.CreateBuilder(args);
// Optional: initialize Aspose license from a file or stream if you have one
// var license = new Aspose.Imaging.License();
// license.SetLicense("Aspose.Total.lic");
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<IImageCompressionService, ImageCompressionService>();
var app = builder.Build();
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
// Enable for local testing
app.UseSwagger();
app.UseSwaggerUI();
app.Run();
ステップ・ステップ・ガイド
ステップ1:プロジェクトの設定
ASP.NET Core Web API プロジェクトを作成します。 Aspose.Imaging
パッケージを作成する Models
, Services
, そして Controllers
上記のようにフォルダー。
ステップ2:設定 Aspose.Imaging (オプションライセンス)
ライセンスを持っている場合は、スタートアップで開始してください(参照) Program.cs
)これは評価水標を避け、完全な機能を確保します。
ステップ3:圧縮サービスの実施
The ImageCompressionService
:
- 画像をアップロードする
Image.Load(Stream)
- メタデータをストリップする
- オプションで再生する側面比率保存
- JPEGまたはPNGに節約し、フォーマットに適したオプション
ステップ4:APIコントローラーを構築する
ImageController
展示 POST /api/images/compress
ファイルとリクエストパラメーター:
format
:jpeg
またはpng
(デフォルト)jpeg
)quality
1~100(JPEGのみ、デフォルト80)maxWidth
/maxHeight
: ダウンスカリングのための制限stripMetadata
●デフォルトtrue
小さな生産量
ステップ5: API をテスト
すべての HTTP クライアントを使用して送信する multipart/form-data
単一のファイルフィールドが名付けられています。 file
, plus optional query parameters. 確認する:
- Response
Content-Type
試合形式 - 返品ファイルサイズが減少します。
- 予想通り作業を再開
デザインの選択と最良の実践
- フォーマットの設定:JPEGを使用する
Quality
PNGは予測可能な生産に損失がない。 - ダウンスケールを暗号化する前に:リサイクルは、ピクセルを最初に減少させます(最大サイズの勝ち点)、その後、スクリングバイトをさらに短縮します。
- Sanitize inputs:保存コンテンツタイプ、ファイルサイズ、リクエスト制限。
- ストリーミング:全ファイルを繰り返しメモリに読み取るのを避け、流れを短寿と検索可能に保ちます。
- キャッシング: 特定の入力から名前/コンテンツを引き出した場合、変更のない回答をマークします。
- セキュリティ:コンテンツのタイプを確認し、疑わしい支払いを拒否します。
- 可視性:前/後の記録サイズと使用されたパラメーター; これはデフォルトを調整するのに役立ちます。
- トロトリング:公に暴露された場合、利率制限または悪用を防ぐために auth を要求します。
一般的な拡張子(後でダウンロード)
- WebP/AVIFの暗号化は、さらに小さな画像(新しいオプションを追加する)
contentType
/ ファイル拡張BuildOptions
). - PNGトゥニング(フィルタリング/圧縮レベル)は、過小損失のない資産が必要な場合。
- プロフィールを設定する
thumbnail
,preview
,hires
知られているパラメーターをマッピングする。 - ETagsまたはコンテンツハッシングは、キャッシュから同じ回答を提供します。
- Async batch endpoint 複数のファイルを同時に圧縮します。
Troubleshooting
- 大入力:増加
RequestSizeLimit
あるいはテムストレージに流れる。 - Wrong Colors: 確保色スペースはデフォルトで処理されます; 高度なケースは明確な色タイプを必要とする可能性があります。
- サイズ減少(PNG): PNG は無損で、より強力なバイト節約のためにリサイクルまたは JPEG に切り替えることができます。
概要
コントローラーはアップロードとパラメーターを処理します; サービスは安全で、フォーマット意識の圧縮とオプションのリサイクルを適用し、カッシュヘッダーで適切にタップされた反応を返します。 ここから、あなたはあなたのウェブスタックに合うために、より多くの形式、プレセット、およびキャッシュ戦略を追加することができます。