使用 php 处理图片时,常常需要对其进行裁剪。如何将裁剪后的图片存入 mysql 数据库是一个有趣的问题。首先,获得上传后文件:$picfile = $_files[picfilename];$pictype = $picfile[type]; $picdata = file_get_contents($tempfile);
如果不需要更改图片大小而直接存入mysql,可以如下简单实现$tempfile = $picfile[tmp_name]; $picdata = base64_encode($picdata); $query = insert into image (imgid, image, imgtype) values( null, '$picdata', '$pictype' );; $link->query($query);
但如果要更改图片大小并以字符流的形式获得图片数据,则需要一点小技巧:
首先完成裁剪图片,获取图片对象list($picw, $pich) = getimagesize($tempfile); if($picw>600){ //超出大小 $src = imagecreatefromjpeg($tempfile); //获取原图数据 $nw =550; $nh = $pich*$nw/$picw; $newpictemp = imagecreatetruecolor($nw,$nh); //创建彩色图片对象 imagecopyresampled($newpictemp,$src,0,0,0,0,$nw,$nh,$picw,$pich); }
这一步以后 newpictemp 就是 resource 型的图片数据了,问题来了,观察上方代码,file_get_contents 返回的类型是 string,也是 base64_encode 的参数类型。 如何把 resource 转为 string 类型呢。 经过学习发现 php 有个这个函数string ob_get_contents ( void )
以字符串的形式返回输出缓冲区中的内容。
因此,思路就是把 resource 图片输出到缓冲区,然后用一个对象获取其内容。代码如下ob_start(); //开启输出缓冲区 imagejpeg($newpictemp); //这个函数可以显示出图片,同时也是把数据输出 $imgcontent = ob_get_contents(); //获取字符流 ob_end_clean(); //关闭并清除缓冲区 $picdata = base64_encode($imgcontent); //不要忘记转码
这样一来,就获得更改大小后的图片字符流了,可以存入mysql
最后销毁临时数据imagedestroy($src); imagedestroy($newpictemp);
如果需要读取并显示图片,可以使用如下代码$query = select image, imgtype from image where imgid = $imgid ;; $result = $link->query($query); $row = mysqli_fetch_array($result); $data = base64_decode( $row[image]); $type = $row[imgtype]; ob_clean(); header(content-type:'$type'); echo $data;
可以看出几个关键函数都含有 ob 标识。 ob 即 output buffer,是 php 非常关键且有用的一项工具参考 php.net
以上就介绍了php裁剪图片并存入mysql,包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。