前言
本系統通過 Laravel 作為前端框架接收用戶上傳的圖片,調用 Python 腳本處理水印添加,最終返回處理后的圖片。這種架構充分利用了 Laravel 的便捷性和 Python 圖像處理庫的強大功能。
一、Python 水印處理腳本
from PIL import Image, ImageEnhance
import fitz
import io
import sys
import os
import logging
import traceback# 配置日志記錄
logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s',filename='watermark_process.log'
)def compress_image(image, quality=85, max_size=(1920, 1920)):"""壓縮圖片尺寸和質量"""try:if image.size[0] > max_size[0] or image.size[1] > max_size[1]:image.thumbnail(max_size, Image.Resampling.LANCZOS)logging.info(f"圖片已壓縮至尺寸: {image.size}")return imageexcept Exception as e:logging.error(f"圖片壓縮失敗: {str(e)}")raisedef add_watermark_on_top(image_path, pdf_watermark_path, output_path):"""將水印清晰地覆蓋整個圖片"""try:logging.info(f"開始處理圖片: {image_path}")# 檢查文件是否存在if not os.path.exists(image_path):error_msg = f"找不到圖片文件: {image_path}"logging.error(error_msg)raise FileNotFoundError(error_msg)if not os.path.exists(pdf_watermark_path):error_msg = f"找不到水印文件: {pdf_watermark_path}"logging.error(error_msg)raise FileNotFoundError(error_msg)# 打開并壓縮原始圖片base_image = Image.open(image_path)logging.info(f"原始圖片格式: {base_image.format}, 尺寸: {base_image.size}")base_image = compress_image(base_image)# 打開PDF水印pdf_doc = fitz.open(pdf_watermark_path)page = pdf_doc[0]logging.info(f"PDF水印已加載,頁數: {len(pdf_doc)}")# 使用更高分辨率轉換PDF水印mat = fitz.Matrix(8, 8)watermark_pix = page.get_pixmap(matrix=mat, alpha=True)watermark_bytes = watermark_pix.tobytes("png")watermark_image = Image.open(io.BytesIO(watermark_bytes))logging.info(f"水印圖片已轉換,尺寸: {watermark_image.size}")# 確保圖片模式正確if base_image.mode != 'RGBA':base_image = base_image.convert('RGBA')logging.info("原始圖片已轉換為RGBA模式")if watermark_image.mode != 'RGBA':watermark_image = watermark_image.convert('RGBA')logging.info("水印圖片已轉換為RGBA模式")# 將水印調整為與原圖完全相同的尺寸watermark_image = watermark_image.resize(base_image.size, Image.Resampling.LANCZOS)logging.info(f"水印已調整為圖片尺寸: {base_image.size}")# 增強水印的不透明度watermark_data = list(watermark_image.getdata())enhanced_data = []for item in watermark_data:if item[3] > 0: # 如果像素不是完全透明的enhanced_data.append((item[0], item[1], item[2], min(255, int(item[3] * 2))))else:enhanced_data.append(item)watermark_image.putdata(enhanced_data)logging.info("水印不透明度已增強")# 創建新的圖層并合成result = Image.new('RGBA', base_image.size, (0,0,0,0))result.paste(base_image, (0,0))result.paste(watermark_image, (0,0), watermark_image)logging.info("圖片與水印已合成")# 確保輸出目錄存在output_dir = os.path.dirname(output_path)if not os.path.exists(output_dir):os.makedirs(output_dir, exist_ok=True)logging.info(f"創建輸出目錄: {output_dir}")# 保存結果result.save(output_path, 'PNG', quality=85, optimize=True)logging.info(f"處理后的圖片已保存至: {output_path}")# 關閉PDF文檔pdf_doc.close()return output_pathexcept Exception as e:error_msg = f"處理過程中出現錯誤:{str(e)}"logging.error(error_msg)logging.error(traceback.format_exc()) # 記錄完整的堆棧信息return Nonedef main():try:logging.info("===== 開始新的水印處理任務 =====")if len(sys.argv) != 4:error_msg = "參數數量錯誤,使用方法: python add_watermark.py 輸入圖片路徑 水印PDF路徑 輸出圖片路徑"logging.error(error_msg)print(error_msg)return 1input_image = sys.argv[1]watermark_pdf = sys.argv[2]output_image = sys.argv[3]logging.info(f"接收到命令行參數: 輸入={input_image}, 水印={watermark_pdf}, 輸出={output_image}")result = add_watermark_on_top(input_image, watermark_pdf, output_image)if result:success_msg = f"處理成功,輸出文件:{result}"logging.info(success_msg)print(success_msg)return 0else:error_msg = "處理失敗,詳情請查看日志文件"logging.error(error_msg)print(error_msg)return 1except Exception as e:logging.critical(f"程序崩潰: {str(e)}")logging.critical(traceback.format_exc())print(f"程序異常終止: {str(e)}")return 1if __name__ == "__main__":sys.exit(main())
二、Laravel 后端集成
<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;class WatermarkController extends Controller
{/*** 添加水印到圖片*/public function addWatermark(Request $request){// 驗證請求$request->validate(['image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',]);try {// 存儲上傳的圖片$imagePath = $request->file('image')->store('temp', 'public');$imageFullPath = storage_path('app/public/' . $imagePath);Log::info("圖片已上傳: {$imageFullPath}");// 水印 PDF 路徑$watermarkPdfPath = public_path('watermark.pdf');if (!file_exists($watermarkPdfPath)) {throw new \Exception("水印文件不存在: {$watermarkPdfPath}");}// 準備輸出路徑$outputFileName = 'watermarked_' . time() . '.' . $request->file('image')->extension();$outputPath = 'temp/' . $outputFileName;$outputFullPath = storage_path('app/public/' . $outputPath);// 執行 Python 腳本$pythonPath = env('PYTHON_PATH', 'python3'); // 配置 Python 路徑$scriptPath = base_path('scripts/add_watermark.py');$process = new Process([$pythonPath,$scriptPath,$imageFullPath,$watermarkPdfPath,$outputFullPath]);$process->run();// 檢查執行結果if (!$process->isSuccessful()) {Log::error("Python 腳本執行失敗: " . $process->getErrorOutput());throw new ProcessFailedException($process);}$output = $process->getOutput();Log::info("Python 腳本輸出: {$output}");// 檢查輸出文件是否存在if (!file_exists($outputFullPath)) {throw new \Exception("處理后的圖片不存在,可能 Python 腳本執行失敗");}// 返回處理后的圖片 URL$imageUrl = Storage::url($outputPath);return response()->json(['success' => true,'message' => '水印添加成功','image_url' => $imageUrl]);} catch (\Exception $e) {Log::error("添加水印失敗: " . $e->getMessage());return response()->json(['success' => false,'message' => '處理過程中出錯: ' . $e->getMessage()], 500);}}
}
三、環境配置
在 .env 文件中添加 Python 路徑配置:
PYTHON_PATH=python3 # 根據實際環境修改
四、錯誤調試指南
1. Python 腳本調試
日志文件: 查看 watermark_process.log 獲取詳細處理過程
命令行測試: 直接通過命令行執行 Python 腳本測試
python3 scripts/add_watermark.py /path/to/input.jpg /path/to/watermark.pdf /path/to/output.png
2. Laravel 調試
日志檢查: 查看 storage/logs/laravel.log
異常信息: 捕獲并記錄完整的異常堆棧
權限問題: 確保 storage 目錄可寫
Python 路徑: 確認 .env 中的 PYTHON_PATH 配置正確
3. 常見錯誤及解決方案
錯誤信息 | 可能原因 | 解決方案 |
---|---|---|
找不到圖片文件 | 文件路徑錯誤或權限不足 | 檢查文件路徑和權限 |
Python 腳本執行失敗 | Python 環境問題或依賴缺失 | 確認 Python 路徑和依賴(如 PyMuPDF、Pillow) |
處理后的圖片不存在 | Python 腳本內部錯誤 | 查看 Python 日志文件獲取詳細信息 |
五、部署注意事項
1、Python 依賴安裝:
pip install pillow pymupdf
2、文件權限設置:
chmod -R 755 storage/
chmod -R 755 bootstrap/cache/
3、Nginx 配置:確保上傳文件大小限制足夠大:
client_max_body_size 20M;
通過以上方案,你可以實現一個完整的 Laravel + Python 圖片水印系統,并具備完善的錯誤調試能力。這種架構既發揮了 Laravel 的 Web 開發優勢,又利用了 Python 在圖像處理領域的強大生態。