php图片的二进制转换实例

 更新时间:2016年11月25日 17:23  点击:2229
这里我们是在上传文件时把上传的文件转换成二进制然后保存到数据的字段中去,下次读读出我们也用同样的方法显示即可。

html:

 代码如下 复制代码
<form action=”insertPic.php” method=”post” enctype=”multipart/form-data” name=”mainForm” id=”mainForm”>
<input type=”file” name=”myFile” />
<input type=”submit” name=”Submit” value=”Submit”/>
</form>

将图片保存到数据库:

 代码如下 复制代码
<?php
//由于上传过来的图片被保存在一个临时文件中,所以
//我们仅需要读取该文件就可以获取传过来的图片
$fp = fopen($_FILES["myFile"]["tmp_name"],”rb”);
$buf = addslashes(fread($fp,$_FILES["myFile"]["size"]));
//创建一个PDO对象
$dbh = new PDO(“mysql:host=localhost;port=
3306;dbname=test”, “root”, “123456″);
//执行插入操作并将结果保存在一个变量中
$result = $dbh->query(“INSERT INTO img (images) VALUES (‘$buf’)”);
//获取影响的行数
if ($result->rowCount() >0) {
echo(“数据已插入。”);
} else {
echo(“不能执行插入操作。”);
}
//显式的关闭PDO连接
$dbh = NULL;
?>
显示图片:(show.php)
<?php
$conn=@mysql_connect(“localhost”,”root”,”123456″) or die(“服务器连接错误!”); //链接数据库
@mysql_select_db(“test”,$conn) or die(“未发现数据库!”);
$query=”select * from img where Id=”.$_GET['id'];
$result=mysql_query($query); www.111cn.net
$num=mysql_num_rows($result);
$data = mysql_result($result,0,”images”);
header(“Content-type: image/” . $num['imgType']);
echo $data;
?>

或者

 代码如下 复制代码
<img src=”show.php?id=5″ />

1、fopen函数。
fopen()函数用于打开文件或者URL。语法如下:
int fopen(string filename, string mode);
字符串参数mode可以是下列的情形:
“r”开文件方式为只读,文件指针指到开始处。
“r+”开文件方式为可读写,文件指针指到开始处。
“w”开文件方式为写入,文件指针指到开始处,并将原文件的长度设为0。若文件不存在,则建立新文件。
“w+”开文件方式为可读写,文件指针指到开始处,并将原文件的长度设为0。若文件不存在,则建立新文件。
“a”开文件方式为写入,文件指针指到文件最后。若文件不存在,则建立新文件。
“a+”开文件方式为可读写,文件指针指到文件最后。若文件不存在,则建立新文件。
“b”若操作系统的文字及二进位文件不同,则可以用此参数,UNIX系统不需要使用本参数。
2、Addslashes函数。
Addslashes函数用于将字符串加入斜线。语法如下:【注:我测试的时候是把这个函数去掉后成功了,道理你懂的。自己试下就明白了】
string addslashes(string str);
该函数使需要让数据库处理的字符串,引号的部份加上斜线,以供数据库查询(query)能顺利运作。这些会被改的字符包括单引号(’)、双引号(”)、反斜线backslash()以及空字符NULL(the null byte)。
3、fread函数。
fread函数用于读到指定长度的位组或到文件尾EOF。语法如下:
string fread(int fp, int length);可安全用于二进制文件
fread() 从文件指针 file 读取最多 length 个字节。该函数在读取完最多 length 个字节数,或到达 EOF 的时候,或(对于网络流)当一个包可用时,或(在打开用户空间流之后)已读取了 8192 个字节时就会停止读取文件,视乎先碰到哪种情况。
二进制转换成图片
注:$newFilePath 对生成的图片名和路径做处理,这里自己去实现。

 代码如下 复制代码
$newFilePath='1.jpg';
$data = $GLOBALS[HTTP_RAW_POST_DATA];//得到post过来的二进制原始数据
if(empty($data)){ www.111cn.net
 $data=file_get_contents("php://input");
}
$newFile = fopen($newFilePath,"w");//打开文件准备写入
fwrite($newFile,$data);//写入二进制流到文件
fclose($newFile);//关闭文件

