PHP根据图片制作缩略图

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: php中制作缩略图的方法也很简单,是用imagecopyresampled方法根据源图制作一个小一点的图片,来看代码check_image_addthumbs.php Here is your pic! ...

php中制作缩略图的方法也很简单,是用imagecopyresampled方法根据源图制作一个小一点的图片,来看代码check_image_addthumbs.php

<?php 
//修改图片效果
$db = mysql_connect('localhost','root','Ctrip07185419') or die('can not connect to database');
mysql_select_db('moviesite',$db) or die(mysql_error($db));
//上传文件的路径
$dir = 'D:\Serious\phpdev\test\images';
//缩略图的路径
$thumbdir = 'D:\Serious\phpdev\test\images\thumbs';
//设置环境变量
putenv('GDFONTPATH='.'C:\Windows\Fonts');
$font = "arial";

//upload_image.php页面传递过来的参数,如果是上传图片
if($_POST['submit'] == 'Upload')
{
    if($_FILES['uploadfile']['error'] != UPLOAD_ERR_OK)
    {
        switch($_FILES['uploadfile']['error'])
        {
            case UPLOAD_ERR_INI_SIZE:
                die('The uploaded file exceeds the upload_max_filesize directive');
            break;
            case UPLOAD_ERR_FORM_SIZE:
                die('The upload file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form');
            break;
            case UPLOAD_ERR_PARTIAL:
                die('The uploaded file was only partially uploaded');
            break;
            case UPLOAD_ERR_NO_FILE:
                die('No file was uploaded');
            break;
            case UPLOAD_ERR_NO_TMP_DIR:
                die('The server is missing a temporary folder');
            break;    
            case UPLOAD_ERR_CANT_WRITE:
                die('The server fail to write the uploaded file to the disk');
            break;        
            case UPLOAD_ERR_EXTENSION:
                die('The upload stopped by extension');
            break;                
        }
    }
    $image_caption = $_POST['caption'];
    $image_username = $_POST['username'];
    $image_date = date('Y-m-d');
    list($width,$height,$type,$attr) = getimagesize($_FILES['uploadfile']['tmp_name']);
    $error = 'The file you upload is not a supported filetype';
    switch($type)
    {
        case IMAGETYPE_GIF:
            $image = imagecreatefromgif($_FILES['uploadfile']['tmp_name']) or die($error);
        break;
        case IMAGETYPE_JPEG:
            $image = imagecreatefromjpeg($_FILES['uploadfile']['tmp_name']) or die($error);
        break;
        case IMAGETYPE_PNG:
            $image = imagecreatefrompng($_FILES['uploadfile']['tmp_name']) or die($error);
        break;
        default:
        break;
    }
    $query = 'insert into images(image_caption,image_username,image_date) values("'.$image_caption.'" , "'.$image_username.'","'.$image_date.'")';
    $result = mysql_query($query,$db) or die(mysql_error($db));
    $last_id = mysql_insert_id();
    
    // $imagename = $last_id.'.jpg';
    // imagejpeg($image,$dir.'/'.$imagename);
    // imagedestroy($image);
    
    $image_id = $last_id;
    imagejpeg($image , $dir.'/'.$image_id.'.jpg');
    imagedestroy($image);
}
else  //如果图片已经上传,则从数据库中取图片名字
{
    $query = 'select image_id,image_caption,image_username,image_date from images where image_id='.$_POST['id'];
    $result = mysql_query($query,$db) or die(mysql_error($db));
    extract(mysql_fetch_assoc($result));
    list($width,$height,$type,$attr) = getimagesize($dir.'/'.$image_id.'.jpg');
}

