给自己网站上的图片添加水印,在图片上留下属于自己的信息,这有两个好处:一是宣传自己的品牌,二是就算带图片的文章被转载了,也会自动的留下了版权。
本文主要实现了php图片上传自动给图片加水印,在下篇中我会给出用php添加文字水印的代码。
php给图片加水印其实很简单,没有想象的那么神奇,就是利用了php里面的一个GD库。说起GD库,其实就是php里面一个专门用于处理图片有关的扩展,比如我们熟悉的验证码、生成缩略图,包括今天所说的php给图片加水印都是要有GD库的支持。
提示:新安装的php环境,可能需要开启GD库,开启方法:打开php.ini,去掉extension=php_gd2.dll前面的“;”然后重启apache/iis即可。
实现并不复杂,核心代码还不到20行,主要是掌握几个函数就行了。
实现源码:
<?php $ori_img = "images/13801220684507.jpg"; //原图 $water_img = "logo.png"; //水印 $new_img = "images/daixiaorui.jpg"; //生成水印后的图片 $original = getimagesize($ori_img); //得到图片的信息,可以print_r($original)发现它就是一个数组 $watermark = getimagesize($water_img); $s_original = imgCreateFrom($ori_img, $original[2]); //$original[2]是图片类型,其中1表示gif、2表示jpg、3表示png $s_watermark = imgCreateFrom($water_img, $watermark[2]); $posX = $original[0] - $watermark[0] - 6; //X坐标(右下角) $poxY = $original[1] - $watermark[1] - 3; //Y坐标(右下角) //打水印 imagecopy($s_original, $s_watermark, $posX, $poxY, 0, 0, $watermark[0], $watermark[1]); //header("Content-type:image/jpeg"); //imagejpeg($s_original); //向浏览器输出图片 $loop = imagejpeg($s_original, $new_img); //生成新的图片(jpg格式),如果用imagepng可以生成png格式 if ($loop) { echo "水印添加成功!"; } //根据文件类型 创建一个新图象 function imgCreateFrom($img_src, $val) { switch ($val) { case 1: $img = imagecreatefromgif($img_src); break; case 2: $img = imagecreatefromjpeg($img_src); break; case 3: $img = imagecreatefrompng($img_src); break; } return $img; } ?>
给图片添加水印除了用基础的GD库实现,其实还可以ImageMagick这个工具,它的功能更强大,不过一般没多大需求,就用上面这个代码了。
永久地址:
转载随意~请带上教程地址吧^^

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software