php 完整图片按比例生成缩略图代码

 更新时间:2016年11月25日 15:58  点击:1802

<?php
require ('resize_img.php');
//how to use the class:
//makes a simple thumbnail of an image of 100x100 and saves the image then outputs it.
$imgresize = new resize_img();

$imgresize->sizelimit_x = 100;
$imgresize->sizelimit_y = 100;
$imgresize->keep_proportions = true;
$imgresize->output = 'PNG';

if( $imgresize->resize_image( 'C:/xampp/htdocs/wannabe/image_bin/public/treeshadows_001.gif' ) === false )
{
  echo 'ERROR!';
}
else
{
  $imgresize->save_resizedimage( 'C:/xampp/htdocs/wannabe/image_bin/public/thumbnails/', 'treeshadows_001' );
  $imgresize->output_resizedimage();
}

$imgresize->destroy_resizedimage();

?>

// resize_img.php文件

<?php

/**
 * by Daniel M. Story <admin@danstory.com>
 */

class resize_img
{
  var $image_path = '';
  //holds the image path
  var $sizelimit_x = 250;
  //the limit of the image width
  var $sizelimit_y = 250;
  //the limit of the image height
  var $image_resource = '';
  //holds the image resource
  var $keep_proportions = true;
  //if true it keeps教程 the image proportions when resized
  var $resized_resource = '';
  //holds the resized image resource
  var $hasGD = false;
  var $output = 'SAME';
  //can be JPG, GIF, PNG, or SAME (same will save as old type)
 
  function resize_img()
  {
    if( function_exists('gd_info') ){ $this->hasGD = true; } 
  }
 
  function resize_image( $image_path )
  {
    if( $this->hasGD === false ){ return false; }
    //no GD installed on the server!
   
    list($img_width, $img_height, $img_type, $img_attr) = @getimagesize( $image_path );
    //this is going to get the image width, height, and format
   
    if( ( $img_width != 0 ) || ( $img_width != 0 ) )
    //make sure it was loaded correctly
    {
      switch( $img_type )
      {
        case 1:
          //GIF
          $this->image_resource = @imagecreatefromgif( $image_path );
          if( $this->output == 'SAME' ){ $this->output = 'GIF'; }
          break;
        case 2:
          //JPG
          $this->image_resource = @imagecreatefromjpeg( $image_path );
          if( $this->output == 'SAME' ){ $this->output = 'JPG'; }
          break; 
        case 3:
          //PNG
          $this->image_resource = @imagecreatefrompng( $image_path );
          if( $this->output == 'SAME' ){ $this->output = 'PNG'; }
      }
      if( $this->image_resource === '' ){ return false; }
      //it wasn't able to load the image
    }
    else{ return false; }
    //something happened!
   
    if( $this->keep_proportions === true )
    {
      if( ($img_width-$this->sizelimit_x) > ($img_height-$this->sizelimit_y) )
      {
      //if the width of the img is greater than the size limit we scale by width
        $scalex = ( $this->sizelimit_x / $img_width );
        $scaley = $scalex;
      }
      else
      //if the height of the img is greater than the size limit we scale by height
      {
        $scalex = ( $this->sizelimit_y / $img_height );
        $scaley = $scalex;
      }

    }
    else
    {
      $scalex = ( $this->sizelimit_x / $img_width );
      $scaley = ( $this->sizelimit_y / $img_height );
      //just make the image fit the image size limit
     
      if( $scalex > 1 ){ $scalex = 1; }
      if( $scaley > 1 ){ $scaley = 1; }
      //don't make it so it streches the image
    }
   
    $new_width = $img_width * $scalex;
    $new_height = $img_height * $scaley;
   
    $this->resized_resource = @imagecreatetruecolor( $new_width, $new_height );
    //creates an image resource, with the width and height of the size limits (or new resized proportion )
   
    if( function_exists( 'imageantialias' )){ @imageantialias( $this->resized_resource, true ); }
    //helps in the quality of the image being resized
   
    @imagecopyresampled( $this->resized_resource, $this->image_resource, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height );
    //resize the iamge onto the resized resource
   
    @imagedestroy( $this->image_resource );
    //destory old image resource
   
    return true;
  }
 
  function save_resizedimage( $path, $name )
  {
    switch( strtoupper($this->output) )
    {
      case 'GIF':
        //GIF
        @imagegif( $this->resized_resource, $path . $name . '.gif' );
        break;
      case 'JPG':
        //JPG
        @imagejpeg( $this->resized_resource, $path . $name . '.jpg' );
        break; 
      case 'PNG':
        //PNG
        @imagepng( $this->resized_resource, $path . $name . '.png' );
    }
  }
 