//如果是保存图片
if($_POST['submit'] == 'Save')
{
    if(isset($_POST['id']) && ctype_digit($_POST['id']) && file_exists($dir.'/'.$_POST['id'].'.jpg'))
    {
        $image = imagecreatefromjpeg($dir.'/'.$_POST['id'].'.jpg');
    }
    else
    {
        die('invalid image specified');
    }
    $effect = (isset($_POST['effect'])) ? $_POST['effect'] : -1;
    switch($effect)
    {
        case IMG_FILTER_NEGATE:
            imagefilter($image , IMG_FILTER_NEGATE);     //将图像中所有颜色反转
        break;
        case IMG_FILTER_GRAYSCALE:
            imagefilter($image , IMG_FILTER_GRAYSCALE);  //将图像转换为灰度的
        break;
        case IMG_FILTER_EMBOSS:
            imagefilter($image , IMG_FILTER_EMBOSS);     //使图像浮雕化
        break;
        case IMG_FILTER_GAUSSIAN_BLUR:
            imagefilter($image , IMG_FILTER_GAUSSIAN_BLUR); //用高斯算法模糊图像
        break;    
    }
    
    if(isset($_POST['emb_caption']))
    {
        imagettftext($image , 12 , 0 , 20 , 20 , 0 , $font , $image_caption);
    }
    
    $thumb_width = $width * 0.10;
    $thumb_height = $height * 0.10;
                   
    //创建一个缩略图
    $thumb = imagecreatetruecolor($thumb_width, $thumb_height);
    imagecopyresampled($thumb, $image, 0, 0, 0, 0, $thumb_width, $thumb_height,    $width, $height);
    //保存原图
    imagejpeg($image, $dir . '/' . $_POST['id'] . '.jpg', 100);
    //保存缩略图
    imagejpeg($thumb, $thumbdir . '/' . $_POST['id'] . '.jpg', 100);
    imagedestroy($thumb);
    ?>
    <html>
        <head>
            <title>Here is your pic!</title>
        </head>
        <body>
            <h1>Your image has been saved!</h1>
            <img src="images/<?php echo $_POST['id'];?>.jpg" alt="" />
        </body>
    </html>
<?php 
}
else
{
?>
    <html>
        <head>
            <title>Here is your pic!</title>
        </head>
        <body>
            <h1>So how does it feel to be famous?</h1>
            <p>Here is the picture you just uploaded to your servers:</p>
            <!--<img src="images/<?php echo $imagename;?>" alt="" style="float:left;" />-->
        </body>
    </html>
    <?php
        if($_POST['submit'] == 'Upload')
        {
            $imagename = 'images/'.$image_id.'.jpg';
        }
        else
        {
            $imagename = 'image_effect.php?id='.$image_id.'&e='.$_POST['effect'];
            if(isset($_POST['emb_caption']))
            {
                $imagename .= '&capt='.urlencode($image_caption);
            }
        }
    ?>
    <img src="<?php echo $imagename;?>" style="float:left;" alt="" />
    <table>
        <tr>
            <td>Image save as:</td>
            <td><?php $image_id?></td>
        </tr>
        <tr>
            <td>Height:</td>
            <td><?php echo $height;?></td>
        </tr>
        <tr>
            <td>Widht:</td>
            <td><?php echo $width;?></td>
        </tr>
        <tr>
            <td>Upload date:</td>
            <td><?php echo $image_date;?></td>
        </tr>
    </table>
    <p>You may apply a special effect to your image from the list of option below.
    Note:saving an image with any of the filters applied <em>can be undone</em>
    </p>
    <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
        <div>
            <input type="hidden" name="id" value="<?php echo $image_id;?>"/>
            Filter:<select name="effect" id="">
                <option value="-1">None</option>
                <?php 
                    echo '<option value="'.IMG_FILTER_GRAYSCALE.'" ';
                    if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GRAYSCALE)
                    {
                        echo 'selected="selected"';
                    }
                    echo ' >Black and white</option>';
                    
                    echo '<option value="'.IMG_FILTER_GAUSSIAN_BLUR.'"';
                    if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_GAUSSIAN_BLUR)
                    {
                        echo ' selected="selected"';
                    }
                    echo '>Blur</option>';
                    
                    echo '<option value="'.IMG_FILTER_EMBOSS.'"';
                    if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_EMBOSS)
                    {
                        echo 'selected="selected"';
                    }
                    echo '>Emboss</option>';
                    
                    echo '<option value="'.IMG_FILTER_NEGATE.'"';
                    if(isset($_POST['effect']) && $_POST['effect'] == IMG_FILTER_NEGATE)
                    {
                        echo 'selected="selected"';
                    }
                    echo '>Negative</option>';
                ?>
            </select><br />
            <?php 
                echo '<input type="checkbox" name="emb_caption"';
                if(isset($_POST['emb_caption']))
                {
                    echo ' checked="checked"';
                }
                echo ' />Embed caption in image?';
            ?>
            <input type="submit" value="Preview" name="submit" /><br /><br />
            <input type="submit" value="Save" name="submit" />
            
        </div>
    </form>
<?php 
}
?>

缩略图放在D:\Serious\phpdev\test\images\thumbs路径下面,这里我们添加了一个gallery.php文件来陈列所有的缩略图,代码如下:

