圖片跟二進位之間的轉換

來源:互聯網
上載者:User
圖片和二進位之間的轉換
將圖片轉換成二進位儲存在資料庫中,代碼如下:
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]);

我應該怎麼去轉換成圖片並顯示出來呢?求大神幫忙
------解決思路----------------------
寫了一個完整的例子,可以參考下。
資料表結構

CREATE TABLE `photo` (
`id` int(10) unsigned NOT NULL auto_increment,
`type` varchar(100) NOT NULL,
`photo` mediumblob NOT NULL,
PRIMARY KEY (`id`)
)


upload_image_todb.php

[email protected]_connect("資料庫ip","帳號","密碼") or die(mysql_error());
@mysql_select_db('資料庫名',$conn) or die(mysql_error());

$action = isset($_REQUEST['action'])? $_REQUEST['action'] : '';

if($action=='add'){
$image = mysql_escape_string(file_get_contents($_FILES['photo']['tmp_name']));
$type = $_FILES['photo']['type'];
$sqlstr = "insert into photo(type,photo) values('".$type."','".$image."')";
@mysql_query($sqlstr) or die(mysql_error());

header('location:upload_image_todb.php');

}elseif($action=='show'){

$id = isset($_GET['id'])? intval($_GET['id']) : 0;
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.