1、创建数据库表
CREATE TABLE `photo` ( `id` int(12) NOT NULL AUTO_INCREMENT, `image` blob NOT NULL, `ContentType` varchar(20) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
image字段存的是图像的内容,为blob格式,contenttype字段存的是图像的contenttype
2、图像保存到数据库
$_allowType = array('image/jpg','image/jpeg','image/pjpeg','image/png','image/gif'); if($_FILES['newmPhoto']['size'] >500000){//图片超过500k cpmsg('size_max'); }elseif(!in_array($_FILES['newmPhoto']['type'],$_allowType)){ cpmsg('type_error'); } else{ $fp =fopen($_FILES['newmPhoto']['tmp_name'],'r'); $fileData = addslashes(fread($fp,filesize($_FILES['newmPhoto']['tmp_name']))); $data = array( 'Contenttype' =>$_FILES['newmPhoto']['type'], 'image' => $fileData, ); DB::insert('photo', $data);//封装的数据库insert函数 }
注意必须用addslashes函数进行转移,否则数据库操作过不去
3、图片显示
echo "<img src=\"show_image.php?id=".$imageId."\"/>";
show_image.php代码
<?php require_once 'std.inc.php'; global $_G; $query = DB::fetch_first("SELECT image,Contenttype FROM ".DB::table('photo')." WHERE id={$_G['gp_id']}"); Header( "Content-type: ".$query['Contenttype']); echo $query[image]; ?>