<?php 
$db = mysql_connect('localhost','root','Ctrip07185419') or die('can not connect to database');
mysql_select_db('moviesite',$db) or die(mysql_error($db));

$dir = 'images';
$thumbdir = $dir.'/thumbs';
?>
<html>
    <head>
        <title>Welcome to our Photo Gallery</title>
        <style type="text/css">
            th{  background-color:#999; }
            .odd_row { background-color:#EEE;}
            .even_row {background-color:#FFF;}
        </style>
    </head>
    <body>
        <p>Click on any image to see it full sized.</p>
        <table style="width:100%"> 
            <tr>
                <th>Image</th>
                <th>Caption</th>
                <th>Uploaded By</th>
                <th>Date uploaded</th>
            </tr>
            <?php 
            $result = mysql_query('select * from images') or die(mysql_error($db));
            $odd = true;
            while($row = mysql_fetch_assoc($result))
            {
                echo ($odd == true) ? '<tr class="odd_row">' : '<tr class="even_row">';
                $odd = !$odd;
                extract($row);
                echo '<td><a href="' . $dir . '/' . $image_id.'.jpg">';
                echo '<img src="' . $thumbdir . '/' . $image_id . '.jpg" alt="" />';
                echo '</a></td>';
                echo '<td>'.$image_caption.'</td>';
                echo '<td>'.$image_username.'</td>';
                echo '<td>'.$image_date.'</td>';
                echo '</tr>';
            }
            
            ?>
        </table>
    </body>
</html>

来看看最后显示缩略图的效果:

注意下面的代码:

    $thumb_width = $width * 0.10;
    $thumb_height = $height * 0.10;
                   
    //创建一个缩略图
    $thumb = imagecreatetruecolor($thumb_width, $thumb_height);
    imagecopyresampled($thumb, $image, 0, 0, 0, 0, $thumb_width, $thumb_height,    $width, $height);
    //保存原图
    imagejpeg($image, $dir . '/' . $_POST['id'] . '.jpg', 100);
    //保存缩略图
    imagejpeg($thumb, $thumbdir . '/' . $_POST['id'] . '.jpg', 100);
    imagedestroy($thumb);

我们设置缩略图的长度是原来长度的10%,宽度也是原来宽度的10%,注意保持一致,否则图片会出现失真,当然这个参数如果设置成大于1的整数,图片就会放大。

 

作者:Tyler Ning
出处:http://www.cnblogs.com/tylerdonet/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,如有问题,可以通过以下邮箱地址williamningdong@gmail.com  联系我,非常感谢。

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
3月前
|
PHP
使用PHP实现随机调用图片
使用PHP实现随机调用图片
76 0
使用PHP实现随机调用图片
|
4月前
|
小程序 PHP 数据安全/隐私保护
php图片加水印函数
这里分享下php给图片加水印的几个自定义函数 给图片加水印首先需要开启GD库。 用到的php函数是imagecopymerge () 和 imagecopy () imagecopymerge 函数可以支持两个图像叠加时,设置叠加的透明度
46 0
|
6月前
|
PHP
【PHP】读取本地文件夹中所有图片并显示
PHP图片收集系统收集作业后,为了方便老师在线查阅作业,特意写了个读取图片然后显示出来的php 比较粗糙,可以再多美化美化
59 0
|
1月前
|
存储 PHP Apache
使用CFimagehost源码搭建无需数据库支持的PHP免费图片托管私人图床
使用CFimagehost源码搭建无需数据库支持的PHP免费图片托管私人图床
|
9月前
|
PHP
PHP实现自制随机图片API- 调用文件夹和引用网络图片
PHP实现随机图片API- 调用文件夹和引用网络图片
110 0
|
6月前
|
小程序 PHP
[微擎]多系统共用accesstoken修复wifi小程序文本敏感词汇检测+图片检测原生php(可用)
[微擎]多系统共用accesstoken修复wifi小程序文本敏感词汇检测+图片检测原生php(可用)
|
9月前
|
JSON 前端开发 API
layui框架实战案例(8):web图片裁切插件croppers.js组件实现上传图片的自定义截取(含php后端)
layui框架实战案例(8):web图片裁切插件croppers.js组件实现上传图片的自定义截取(含php后端)
386 0
|
9月前
|
PHP
PHP实现图片登录验证码的解决方案
PHP实现图片登录验证码的解决方案
75 0
|
9月前
|
API PHP
php访问API将图片保存到本地
php访问API将图片保存到本地
47 0