可以把读取到的二进制流存到数据库,也可以直接写入成一个图片。
获取二进制头文件,从而得知属于什么类型文件

 代码如下 复制代码
$bin = substr($content,0,2);
    $strInfo = @unpack("C2chars", $bin);
    $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
    $fileType = '';
    switch ($typeCode)
    {
        case 7790:
            $fileType = 'exe';
            break;
        case 7784:
            $fileType = 'midi';
            break;
        case 8297:
            $fileType = 'rar';
            break;
        case 255216:
            $fileType = 'jpg';
            break;
        case 7173:
            $fileType = 'gif';
            break;
        case 6677:
            $fileType = 'bmp';
            break;
        case 13780:
            $fileType = 'png';
            break;
        default:
            echo 'unknown';
    }
这是一个可以获取网页的html代码以及css,js,font和img资源的小工具,主要用来快速获取模板。如果你来不及设计UI或者看到不错的模板,则可以使用这个工具来抓取网页和提取资源文件。提取的内容会按相对路径来保存资源,因此你不必担心资源文件的错误url导入

首页 index.php:

 代码如下 复制代码

<!DOCTYPE html>
<html>
<head>
<meta name="author" content="flute" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>网页抓取器</title>
<link rel="stylesheet" href="main.css" media="all" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<h1>Web Grabber</h1>
<hr />
<div class="box">
  <h2>Url</h2>
  <div class="form">
    <input type="text" id="project" value="projectname" />
    <input type="text" id="url" value="http://" size="60" />
    <button class="submit" type="button">Get</button><span id="tip"></span>
  </div> www.111cn.net
</div>
<div class="box">
  <span class="all" id="saveall">Save All</span>
  <h2>List</h2>
  <ul id="list">
  </ul>
</div>
</body>
</html>

抓取页面代码 grab.php:

 代码如下 复制代码

<?PHP
 /*
 * flute
 * 2014/03/31
 */

 if(isset($_POST['url'])) {
  if(isset($_POST['project']) && !is_dir($_POST['project'])) mkdir($_POST['project'], 0777);
  echo json_encode(grab($_POST['url']));
 }

 function grab($url) {
  //$url = 'http://ldixing-wordpress.stor.sinaapp.com/uploads/leaves/test.html';
  $data = array();
  $file = preg_replace('/^.*//', '', $url);

  if(($content = file_get_contents($url)) !== false) {

   if(isset($_POST['project'])) file_put_contents($_POST['project'].'/'.$file, $content);

   $pattern = '/<link.*?href=('|")(.*?.css)1.*?>/i';
   if(preg_match_all($pattern, $content, $matches)) {
    $data['css'] = $matches[2];
   }

   $pattern = '/<script.*?src=('|")(.*?.js)1.*?>/i';
   if(preg_match_all($pattern, $content, $matches)) {
    $data['js'] = $matches[2];
   }

   $pattern = '/<img.*?src=('|")(.*?)1.*?>/i';
   if(preg_match_all($pattern, $content, $matches)) {
    $data['img'] = $matches[2];
   }

   $pattern = '/url(('|"|s)(.*?)1)/i';
   if(preg_match_all($pattern, $content, $matches)) {
    $data['src'] = $matches[2];
   }
  }

  return $data;
 }

www.111cn.net

 function vardump($obj) {
  echo '<pre>';
  print_r($obj);
  echo '</pre>';
 }
?>

保存css,js,img等资源的页面 save.php:

 代码如下 复制代码

<?PHP
 /*
 *  flute
 *  2014/03/31
 */

 if(isset($_POST['url']) && isset($_POST['project']) && isset($_POST['domain'])) {
  extract($_POST);
  $url = preg_replace('/?.*$/', '', $url);
  $file = $url;
  $arr = explode('/', $file);
  $length = sizeof($arr);
  $filename = $arr[$length - 1];
  $root = $project;
  $dir = $root;

  if($domain == 'http') {
   $dir = $root.'/http';
   if(!is_dir($dir)) mkdir($dir, 0777);
  } else {
   $file = $domain.'/'.$url;
   for($i = 0; $i < $length -1; $i++) {
    if(!empty($arr[$i])) {
     $dir .= '/'.$arr[$i];
     if(!is_dir($dir)) mkdir($dir, 0777);
    }
   }
  }
  if(!file_exists($dir.'/'.$filename) || filesize($dir.'/'.$filename) == 0) {
   $content = file_get_contents($file);
   file_put_contents($dir.'/'.$filename, $content);
  }
 }
