PHP - 图片上传并添加莫尔斯密码水印(终版)

  • 支持图片上传功能。
  • 支持上传文件类型判断功能。
  • 支持图片删除功能。
  • 支持删除提示功能。
  • 支持遍历目录文件功能。
  • 支持莫尔斯密码水印。
  • demo

index.php

<?php
include('morsecode.php');//加载莫尔斯密码
include('dir.php');//加载遍历文件方法
$conn=@mysql_connect("localhost","root","root")  or die(mysql_error());  
@mysql_select_db('uploadimg',$conn) or die(mysql_error());  
$action = isset($_REQUEST['action'])? $_REQUEST['action'] : '';//判断action
if($action=='add'){//上传图片操作
    if (!is_dir("./upload")){//存储目录判断
        mkdir("./upload");
    } elseif (!is_dir("./afterupload")){
        mkdir("./afterupload");
    }
    $beforeName = $_FILES['photo']['name'];//原始图片文件名
    $afterName = "after".$_FILES['photo']['name'];//水印图片文件名
    $tmpName = $_FILES['photo']['tmp_name'];//缓存文件
    $beforeUrl = "./upload/";//原始图片路径
    $afterUrl = "./afterupload/";//原始图片路径
    $fileType = $_FILES['photo']['type'];//上传文件类型
    if(!(strpos("@$fileType","image")) > 0){//判断是否为图片
            echo "<script>alert('文件类型错误,请上传 jpg 或 png 格式文件!')</script>";
            echo "<script>window.location.href='index.php'</script>";
    }elseif(!file_exists("$beforeUrl"."$beforeName")){//原始图片操作
        move_uploaded_file($tmpName,"$beforeUrl"."$beforeName");
    }else{
        echo "<script>alert('该文件已存在或文件名重复!')</script>";
        echo "<script>window.location.href='index.php'</script>";
    }
    if (!file_exists("$afterUrl"."$afterName")){//水印图片操作
        $time = time();//当前时间
        $morseTime = morse_encode($time);//对时间进行莫斯加密
        $morseName = morse_encode($beforeName);//对文件名进行莫斯加密
        $src = "$beforeUrl"."$beforeName";
        //获取图片信息  
        $info = getimagesize($src);  
        //通过编号获取图像类型  
        $type = image_type_to_extension($info[2],false);  
        //在内存中创建和图像类型一样的图像  
        $fun = "imagecreatefrom".$type;  
        //图片复制到内存  
        $image = $fun($src);  
        //设置字体的路径  
        $font = "./font/arial.ttf";  
        //设置字体颜色和透明度
        $color = imagecolorallocatealpha($image, 0, 0, 0, 0);
        //(文件资源,红,绿,蓝,透明度)
        //(文件资源,字体尺寸,字体角度,x坐标,y坐标,字体颜色,字体类型,内容)
        $fontContent = "shuiyin";//文字水印
        $nameContent = "$morseName";//莫斯文件名水印
        $timeContent = "$morseTime";//莫斯时间水印
        imagettftext($image, 10, 0, 20, 20, $color, $font, $fontContent);//添加文字水印
        imagettftext($image, 10, 0, 20, 50, $color, $font, $nameContent);//添加莫斯文件名水印
        imagettftext($image, 10, 0, 20, 80, $color, $font, $timeContent);//添加莫斯时间密码水印
        $fun = "image".$type;  
        //保存水印图片  
        $fun($image,"$afterUrl"."$afterName");
        $name = $beforeName;
        $type = $_FILES['photo']['type'];
        $url = "$beforeUrl"."$beforeName";
        $afterurl = "$afterUrl"."$afterName";
        $time = $time;
        $sqlstradd = "insert into photo(name,morsename,type,time,morsetime,url,afterurl) values('".$name."','".$morseName."','".$type."','".$time."','".$morseTime."','".$url."','".$afterurl."')";  
        @mysql_query($sqlstradd) or die(mysql_error());
        header('location:index.php');
    }
}elseif($action =='del'){//删除图片操作
    $delId = $_REQUEST['id'];//获取删除数据id
    $delName = $_REQUEST['name'];//获取删除图片名称
    $sqlstrdel = "delete from photo where id in (".$delId.")";
    $unlink = unlink("./upload/".$delName);//删除服务器端原始图片
    $unlink = unlink("./afterupload/after".$delName);//删除服务器端水印图片
    @mysql_query($sqlstrdel) or die(mysql_error());
    $delResult = mysql_query($sqlstrdel);
    if($delResult){
        echo "<script>alert('删除成功!')</script>";
        echo "<script>window.location.href='index.php'</script>";
    }else{
        echo "<script>alert('删除失败!')</script>";
        echo "<script>window.location.href='index.php'</script>";
    }
}else{  
//显示图片列表及上传表单
?>  
<!DOCTYPE>  
<html>  
<head>  
<meta http-equiv="content-type" content="text/html; charset=utf-8">  
<title>图片操作功能</title>
<style>
body {
    text-align: center;
}
.submit {
    position: fixed;
    right: 10px;
    top: 10px;
    padding: 0;
    margin: 0;
    border: 1px solid black;
    width: 400px;
}
.img {
    width: 90%;
    padding: 5px;
}
.list {
    border: 0px solid black;
    padding: 0;
    margin-bottom: 20px;
}
table,tr,td {
    border: 1px solid black;
    margin: 0;
    padding: 0;
}
table {
    width: 800px;
}
.one,.two {
    width: 400px;
}
.uploadimg, .afteruploadimg {
    width: 400px;
}
img {
    margin: 5px;
    box-shadow: 2px 2px 1px #000,-2px -2px 1px #000,2px -2px 1px #000,-2px 2px 1px #000;
}
#localImag {
    position: relative;
    width: 200px;
    margin: 0 auto;
}
a {
    text-decoration: none;
}
li {
    list-style-type: none;
    margin: 0 -35px;
    padding: 0;
}
</style>
</head>
<body>
<div class="submit">   
<form name="form" method="post" action="index.php" enctype="multipart/form-data">  
    <p>图片:<input type="file" name="photo" id="file" onchange="javascript:setImagePreview();"></p>
    <div id="localImag">
        <img id="preview" width=-1 height=-1 style="diplay:none" />
    </div>
