本文目录导读:

我来帮你详细介绍PHP项目中的水印和指纹技术实现。
图片水印处理
文字水印
<?php
class ImageWatermark {
/**
* 添加文字水印
* @param string $source 原图路径
* @param string $text 水印文字
* @param array $options 配置选项
* @return string 处理后的图片路径
*/
public function addTextWatermark($source, $text, $options = []) {
$defaults = [
'output' => null,
'font' => './fonts/arial.ttf',
'fontSize' => 20,
'angle' => 0,
'x' => 10,
'y' => 10,
'color' => [255, 255, 255],
'opacity' => 50
];
$options = array_merge($defaults, $options);
// 创建图片资源
$imageInfo = getimagesize($source);
$mime = $imageInfo['mime'];
switch($mime) {
case 'image/jpeg':
$im = imagecreatefromjpeg($source);
break;
case 'image/png':
$im = imagecreatefrompng($source);
break;
case 'image/gif':
$im = imagecreatefromgif($source);
break;
default:
throw new Exception('不支持的图片格式');
}
// 创建颜色
$color = imagecolorallocatealpha(
$im,
$options['color'][0],
$options['color'][1],
$options['color'][2],
$options['opacity']
);
// 添加水印文字
imagettftext(
$im,
$options['fontSize'],
$options['angle'],
$options['x'],
$options['y'],
$color,
$options['font'],
$text
);
// 输出或保存
$output = $options['output'] ?: $source;
$this->saveImage($im, $output, $mime);
imagedestroy($im);
return $output;
}
}
图片水印(Logo)
<?php
class ImageLogoWatermark {
/**
* 添加图片水印
* @param string $source 原图
* @param string $watermark 水印图片
* @param string $position 位置 (center/top-left/top-right/bottom-left/bottom-right)
*/
public function addImageWatermark($source, $watermark, $position = 'bottom-right') {
// 获取图片信息
$sourceInfo = getimagesize($source);
$watermarkInfo = getimagesize($watermark);
// 创建图片资源
$sourceImg = $this->createImageFromFile($source);
$watermarkImg = $this->createImageFromFile($watermark);
// 计算水印位置
$positions = [
'center' => [
'x' => ($sourceInfo[0] - $watermarkInfo[0]) / 2,
'y' => ($sourceInfo[1] - $watermarkInfo[1]) / 2
],
'top-left' => ['x' => 10, 'y' => 10],
'top-right' => ['x' => $sourceInfo[0] - $watermarkInfo[0] - 10, 'y' => 10],
'bottom-left' => ['x' => 10, 'y' => $sourceInfo[1] - $watermarkInfo[1] - 10],
'bottom-right' => [
'x' => $sourceInfo[0] - $watermarkInfo[0] - 10,
'y' => $sourceInfo[1] - $watermarkInfo[1] - 10
]
];
$pos = $positions[$position] ?? $positions['bottom-right'];
// 合并图片
imagecopy(
$sourceImg,
$watermarkImg,
$pos['x'],
$pos['y'],
0,
0,
$watermarkInfo[0],
$watermarkInfo[1]
);
// 保存
$this->saveImage($sourceImg, $source, $sourceInfo['mime']);
imagedestroy($sourceImg);
imagedestroy($watermarkImg);
}
private function createImageFromFile($file) {
$info = getimagesize($file);
switch($info['mime']) {
case 'image/jpeg':
return imagecreatefromjpeg($file);
case 'image/png':
return imagecreatefrompng($file);
case 'image/gif':
return imagecreatefromgif($file);
}
}
}
数字指纹技术
文件指纹(哈希)
<?php
class FileFingerprint {
/**
* 计算文件指纹
*/
public static function generateFileFingerprint($filePath) {
if (!file_exists($filePath)) {
throw new Exception('文件不存在');
}
return [
'md5' => md5_file($filePath),
'sha1' => sha1_file($filePath),
'sha256' => hash_file('sha256', $filePath),
'crc32' => hash_file('crc32', $filePath),
'size' => filesize($filePath),
'created_at' => filectime($filePath),
'modified_at' => filemtime($filePath)
];
}
/**
* 验证文件完整性
*/
public static function verifyFileIntegrity($filePath, $expectedHash, $algorithm = 'md5') {
$actualHash = hash_file($algorithm, $filePath);
return hash_equals($expectedHash, $actualHash);
}
}
图片感知哈希(pHash)
<?php
class ImagePerceptualHash {
/**
* 计算图片感知哈希
*/
public static function calculatePerceptualHash($imagePath) {
// 缩小图片到8x8
$img = imagecreatefromstring(file_get_contents($imagePath));
$img = imagescale($img, 8, 8);
// 转换为灰度
imagefilter($img, IMG_FILTER_GRAYSCALE);
// 计算平均颜色值
$pixels = [];
$total = 0;
for ($y = 0; $y < 8; $y++) {
for ($x = 0; $x < 8; $x++) {
$color = imagecolorat($img, $x, $y);
$gray = ($color >> 16) & 0xFF;
$pixels[] = $gray;
$total += $gray;
}
}
$average = $total / 64;
// 生成哈希
$hash = '';
foreach ($pixels as $pixel) {
$hash .= ($pixel >= $average) ? '1' : '0';
}
imagedestroy($img);
return $hash;
}
/**
* 比较两个感知哈希的相似度
*/
public static function compareHashes($hash1, $hash2) {
$distance = 0;
$len = strlen($hash1);
for ($i = 0; $i < $len; $i++) {
if ($hash1[$i] !== $hash2[$i]) {
$distance++;
}
}
return [
'distance' => $distance,
'similarity' => (1 - $distance / $len) * 100
];
}
}
高级水印系统
批量水印处理
<?php
class BatchWatermarkProcessor {
private $watermark;
private $config;
public function __construct($watermark, $config = []) {
$this->watermark = $watermark;
$this->config = $config;
}
/**
* 批量处理文件夹中的图片
*/
public function processDirectory($inputDir, $outputDir, $pattern = '*.*') {
if (!is_dir($outputDir)) {
mkdir($outputDir, 0755, true);
}
$files = glob($inputDir . '/' . $pattern);
$processed = [];
foreach ($files as $file) {
if (is_file($file) && $this->isImage($file)) {
$outputPath = $outputDir . '/' . basename($file);
try {
$result = $this->processSingleImage($file, $outputPath);
$processed[] = [
'source' => $file,
'output' => $outputPath,
'status' => 'success',
'size_before' => filesize($file),
'size_after' => filesize($outputPath)
];
} catch (Exception $e) {
$processed[] = [
'source' => $file,
'status' => 'error',
'message' => $e->getMessage()
];
}
}
}
return $processed;
}
private function isImage($file) {
$extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
return in_array($ext, $extensions);
}
private function processSingleImage($source, $output) {
// 实现具体的水印处理逻辑
// 可以复用之前的文字水印或图片水印类
}
}
动态水印生成
<?php
class DynamicWatermarkGenerator {
/**
* 生成基于用户信息的动态水印
*/
public static function generateUserWatermark($userId, $username, $timestamp) {
$watermarkData = [
'user_id' => $userId,
'username' => $username,
'timestamp' => $timestamp,
'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
'hash' => self::generateSignature($userId, $username, $timestamp)
];
// 生成水印文本
$text = sprintf(
"用户: %s\n时间: %s\nIP: %s",
$watermarkData['username'],
date('Y-m-d H:i:s', $watermarkData['timestamp']),
$watermarkData['ip']
);
return $text;
}
/**
* 生成验证签名
*/
private static function generateSignature($userId, $username, $timestamp) {
$secretKey = 'your-secret-key';
$data = $userId . $username . $timestamp . $secretKey;
return hash_hmac('sha256', $data, $secretKey);
}
}
水印检测与验证
水印检测
<?php
class WatermarkDetector {
/**
* 检测图片是否包含水印
*/
public static function detectWatermark($imagePath, $referenceWatermark) {
// 提取图片特征
$features = self::extractFeatures($imagePath);
// 计算与参考水印的相似度
$similarity = self::calculateSimilarity($features, $referenceWatermark);
return [
'has_watermark' => $similarity > 0.8,
'similarity' => $similarity,
'position' => self::detectPosition($features)
];
}
private static function extractFeatures($imagePath) {
// 实现特征提取逻辑
// 例如边缘检测、颜色直方图等
}
private static function calculateSimilarity($features1, $features2) {
// 计算特征相似度
}
private static function detectPosition($features) {
// 检测水印位置
}
}
水印去除检测
<?php
class WatermarkTamperDetector {
/**
* 检测水印是否被篡改
*/
public static function checkTampering($originalFile, $suspiciousFile) {
// 比较文件指纹
$originalHash = FileFingerprint::generateFileFingerprint($originalFile);
$suspiciousHash = FileFingerprint::generateFileFingerprint($suspiciousFile);
// 感知哈希比较
$phash1 = ImagePerceptualHash::calculatePerceptualHash($originalFile);
$phash2 = ImagePerceptualHash::calculatePerceptualHash($suspiciousFile);
$phashComparison = ImagePerceptualHash::compareHashes($phash1, $phash2);
return [
'tampered' => $phashComparison['similarity'] < 95,
'hash_matched' => $originalHash['md5'] === $suspiciousHash['md5'],
'phash_similarity' => $phashComparison['similarity'],
'details' => [
'original' => $originalHash,
'suspicious' => $suspiciousHash
]
];
}
}
使用示例
<?php
// 1. 添加文字水印
$watermark = new ImageWatermark();
$result = $watermark->addTextWatermark(
'image.jpg',
'© 2024 Your Company',
['fontSize' => 30, 'opacity' => 30]
);
// 2. 计算文件指纹
$fingerprint = FileFingerprint::generateFileFingerprint('document.pdf');
// 3. 图片相似度检测
$phash1 = ImagePerceptualHash::calculatePerceptualHash('image1.jpg');
$phash2 = ImagePerceptualHash::calculatePerceptualHash('image2.jpg');
$comparison = ImagePerceptualHash::compareHashes($phash1, $phash2);
echo "相似度: " . $comparison['similarity'] . "%";
// 4. 批量处理
$batchProcessor = new BatchWatermarkProcessor('watermark.png');
$results = $batchProcessor->processDirectory('images/', 'watermarked/');
这些实现提供了完整的水印和指纹功能,可以根据项目需求进行定制和扩展。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播