PHP根据图片色阶自动添加水印
本实例详解如何利用PHP技术依据图片色彩层次在不同区域智能添加水印。内容旨在提供实用的参考代码,帮助开发者解决常见痛点。
在PHP开发过程中,为上传图片添加水印是保护版权和溯源的常规操作。传统做法通常将水印固定在右下角,但若原图背景色阶与水印相近,会导致水印难以辨认,影响效果。
以下代码逻辑能够自动分析图片的色阶分布,并根据色阶差异动态选择水印放置位置,从而有效规避因颜色重合造成的水印隐形问题。
<?php
function add_wm($nmw_water, $src_file, $output_file, $x, $y) {
if(file_exists($output_file))
return;
$w1 = MagickGetImageWidth($nmw_water);
$h1 = MagickGetImageHeight($nmw_water);
$nmw =NewMagickWand();
MagickReadImage($nmw, $src_file);
// 默认的加水印位置调整
$lt_w = 50;
$lt_h = 50;
if($x == 0){
$w = MagickGetImageWidth($nmw);
$h = MagickGetImageHeight($nmw);
$x = $w;
$y = $h;
}else{
// 根据具体情况调整
$lt_w = 30;
$lt_h = 40;
}
MagickCompositeImage($nmw, $nmw_water, MW_OverCompositeOp, $x - $w1 - $lt_w, $y - $h1 - $lt_h);
MagickWriteImage($nmw, $output_file);
DestroyMagickWand($nmw);
}
// 还是groovy的eachFileRecurse好用啊
function add_wm_recurse($nmw_water, $to_dir, $output_dir, $arr) {
$dp = dir($to_dir);
while($file=$dp->read()){
if($file != '.' && $file != '..'){
if(is_dir($to_dir . '/' . $file)){
mkdir($output_dir . '/' . $file);
add_wm_recurse($nmw_water, $to_dir . '/' . $file, $output_dir . '/' . $file, $arr);
}else{
if(!array_key_exists($to_dir . '/' . $file, $arr)){
continue;
}
$sub_arr = $arr[$to_dir . '/' . $file];
if($sub_arr){
$x = intval($sub_arr[0]);
$y = intval($sub_arr[1]);
add_wm($nmw_water, $to_dir . '/' . $file, $output_dir . '/' . $file, $x, $y);
}
}
}
}
$dp->close();
}
$to_dir = './resized';
$output_dir = './output';
// 这个是我用java的ImageIO遍历图片像素获取的符合裤子颜色的区域的坐标array(posX, posY)
$arr = array(
array(50, 50)
);
$water = './water.png';
$nmw_water =NewMagickWand();
MagickReadImage($nmw_water, $water);
add_wm_recurse($nmw_water, $to_dir, $output_dir, $arr);
DestroyMagickWand($nmw_water);
?>
PHP图像处理模块 MagickWand用法
附加资料:
PHP中MagickWand模块的使用指南
MagickWand作为PHP扩展,用于对接ImageMagick强大的图像处理能力。下面展示一段基于MagicWand的基础代码片段:
$magick_wand=NewMagickWand();
MagickReadImage($magick_wand,'rose.jpg');
$drawing_wand=NewDrawingWand();
DrawSetFont($drawing_wand,"/usr/share/fonts/bitstream-vera/Vera.ttf");
DrawSetFontSize($drawing_wand,20);
DrawSetGravity($drawing_wand,MW_CenterGravity);
$pixel_wand=NewPixelWand();
PixelSetColor($pixel_wand,"white");
DrawSetFillColor($drawing_wand,$pixel_wand);
if (MagickAnnotateImage($magick_wand,$drawing_wand,0,0,0,"Rose") != 0)
{
MagickEchoImageBlob( $magick_wand );
}
else
{
echo MagickGetExceptionString($magick_wand);
}
?>
环境安装步骤如下:
1. 下载适用于PHP 5.2.x版本的 php_magickwand_q16_st.dll 文件 2. 将该DLL文件放入PHP的扩展目录中 3. 在 php.ini 配置文件中添加 extension=php_magickwand_q16_st.dll 4. 重启Apache服务器以生效
希望上述关于PHP程序设计的技巧能对大家有所帮助。