<script>  
function setImagePreview()   
{  
        var docObj = document.getElementById("file");   
        var imgObjPreview = document.getElementById("preview");  
        if(docObj.files && docObj.files[0])  
        {  
            //火狐下,直接设img属性  
            imgObjPreview.style.display = 'block';  
            imgObjPreview.style.width = '200px';  
            //imgObjPreview.style.height = '200px';                      
            //imgObjPreview.src = docObj.files[0].getAsDataURL();  
            //火狐7以上版本不能用上面的getAsDataURL()方式获取,需要以下方式    
            imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);  
        }  
        else  
        {  
            //IE下,使用滤镜  
            docObj.select();  
            var imgSrc = document.selection.createRange().text;  
            var localImagId = document.getElementById("localImag");  
            //必须设置初始大小  
            localImagId.style.width = "300px";  
            localImagId.style.height = "120px";  
            //图片异常的捕捉,防止用户修改后缀来伪造图片  
            try  
            {  
                localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";  
                localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;  
            }  
            catch(e)  
            {  
                alert("您上传的图片格式不正确,请重新选择!");  
                return false;  
            }  
                imgObjPreview.style.display = 'none';  
                document.selection.empty();  
         }  
         return true;  
 }  
</script>
    <p>
        <input type="hidden" name="action" value="add">
        <input type="submit" name="submit" value="提交">
    </p>  
</form>
<hr>
<h1>莫斯密码对照表</h1>
<img class="img" src="./img/morse.jpg"/>
<hr>
<h1>原始图片目录</h1>
<ul>
    <?php rmdi_r("./upload");?>
</ul>
<hr>
<h1>水印图片目录</h1>
<ul>
    <?php
        rmdi_r("./afterupload");
    ?>
</ul>
</div>
<?php  
    $sqlstr = "select * from photo order by id asc";  
    $query = mysql_query($sqlstr) or die(mysql_error());  
    $result = array();  
    while($thread = mysql_fetch_assoc($query)){  
        $result[] = $thread;
    }
    if(empty($result)){
        echo "<h1>没有数据</h1>";
    }else{
foreach($result as $key => $val){
$key = $key+1;
$uploadTime = date("Y-m-d H:i:s", $val['time']);
echo <<<EOF
<div class="list">
    <table>
        <tr>
            <td class="one">序号:{$key}</td>
            <td class="two">文件id:{$val['id']}</td>
        </tr>
        <tr>
            <td>
                <ul>
                    <li>文件名</li>
                    <li>{$val['name']}</li>
                </ul>
            </td>
            <td>
                <ul>
                    <li>莫斯文件名密码</li>
                    <li>{$val['morsename']}</li>
                </ul>
            </td>
        </tr>
        <tr>
            <td>
                <ul>
                    <li>上传时间</li>
                    <li>{$uploadTime}</li>
                </ul>
            </td>
            <td>
                <ul>
                    <li>莫斯时间密码</li>
                    <li>{$val['morsetime']}</li>
                </ul>
            </td>
        </tr>
        <tr>
            <td>原始图</td>
            <td>水印图</td>
        </tr>
        <tr>
            <td><img class="uploadimg" src="{$val['url']}"/></td>
            <td><img class="afteruploadimg" src="{$val['afterurl']}"/></td>
        </tr>
        <tr>
            <td><a href="../uploadimg/upload/{$val['name']}" target="_blank"><b>下载</b></a></td>
            <td><a href="?action=del&id={$val['id']}&name={$val['name']}" onclick="if(confirm('确实要删除数据吗?')) return true;else return false;"><b>删除</b></a></td>
        </tr>
    </table>
</div>
EOF;
    }
}
?>
</body>  
</html>  
<?php  
}  
?>

morsecode.php