?>

使用方法:
1. 打开index页,输入项目名和要抓取的网址,网址必须是文件名结尾,如index.html;
2. 点Get按钮,得到当前页面所有的css,js,img等资源列表;
3. 点击css链接会获取css文件中的背景资源图片,附加在列表后头;
4. 点击Save All即可保存列表中所有的文件,并按相对路径生成;
5. 如果网页上有http远程文件,将会直接保存在http文件夹下;
6. Get和Save有时会失败,没关系重试几次即可。

临时性需求,研究了一下天翼开发平台的东西,用来发送验证码还是不错的,但是每日限额不多,所以很鸡肋,但是保证100%到达 买的话还是蛮贵的,代码没有做任何优化处理,只是测试是否可以实现接口,用的同学记得完善代码,刚写完老大又说是鸡肋的东西,不用了,代码放在博客记录下
 代码如下 复制代码

<?php
//
date_default_timezone_set('PRC');
//获取access_token
$data = "app_id=x&app_secret=x&grant_type=client_credentials";
$ch = curl_init("https://oauth.api.189.cn/emp/oauth2/v2/access_token");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_POST,1);//使用post提交数据
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);//设置 post提交的数据
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// 从证书中检查SSL加密算法是否存在

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$access_token = curl_exec($ch);
curl_close($ch);
$access_token = json_decode($access_token,true);
//获取短信信任码 www.111cn.net
$timestamp = date('Y-m-d H:i:s');

$param['app_id'] = "app_id=x";
$param['access_token'] = "access_token=".$access_token['access_token'];
$param['timestamp'] = "timestamp=".$timestamp;
ksort($param);
$plaintext = implode("&",$param);
$sign = rawurlencode(base64_encode(hash_hmac('sha1',$plaintext,app_secret,true)));
//echo $sign;exit;
$code = file_get_contents("http://api.189.cn/v2/dm/randcode/token?app_id=x&access_token={$access_token['access_token']}&timestamp=".$timestamp."&sign=".$sign);
$code = json_decode($code,true);
$code = $code['token'];
echo $code;
//下发验证码
unset($param,$plaintext,$sign);
$param['app_id'] = "app_id=x";
$param['access_token'] = "access_token=".$access_token['access_token'];
$param['token'] = "token=".$code;
$param['phone'] = "phone=15091421612";
$param['url'] = "url=http://wx.podapi.com/test.php";
$param['exp_time'] = "exp_time=2";
$param['timestamp'] = "timestamp=".$timestamp;
ksort($param);
$plaintext = implode("&",$param);
$sign = rawurlencode(base64_encode(hash_hmac('sha1',$plaintext,'xx',true)));

$data = "app_id=x&access_token={$access_token['access_token']}&token={$code}&phone=15091421612&url=http://wx.podapi.com/test.php&exp_time=2&timestamp={$timestamp}&sign=".$sign;
$ch = curl_init("http://api.189.cn/v2/dm/randcode/send");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_POST,1);//使用post提交数据
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);//设置 post提交的数据
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// 从证书中检查SSL www.111cn.net 加密算法是否存在
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$state = curl_exec($ch);
//var_dump(curl_getinfo($ch));
curl_close($ch);
//echo $state;

最近看到博客留言的头像有点别扭,因为游客的头像都是同一个头像,看着不是很舒服。虽然现在绝大多数的主题集成了Gavatar头像功能,先不说gavatar被墙的问题,我自己现在都没弄个gavatar头像。

因为我登陆了几次,连接速度巨慢,所以我就放弃了。当然留言插件也不胜枚举,比如现在比较火的多说,但对于没有注册多说的朋友,头像仍是个问题。对于多说的社交账号绑定,我测试多次,QQ,人人这些主流平台的绑定经常出错,而且有的朋友(像我)讨厌繁琐的授权。

鉴于此,我在想一个大众化的,比较简单的方法。我想到的是对于没有头像的朋友调用其QQ头像,因为QQ现在至少是人手一个,所以只需要留言时填写QQ号,然后调用其头像。这样一来就方便多了。

