2013-01-24 69 views
1

我目前在我的PHP文件做這個檢索我的JSON數據庫的信息,讓我們把它getJson.php:如何從MySql數據庫檢索圖像?

<?php 
    include ("config.php"); 

    $query = "SELECT id,title,text,image,date FROM posts"; 
    $result = mysql_query($query) or die(mysql_error()); 

    $num = mysql_num_rows($result); 

    $rows = array(); 
    while ($r = mysql_fetch_assoc($result)){ 
     $rows[] = $r; 
    } 


    echo json_encode($rows); 


?> 

然後在我的應用程序獲取JSON表示通過使用:

NSURL *url = [NSURL URLWithString:kGETUrlPosts]; 
NSData *data = [NSData dataWithContentsOfURL:url]; 
NSError *error; 
postsArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 

我也有二進制圖像數據存儲爲一個BLOB,我想檢索。然而,我不能JSON編碼這個二進制數據在JSON中,我可以嗎?

我的第二個選擇是已經在圖像領域一直保持一個URL到我的圖像,然後只需調用

UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"www.myURL.com/MyPhotos/somephoto.png"]]]; 
+0

使用基數64對圖像數據進行編碼。不言而喻,將圖像數據存儲在數據庫中並不是一個好主意。 – datasage

+0

將URL存儲在您的數據庫中是最好的選擇。 –

+1

最好的解決方案是將圖像複製到文件夾並將路徑和圖像名稱保存到數據庫中。如果您將圖片上傳到數據庫,並且您有許多用戶,則閱讀需要更多時間。 – jcho360

回答

0

我們在步驟的解決方案。

Step1。創建一個專用的PHP腳本,接受一個$ _GET PARAM '圖像標識'

<?php 
//Lets call this script as 'getImage.php'. 
//This script should be publicly accessible 
//Example format: http://www.yourdomain.com/getImage.php?imageId=2 

include ("config.php"); 
$query = "SELECT image FROM posts WHERE id=" . mysql_real_escape_string($_GET['imageId']); 
$result = mysql_query($query) or die(mysql_error()); 
$r = mysql_fetch_assoc($result); 

//display the image 
$im = imagecreatefromstring($r['image']); 
if ($im !== false) { 
    // I assume you use only jpg 
    //You may have to modify this block if you use some othe image format 
    //visit: http://php.net/manual/en/function.imagejpeg.php 
    header('Content-Type: image/jpeg'); 
    imagejpeg($im); 
    imagedestroy($im); 
} else { 
    echo 'error.'; 
} 

?> 

第二步。修改getJson.php

<?php 
    include ("config.php"); 

    //Notice the change in query. 
    $query = "SELECT id,title,text,date FROM posts"; 
    $result = mysql_query($query) or die(mysql_error()); 

    $num = mysql_num_rows($result); 

    $rows = array(); 
    while ($r = mysql_fetch_assoc($result)){ 
     //Please replace below url with your real server url. 
     $r['image'] = 'http://www.yourdomain.com/getImage.php?imageId=' . $r['id']; 
     $rows[] = $r; 
    } 

    echo json_encode($rows);  
?> 

步驟3 - IOS端 - 表示圖像

圖像URL存在於您的repsponse陣列(我認爲postsArray)。你只需要像普通圖像一樣對待每一行中的圖像url!

注:

  • GD library應該在PHP中啓用。
  • 我們可以做更多的優化。但是這種方法將起作用。
+0

嗨@馬丁E.請讓我知道它是如何去。 – OMG