跳轉到

圖片管理

ImageRegistryProcess 層管理所有圖片資源,確保同一張圖片在多頁或多份文件中只解析與嵌入一次。支援 JPEG、PNG(含透明度)、GIF(靜態)與 WebP 格式。

嵌入圖片

use NextPDF\ValueObjects\Rectangle;

// 從檔案路徑嵌入
$document->images()->place(
    path: '/path/to/company-logo.png',
    position: Rectangle::fromXY(x: 20.0, y: 20.0, width: 50.0, height: 20.0),
);

// 從位元組字串嵌入
$imageBytes = file_get_contents('https://example.com/image.jpg');
$document->images()->placeBytes(
    bytes: $imageBytes,
    mimeType: 'image/jpeg',
    position: Rectangle::fromXY(x: 20.0, y: 50.0, width: 100.0, height: 75.0),
);

支援的格式

格式 MIME 類型 特殊功能
JPEG image/jpeg 直接嵌入(不重新壓縮)、Progressive JPEG
PNG image/png 透明度(alpha 通道)、16-bit 色深
GIF image/gif 靜態幀(動畫取第一幀)
WebP image/webp 有損/無損、透明度、需 PHP 8.5 GD

圖片快取與重用

// 同一張圖片在多頁使用時,ImageRegistry 自動重用
$logoPath = '/path/to/logo.png';

// 第 1 頁頁首
$document->images()->place(
    path: $logoPath,
    position: Rectangle::fromXY(x: 20.0, y: 10.0, width: 40.0, height: 16.0),
);

$document->addPage();

// 第 2 頁頁首(使用相同快取,不重新解析)
$document->images()->place(
    path: $logoPath,
    position: Rectangle::fromXY(x: 20.0, y: 10.0, width: 40.0, height: 16.0),
);

圖片縮放與裁剪

use NextPDF\Graphics\ImageFit;
use NextPDF\ValueObjects\Rectangle;

$document->images()->place(
    path: '/path/to/photo.jpg',
    position: Rectangle::fromXY(x: 20.0, y: 50.0, width: 80.0, height: 60.0),
    fit: ImageFit::Cover,    // Cover | Contain | Fill | None
    alignment: ImageAlignment::Center,
);

圖片透明度

// PNG with alpha channel
$document->images()->place(
    path: '/path/to/watermark.png',
    position: Rectangle::fromXY(x: 50.0, y: 80.0, width: 100.0, height: 50.0),
    opacity: 0.3,  // 30% 不透明度
);

影像解析度與 DPI

use NextPDF\Graphics\ImageOptions;

$document->images()->place(
    path: '/path/to/print-ready.tiff',
    position: Rectangle::fromXY(x: 20.0, y: 50.0, width: 80.0, height: 60.0),
    options: ImageOptions::create(
        targetDpi: 300,  // 300 DPI 印刷品質
        colorSpace: ColorSpace::CMYK,
    ),
);

SVG 圖片

// SVG 透過 VectorRenderer 渲染(非點陣圖)
$document->vector()->placeSvg(
    svgPath: '/path/to/icon.svg',
    position: Rectangle::fromXY(x: 20.0, y: 50.0, width: 40.0, height: 40.0),
);

參見