<?php
function morse_encode($string)//加密
{
    $strlength = strlen($string);//字符串长度
    $string = strtoupper($string);//转换为大写
    $i = 0;
    $search = array(
            ' ','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
            'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3',
            '4', '5', '6', '7', '8', '9', '.', ',', '?', '\'',
            '!', '/', '(', ')', '&', ':', ';', '=', '-', '_',
            '"', '$', '@'
            );
    $replace = array(
            '  ','�* ', '*��� ', '*�*� ', '*�� ', '� ', '��*� ', '**� ', '���� ', '�� ', '�*** ',
            '*�* ', '�*�� ', '** ', '*� ', '*** ', '�**� ', '**�* ', '�*� ', '��� ', '* ',
            '��* ', '���* ', '�** ', '*��* ', '*�** ', '**�� ', '***** ', '�**** ', '��*** ', '���** ',
            '����* ', '����� ', '*���� ', '**��� ', '***�� ', '****� ', '�*�*�* ', '**��** ', '��**�� ', '�****� ',
            '*�*�** ', '*��*� ', '*�**� ', '*�**�* ', '�*���* ', '***��� ', '*�*�*� ', '*���* ', '*����* ', '��** �* ', '�*��*� ', '���*��* ', '�**�*� '
            );
    $string = str_replace($search, $replace, $string);//(要查找的值,替换的值,要搜索的字符)
    $string = str_replace('*', '-', $string);
    $string = str_replace('�', '.', $string);
    return $string;
}
function morse_decode($string)//解密
{
    $string .= ' ';
    $array['0'] = '----- ';
    $array['1'] = '.---- ';
    $array['2'] = '..--- ';
    $array['3'] = '...-- ';
    $array['-'] = '-....- ';
    $array['4'] = '....- ';
    $array['5'] = '..... ';
    $array['6'] = '-.... ';
    $array['7'] = '--... ';
    $array['8'] = '---.. ';
    $array['\''] = '.----. ';
    $array['9'] = '----. ';
    $array['B'] = '-... ';
    $array[';'] = '-.-.-. ';
    $array['@'] = '.--.-. ';
    $array['C'] = '-.-. ';
    $array['"'] = '.-..-. ';
    $array['/'] = '-..-. ';
    $array['F'] = '..-. ';
    $array['('] = '-.--. ';
    $array['P'] = '.--. ';
    $array['G'] = '--. ';
    $array['H'] = '.... ';
    $array['J'] = '.--- ';
    $array[')'] = '-.--.- ';
    $array['Q'] = '--.- ';
    $array['.'] = '.-.-.- ';
    $array['K'] = '-.- ';
    $array['L'] = '.-.. ';
    $array['?'] = '..--.. ';
    $array['Z'] = '--.. ';
    $array['D'] = '-.. ';
    $array[':'] = '---... ';
    $array['S'] = '... ';
    $array['I'] = '.. ';
    $array['O'] = '--- ';
    $array['!'] = '-.-.-- ';
    $array['Y'] = '-.-- ';
    $array[','] = '--..-- ';
    $array['&'] = '. ... ';
    $array['_'] = '..-- .- ';
    $array['M'] = '-- ';
    $array['&'] = '.-...- ';
    $array['R'] = '.-. ';
    $array['N'] = '-. ';
    $array['='] = '-...- ';
    $array['V'] = '...- ';
    $array['$'] = '...-..- ';
    $array['X'] = '-..- ';
    $array['U'] = '..- ';
    $array['A'] = '.- ';
    $array['T'] = '- ';
    $array['W'] = '.-- ';
    $array[')'] = '-.--.- ';
    $array['E'] = '. ';
    $array['   '] = ' ';
    foreach ($array as $key => $var) {
        $string = str_replace($var, $key, $string);
    }
    return $string;
}
//echo morse_encode('a b c');// .- -... -.-. 
//echo morse_decode(morse_encode('a b c'));// A B C
?>

dir.php

<?php
function rmdi_r($dirname){
//判断是否为一个目录,非目录直接关闭
if(is_dir($dirname)){
//如果是目录,打开他
$name = opendir($dirname);
//使用while循环遍历
$i = 0;
while($file = readdir($name)){
    //去掉本目录和上级目录的点
    if($file == "." || $file == ".."){
        continue;
    }
    //如果目录里面还有一个目录,再次回调
    if(is_dir($dirname."/".$file)){
        rmdi_r($dirname."/".$file);
    }
    //exit();
    //如果目录里面是个文件,那么输出文件名
    if(is_file($dirname."/".$file)){
        echo "<li>".$dirname."/".$file."</li>";
    }
    $i++;
}
//遍历完毕关闭文件
closedir($name);
//输出目录名
//echo("目录名称:".$dirname);
    if($i == 0){//目录为空提示语
        echo "该目录为空";
    }else{
    }
}
}

mysql

SET NAMES utf8;
SET time_zone = '+00:00';
SET foreign_key_checks = 0;
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
DROP TABLE IF EXISTS `photo`;
CREATE TABLE `photo` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(1000) NOT NULL,
  `morsename` varchar(1000) NOT NULL,
  `type` varchar(100) NOT NULL,
  `time` int(10) unsigned NOT NULL,
  `morsetime` varchar(100) NOT NULL,
  `url` varchar(100) NOT NULL,
  `afterurl` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
返回文章列表 文章二维码 打赏
本页链接的二维码
打赏二维码
期待你的评论