首先是获取QQ的头像了,这也是这个想法的第一步,即今天的主题:

第一种方法:

 代码如下 复制代码

<?php
$qq = 552452006;
echo '<img src="'.'http://q1.qlogo.cn/g?b=qq&nk='.$qq.'&s=100&t='. time() .'">';
?>

第二种方法:

 代码如下 复制代码

<?php
$qq = 552452006;
 
$src = 'http://q1.qlogo.cn/g?b=qq&nk=' . $qq . '&s=100&t=' . time();
 
header('Content-type: image/png');
 
$res = imagecreatefromstring(file_get_contents($src));
 
imagepng($res);
 
imagedestroy($res);
?>

这两种方法的区别:

第一种方法的优点是可以输出头像的原图,如果你的头像是动态的gif,那么输出的也是动态图。缺点是速度比较慢,不适合作为调用头像的方法。

第二种方法的优点是相比第一种速度比较快,但只抓取头像的静态图,不会显示动态头像,比较适合作为调用头像的方法。

在 php 获取图片尺寸的方法我们可以使用 getimagesize 获取图片尺寸的效率是很低的,首先需要获取整个的图片信息,然后再进行操作,下面的例子更科学算法更好,我们一起来看看吧。

下方法可以用于快速获取图片尺寸信息

1.获取JPEG格式图片的尺寸信息

 代码如下 复制代码

<?php
/*

* 获取JPEG格式图片的尺寸信息,并且不需要下载/读取整个图片。

* 经测试这个函数不是对所有JPEG格式的图片都有效。

* http://www.111cn.net

*/

// Retrieve JPEG width and height without downloading/reading entire image.

function getjpegsize($img_loc) {
    $handle = fopen($img_loc, "rb") or die("Invalid file stream.");
    $new_block = NULL;
    if(!feof($handle)) {
        $new_block = fread($handle, 32);
        $i = 0;
        if($new_block[$i]=="xFF" && $new_block[$i+1]=="xD8" && $new_block[$i+2]=="xFF" && $new_block[$i+3]=="xE0") {
            $i += 4;
            if($new_block[$i+2]=="x4A" && $new_block[$i+3]=="x46" && $new_block[$i+4]=="x49" && $new_block[$i+5]=="x46" && $new_block[$i+6]=="x00") {
                
// Read block size and skip ahead to begin cycling through blocks in search of SOF marker

                $block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]);
                $block_size = hexdec($block_size[1]);
                while(!feof($handle)) {
                    $i += $block_size;
                    $new_block .= fread($handle, $block_size);
                    if($new_block[$i]=="xFF") {
                        
// New block detected, check for SOF marker

                        $sof_marker = array("xC0", "xC1", "xC2", "xC3", "xC5", "xC6", "xC7", "xC8", "xC9", "xCA", "xCB", "xCD", "xCE", "xCF");
                        if(in_array($new_block[$i+1], $sof_marker)) {
                            
// SOF marker detected. Width and height information is contained in bytes 4-7 after this byte.

                            $size_data = $new_block[$i+2] . $new_block[$i+3] . $new_block[$i+4] . $new_block[$i+5] . $new_block[$i+6] . $new_block[$i+7] . $new_block[$i+8];
                            $unpacked = unpack("H*", $size_data);
                            $unpacked = $unpacked[1];
                            $height = hexdec($unpacked[6] . $unpacked[7] . $unpacked[8] . $unpacked[9]);
                            $width = hexdec($unpacked[10] . $unpacked[11] . $unpacked[12] . $unpacked[13]);
                            return array($width, $height);
                        } else {
                            
// Skip block marker and read block size

                            $i += 2;
                            $block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]);
                            $block_size = hexdec($block_size[1]);
                        }
                    } else {
                        return FALSE;
                    }
                }
            }
        }
    }
    return FALSE;
}
?>

2.

 代码如下 复制代码

$url='http://www.111cn.net /images/201203/08/1331189004_28093400.jpg';
$image_content = file_get_contents($url);
$image = imagecreatefromstring($image_content);
$width = imagesx($image);
$height = imagesy($image);
echo $width.'*'.$height."nr";   

[!--infotagslink--]

相关文章