核心邏輯
- 預先分析目標圖片(如褲子產品圖),提取特定顏色區域(如深藍牛仔布)的座標陣列
[(x,y), ...]。
- 水印疊加時,根據傳入座標動態計算水印右下角偏移量,避開主體、落在背景區域。
- 批量處理支援遞歸目錄遍歷,配置映射表指定每張圖的最佳座標。
基於 ImageMagick (imagick 擴展) 實現
<?php
function addWatermark($waterWand, $srcPath, $outPath, $targetX, $targetY) {
if (file_exists($outPath)) return;
$wW = $waterWand->getImageWidth();
$wH = $waterWand->getImageHeight();
$wand = new Imagick($srcPath);
$imgW = $wand->getImageWidth();
$imgH = $wand->getImageHeight();
// 預設右下角內邊距
$padX = 50; $padY = 50;
if ($targetX == 0 && $targetY == 0) {
// 未提供座標,使用圖片右下角
$targetX = $imgW;
$targetY = $imgH;
} else {
// 提供座標時縮小邊距
$padX = 30; $padY = 40;
}
$dstX = $targetX - $wW - $padX;
$dstY = $targetY - $wH - $padY;
$wand->compositeImage($waterWand, Imagick::COMPOSITE_OVER, $dstX, $dstY);
$wand->writeImage($outPath);
$wand->destroy();
}
// 遞歸批量處理
function batchWatermark($waterWand, $srcDir, $outDir, array $coordMap) {
$dir = new DirectoryIterator($srcDir);
foreach ($dir as $file) {
if ($file->isDot()) continue;
$srcPath = $file->getPathname();
$relPath = substr($srcPath, strlen($srcDir) + 1);
$outPath = $outDir . DIRECTORY_SEPARATOR . $relPath;
if ($file->isDir()) {
@mkdir($outPath);
batchWatermark($waterWand, $srcPath, $outPath, $coordMap);
} elseif (isset($coordMap[$srcPath])) {
[$x, $y] = $coordMap[$srcPath];
addWatermark($waterWand, $srcPath, $outPath, (int)$x, (int)$y);
}
}
}
// 使用示例
$water = new Imagick('water.png');
$coordMap = [
'resized/pants1.jpg' => [320, 480],
'resized/pants2.jpg' => [280, 450],
];
batchWatermark($water, 'resized', 'output', $coordMap);
$water->destroy();
?>
座標獲取方案
- 離線腳本:Python/OpenCV 或 Java ImageIO 掃描像素,輸出目標顏色區域質心座標 JSON。
- 線上即時:前端 Canvas 讓用戶點選位置,回傳座標存儲。
優勢
- 避免水印遮擋產品關鍵細節(Logo、紋理、標籤)。
- 批量處理數萬張電商圖,人工成本趨近零。
- ImageMagick 支援 CMYK、高位深、大尺寸圖,生產級可靠。