如何从MySql数据库中检索图像?

I currently retrieve information from my database with JSON by doing this in my php file, let's call it getJson.php:

<?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);


?>

Then in my application I retrieve the JSON representation by using:

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

I also have binary image data stored as a BLOB which I would like to retrieve. However I cannot JSON encode this binary data in JSON, can I ?

My second option would have been keeping a URL to my image in the image field and then just call

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

Our Solution in 3 steps.

Step1. Create a dedicated php script that accepts a $_GET param 'imageId'

<?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.';
} 

?>

Step2. Modify your 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);    
?>

Step3 - IOS end - showing the image

The image url is present in your repsponse array (i think postsArray). You just have to treat the image url in each row just like a normal image!

Notes:

  • GD library should be enabled in php.
  • We can do more optimizations. But this approach will work.