Maison >développement back-end >tutoriel php >图片跟二进制之间的转换
图片和二进制之间的转换
将图片转换成二进制保存在数据库中,代码如下:
if($_FILES['image']['size'])
{
$names=$_FILES['image']['name'];
$arr=explode('.',$names);
$name=$arr[0];
$date=date('Y-m-d h:i:s');
$fp = fopen($_FILES['image']['tmp_name'], 'rb');
$type = $_FILES['image']['type'];
if (!$fp) {
echo('读取图片失败!');
} else {
$image = addslashes(fread($fp, filesize($_FILES['image']['tmp_name'])));
if ($image) {
$pic=new Image();
$pic->name=$name;
$pic->pic=$image;
$pic->type=$type;
$pic->date=$date;
if($pic->save())
{
$this->flash->notice("图片保存成功");
}
}
}
}
图片保存到数据库中了,文件的格式是BLOB,但是我从数据库中查找到并输出的时候是乱码,代码如下:
$conn=mysqli_connect("localhost","root","");
if(!$conn)
{
$this->flash->notice("连接失败");
}
else
{
mysqli_select_db($conn,"");
$result = mysqli_query($conn,"select * from image where id=3");
if(!$result)
{
$this->flash->notice("数据不存在");
}
else
{
$data=mysqli_fetch_row($result);
/*$type=$data[3];
Header("Content-type: $type");*/
echo($data[2]);
我应该怎么去转换成图片并显示出来呢?求大神帮忙
------解决思路----------------------
写了一个完整的例子,可以参考下。
数据表结构
<br />CREATE TABLE `photo` (<br /> `id` int(10) unsigned NOT NULL auto_increment,<br /> `type` varchar(100) NOT NULL,<br /> `photo` mediumblob NOT NULL,<br /> PRIMARY KEY (`id`)<br />) <br />
<br><?php <br />[email protected]_connect("数据库ip","帐号","密码") or die(mysql_error());<br>@mysql_select_db('数据库名',$conn) or die(mysql_error());<br><br>$action = isset($_REQUEST['action'])? $_REQUEST['action'] : '';<br><br>if($action=='add'){<br> $image = mysql_escape_string(file_get_contents($_FILES['photo']['tmp_name']));<br> $type = $_FILES['photo']['type'];<br> $sqlstr = "insert into photo(type,photo) values('".$type."','".$image."')";<br> @mysql_query($sqlstr) or die(mysql_error());<br><br> header('location:upload_image_todb.php');<br><br>}elseif($action=='show'){<br><br> $id = isset($_GET['id'])? intval($_GET['id']) : 0;<div class="clear"> </div>