  function output_resizedimage()
  {
    $the_time = time();
    header('Last-Modified: ' . date( 'D, d M Y H:i:s', $the_time ) . ' GMT');
    header('Cache-Control: public');
   
    switch( strtoupper($this->output) )
    {
      case 'GIF':
        //GIF
        header('Content-type: image/gif');
        @imagegif( $this->resized_resource );
        break;
      case 'JPG':
        //JPG
        header('Content-type: image/jpg');
        @imagejpeg( $this->resized_resource );
        break; 
      case 'PNG':
        //PNG
        header('Content-type: image/png');
        @imagepng( $this->resized_resource );
    }
  }
 
  function destroy_resizedimage()
  {
    @imagedestroy( $this->resized_resource );
    @imagedestroy( $this->image_resource );
  }

}

?>

<?
//php教程获取ip的算法
$user_IP = ($_SERVER["HTTP_VIA"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];
$user_IP = ($user_IP) ? $user_IP : $_SERVER["REMOTE_ADDR"];
//echo $user_IP;
//===================================
//
// 功能:IP地址获取真实地址函数
// 参数:$ip - IP地址
// 作者:[Discuz!] (C) Comsenz Inc.
//
//===================================
function convertip($ip) {
    //IP数据文件路径,请根据情况自行修改
    $dat_path = 'QQWry.dat';
    //检查IP地址
    if(!ereg("^([0-9]{1,3}.){3}[0-9]{1,3}$", $ip)){
        return 'IP Address Error';
    }
    //打开IP数据文件
    if(!$fd = @fopen($dat_path, 'rb')){
        return 'IP date file not exists or access denied';
    }
    //分解IP进行运算,得出整形数
    $ip = explode('.', $ip);
    $ipNum = $ip[0] * 16777216 + $ip[1] * 65536 + $ip[2] * 256 + $ip[3];
    //获取IP数据索引开始和结束位置
    $DataBegin = fread($fd, 4);
    $DataEnd = fread($fd, 4);
    $ipbegin = implode('', unpack('L', $DataBegin));
    if($ipbegin < 0) $ipbegin += pow(2, 32);
    $ipend = implode('', unpack('L', $DataEnd));
    if($ipend < 0) $ipend += pow(2, 32);
    $ipAllNum = ($ipend - $ipbegin) / 7 + 1;
    $BeginNum = 0;
    $EndNum = $ipAllNum;
    //使用二分查找法从索引记录中搜索匹配的IP记录
    while($ip1num>$ipNum || $ip2num<$ipNum) {
        $Middle= intval(($EndNum + $BeginNum) / 2);
        //偏移指针到索引位置读取4个字节
        fseek($fd, $ipbegin + 7 * $Middle);
        $ipData1 = fread($fd, 4);
        if(strlen($ipData1) < 4) {
            fclose($fd);
            return 'System Error';
        }
        //提取出来的数据转换成长整形,如果数据是负数则加上2的32次幂
        $ip1num = implode('', unpack('L', $ipData1));
        if($ip1num < 0) $ip1num += pow(2, 32);
        //提取的长整型数大于我们IP地址则修改结束位置进行下一次循环
        if($ip1num > $ipNum) {
            $EndNum = $Middle;
            continue;
        }
        //取完上一个索引后取下一个索引
        $DataSeek = fread($fd, 3);
        if(strlen($DataSeek) < 3) {
            fclose($fd);
            return 'System Error';
        }
        $DataSeek = implode('', unpack('L', $DataSeek.chr(0)));
        fseek($fd, $DataSeek);
        $ipData2 = fread($fd, 4);
        if(strlen($ipData2) < 4) {
            fclose($fd);
            return 'System Error';
        }
        $ip2num = implode('', unpack('L', $ipData2));
        if($ip2num < 0) $ip2num += pow(2, 32);
        //没找到提示未知
        if($ip2num < $ipNum) {
            if($Middle == $BeginNum) {
                fclose($fd);
                return 'Unknown';
            }
            $BeginNum = $Middle;
        }
    }
    //下面的代码读晕了,没读明白,有兴趣的慢慢读
    $ipFlag = fread($fd, 1);
    if($ipFlag == chr(1)) {
        $ipSeek = fread($fd, 3);
        if(strlen($ipSeek) < 3) {
            fclose($fd);
            return 'System Error';
        }
        $ipSeek = implode('', unpack('L', $ipSeek.chr(0)));
        fseek($fd, $ipSeek);
        $ipFlag = fread($fd, 1);
    }
    if($ipFlag == chr(2)) {
        $AddrSeek = fread($fd, 3);
        if(strlen($AddrSeek) < 3) {
            fclose($fd);
            return 'System Error';
        }
        $ipFlag = fread($fd, 1);
        if($ipFlag == chr(2)) {
            $AddrSeek2 = fread($fd, 3);
            if(strlen($AddrSeek2) < 3) {
                fclose($fd);
                return 'System Error';
            }
            $AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
            fseek($fd, $AddrSeek2);
        } else {
            fseek($fd, -1, SEEK_CUR);
        }
        while(($char = fread($fd, 1)) != chr(0))
            $ipAddr2 .= $char;
        $AddrSeek = implode('', unpack('L', $AddrSeek.chr(0)));
        fseek($fd, $AddrSeek);
        while(($char = fread($fd, 1)) != chr(0))
            $ipAddr1 .= $char;
    } else {
        fseek($fd, -1, SEEK_CUR);
        while(($char = fread($fd, 1)) != chr(0))
            $ipAddr1 .= $char;
        $ipFlag = fread($fd, 1);
        if($ipFlag == chr(2)) {
            $AddrSeek2 = fread($fd, 3);
            if(strlen($AddrSeek2) < 3) {
                fclose($fd);
                return 'System Error';
            }
            $AddrSeek2 = implode('', unpack('L', $AddrSeek2.chr(0)));
            fseek($fd, $AddrSeek2);
        } else {
            fseek($fd, -1, SEEK_CUR);
        }
        while(($char = fread($fd, 1)) != chr(0)){
            $ipAddr2 .= $char;
        }
    }
    fclose($fd);
    //最后做相应的替换操作后返回结果
    if(preg_match('/http/i', $ipAddr2)) {
        $ipAddr2 = '';
    }
    $ipaddr = "$ipAddr1 $ipAddr2";
    $ipaddr = preg_replace('/CZ88.Net/is', '', $ipaddr);
    $ipaddr = preg_replace('/^s*/is', '', $ipaddr);
    $ipaddr = preg_replace('/s*$/is', '', $ipaddr);
    if(preg_match('/http/i', $ipaddr) || $ipaddr == '') {
        $ipaddr = 'Unknown';
    }
    return $ipaddr;
}
?>
<script language="javascript教程">
var sf='<?echo convertip($user_IP);?>';
if(sf.indexOf("香港")>=0){
        window.location.href="http://xianggang.111cn.net";
}
else if(sf.indexOf("广东省")>=0){
        window.location.href="http://guangdong.111cn.net";
}
else if(sf.indexOf("北京")>=0){
        window.location.href="http://beijing.111cn.net";
}
else{
        window.location.href="http://www.111cn.net";
}
</script>

现在我将告诉你如何看到有多少用户在浏览您的网站。有许多方法来显示它,但我试图保持它简单,干净。

首先,我们必须创建两个表,您的数据库教程。

CREATE TABLE `uonline` (
  `session` varchar(100) NOT NULL,
  `time` int(5) NOT NULL default '0'
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

这将创建两个表。一个是会议和其他的是时间。他们将我们的信息存储。

现在是PHP的时间。让我们一起创造我们的主要变数

<?php教程
session_start();
$ses = session_id();
$time = time();
$timech=$time-300;
session_start(); - This wills start a session
$ses = session_id(); - This will get our session's ID
$time = time(); - This will get the time
$timech=$time-300; - This will set our time to 5min

Now we have to connect to the database:


// Declare SQL login info
$host = "localhost";
$username = "";
$password = "";
$dbname = "";
 
// Now we are going to connect to our database
mysql教程_connect("$host", "$username", "$password")or die("<font style='color:red'><b>Can not connect:</b> ".mysql_error()."</font>");
mysql_select_db("$db_name")or die("<font style='color:red'><b>Can not select the database:</b> ".mysql_error()."</font>");

$host = "localhost"; - Your SQL's host name, usually it's "localhost"
$username = ""; - Your MySQL username
$password = ""; - Your MySQL password
$dbname = ""; - Your database's name

Now we have to look for existing sessions and get the number of sessions.


$result = mysql_query("SELECT * FROM uonline WHERE session='$ses'");
$num = mysql_num_rows($result); 

$result = mysql_query("SELECT * FROM uonline WHERE session='$ses'"); - This will select all info from session column where it's value is "$ses"
$num = mysql_num_rows($result); - It will tell us how many active records are in session column


if($num == "0"){
$result1 = mysql_query("INSERT INTO uonline (session, time)VALUES('$ses', '$time')");
}else{
$result2 = mysql_query("UPDATE uonline SET time='$time' WHERE session = '$ses'");
}

if($num=="0"){ - If there's no records in session column then we must insert some records
$result1 = mysql_query("INSERT INTO uonline (session, time)VALUES('$ses', '$time')"); - Inserts session's ID and time to database
}else{ - But if there was more records than 0, let's update their records
$result2 = mysql_query("UPDATE uonline SET time='$time' WHERE session = '$ses'"); - Updates existing records
} - Ends If statement

Now let's find our info again from the columns:


$result3 = mysql_query("SELECT * FROM uonline");

$result3 = mysql_query("SELECT * FROM uonline"); - This will get all info from uonline table

It's time for showing how many users are looking your site:


$usersonline = mysql_num_rows($result3);
echo "There are: <b>".$usersonline."</b> users online";

$usersonline = mysql_num_rows($result3); - It will get the number of records in columns
echo "There are: <b>".$usersonline."</b> users online"; - This will show how many users are on your site

When the users have left, you must delete their records from database.


mysql_query("DELETE FROM uonline WHERE time<$timech");
?>

mysql_query("DELETE FROM uonline WHERE time<$timech"); - Deletes records from database when 5min has been thru.

And here's the full code:


<?php
session_start();
$ses = session_id();
$time = time();
$timech=$time-300; 
 
$host = "localhost";
$username = "";
$password = "";
$dbname = "";
 
mysql_connect("$host", "$username", "$password")or die("<font style='color:red'><b>Can not connect:</b> ".mysql_error()."</font>");
mysql_select_db("$db_name")or die("<font style='color:red'><b>Can not select the database:</b> ".mysql_error()."</font>");  
 
$result = mysql_query("SELECT * FROM uonline WHERE session='$ses'");
$num = mysql_num_rows($result); 
 
if($num == "0"){
$result1 = mysql_query("INSERT INTO uonline (session, time)VALUES('$ses', '$time')");
}else{
$result2 = mysql_query("UPDATE uonline SET time='$time' WHERE session = '$ses'");

 
$result3 = mysql_query("SELECT * FROM uonline"); 
 
$usersonline = mysql_num_rows($result3);
echo "There are: <b>".$usersonline."</b> users online";  
 
mysql_query("DELETE FROM uonline WHERE time<$timech");
?>

此脚本时,页面最后修订和产出作为二十分钟前,或XX天前的日期...或者即使您不更新太多 - 二十周前显示!

//File Name
$last_modified = filemtime("FILE.php");
 
{
$timediff = time() - $last_modified;
 
if ($timediff < 3600)
{
if ($timediff < 120)
{
$returndate = "1 minute ago.";
}
else
{
$returndate = intval($timediff / 60) . " minutes ago.";
}
}
else if ($timediff < 7200)
{
$returndate = "1 hour ago.";
}
else if ($timediff < 86400)
{
$returndate = intval($timediff / 3600) . " hours ago.";
}
else if ($timediff < 172800)
{
$returndate = "1 day ago.";
}
else if ($timediff < 604800)
{
$returndate = intval($timediff / 86400) . " days ago.";
}
 
else if ($timediff < 1209600)
{
$returndate = "1 week ago.";
}
else if ($timediff < 3024000)
{
$returndate = intval($timediff / 604900) . " weeks ago.";
}
else
{
$returndate = @date('n-j-Y', $timestamp);
if($type=="fulldate")
{
$returndate = @date('n-j-y, H:i', $timestamp);
 
}
 
else if ($type=="time")
{
 
$returndate = @date('H:i', $timestamp);
 
}
 
}
//Display It
print("Last Modified: ");
print($returndate);
 
}
?>

它应该很容易理解。

$ last_modified = filemtime(“FILE.php”); - 更改FILE.php到文件您要连接。

确定了PHP脚本所需的时间执行正确的一微秒。

插入在页面顶部的代码:

<?php 
          $mtime = microtime(); 
          $mtime = explode(' ', $mtime); 
          $mtime = $mtime[1] + $mtime[0]; 
          $starttime = $mtime; 
?>
然后添加在页面底部的以下内容:

<?php 
          $mtime = microtime(); 
          $mtime = explode(" ", $mtime); 
          $mtime = $mtime[1] + $mtime[0]; 
          $endtime = $mtime; 
          $totaltime = ($endtime - $starttime); 
          echo 'This page was created in ' .$totaltime. ' seconds.'; 
?>

PHP的microtime中()函数返回当前的Unix时间戳微秒。

 

[!--infotagslink--]

相关文章

  • php二维码生成

    本文介绍两种使用 php 生成二维码的方法。 (1)利用google生成二维码的开放接口,代码如下: /** * google api 二维码生成【QRcode可以存储最多4296个字母数字类型的任意文本,具体可以查看二维码数据格式】 * @param strin...2015-10-21
  • Java生成随机姓名、性别和年龄的实现示例

    这篇文章主要介绍了Java生成随机姓名、性别和年龄的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-10-01
  • C#生成随机数功能示例

    这篇文章主要介绍了C#生成随机数功能,涉及C#数学运算与字符串操作相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • php生成唯一数字id的方法汇总

    关于生成唯一数字ID的问题,是不是需要使用rand生成一个随机数,然后去数据库查询是否有这个数呢?感觉这样的话有点费时间,有没有其他方法呢?当然不是,其实有两种方法可以解决。 1. 如果你只用php而不用数据库的话,那时间戳+随...2015-11-24
  • jQuery为动态生成的select元素添加事件的方法

    下面小编就为大家带来一篇jQuery为动态生成的select元素添加事件的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2016-09-01
  • PHP自动生成后台导航网址的最佳方法

    经常制作开发不同的网站的后台,写过很多种不同的后台导航写法。 最终积累了这种最写法,算是最好的吧...2013-09-29
  • js生成随机数的方法实例

    js生成随机数主要用到了内置的Math对象的random()方法。用法如:Math.random()。它返回的是一个 0 ~ 1 之间的随机数。有了这么一个方法,那生成任意随机数就好理解了。比如实际中我们可能会有如下的需要: (1)生成一个 0 - 1...2015-10-21
  • c#生成高清缩略图的二个示例分享

    这篇文章主要介绍了c#生成高清缩略图的二个示例,需要的朋友可以参考下...2020-06-25
  • PHP验证码生成与验证例子

    验证码是一个现在WEB2.0中常见的一个功能了,像注册、登录又或者是留言页面,都需要注册码来验证当前操作者的合法性,我们会看到有些网站没有验证码,但那是更高级的验证了,...2016-11-25
  • PHP生成不同颜色、不同大小的tag标签函数

    复制代码 代码如下:function getTagStyle(){ $minFontSize=8; //最小字体大小,可根据需要自行更改 $maxFontSize=18; //最大字体大小,可根据需要自行更改 return 'font-size:'.($minFontSize+lcg_value()*(abs($maxFo...2013-10-04
  • JS生成某个范围的随机数【四种情况详解】

    下面小编就为大家带来一篇JS生成某个范围的随机数【四种情况详解】。小编觉得挺不错的,现在分享给大家,也给大家做个参考,一起跟随小编过来看看吧...2016-04-22
  • php中利用str_pad函数生成数字递增形式的产品编号

    解决办法:$str=”QB”.str_pad(($maxid[0]["max(id)"]+1),5,”0″,STR_PAD_LEFT ); 其中$maxid[0]["max(id)"]+1) 是利用max函数从数据库中找也ID最大的一个值, ID为主键,不会重复。 str_pad() 函数把字符串填充为指...2013-10-04
  • C#生成Word文档代码示例

    这篇文章主要介绍了C#生成Word文档代码示例,本文直接给出代码实例,需要的朋友可以参考下...2020-06-25
  • Vue组件文档生成工具库的方法

    本文主要介绍了Vue组件文档生成工具库的方法,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-08-11
  • PHP简单实现生成txt文件到指定目录的方法

    这篇文章主要介绍了PHP简单实现生成txt文件到指定目录的方法,简单对比分析了PHP中fwrite及file_put_contents等函数的使用方法,需要的朋友可以参考下...2016-04-28
  • PHP批量生成图片缩略图(1/5)

    这款批量生成缩略图代码可以生成指定大小的小图哦,并且支持文件批量上传。 这款教程会用到php文件 view.php config.php funs.php index.php 功能: -------...2016-11-25
  • C#实现为一张大尺寸图片创建缩略图的方法

    这篇文章主要介绍了C#实现为一张大尺寸图片创建缩略图的方法,涉及C#创建缩略图的相关图片操作技巧,需要的朋友可以参考下...2020-06-25
  • 史上最简洁C# 生成条形码图片思路及示例分享

    这篇文章主要介绍了史上最简洁C# 生成条形码图片思路及示例分享,需要的朋友可以参考下...2020-06-25
  • php 上传文件并生成缩略图代码

    if( isset($_FILES['upImg']) ) { if( $userGroup[$loginArr['group']]['upload'] == 0 ) { echo '{"error":"您所在的用户组无权上传图片!"}'; } else...2016-11-25
  • 简单入门级php 生成xml文档代码

    $doc = new domdocument('1.0'); // we want a nice output $doc->formatoutput = true; 代码如下 复制代码 $root = $doc->createelement('bo...2016-11-25