arsenallavigne
arsenallavigne

Reputation: 141

Imagick PHP (How to resize each image from database?)

I have been trying to resize each image from database before pushing it into an array. The array contains the image path(URL) where I would like to display the resize image onto a grid view as the original images are too big and takes too long to load, hence the resizing. I have been figuring out the logic and still couldn't solve it. Could anyone help me with this? My database contains columns 'photo' and 'location'.

getphoto.php

<?php

require_once('dbConnect.php');

$sql = "select * from volleyupload1";
$res = mysqli_query($con, $sql);

$result = array();

while ($row = mysqli_fetch_array($res)) {
    foreach ($result as $row['photo']) {
        $imagick = new Imagick($row['photo']);
        $imagick->thumbnailImage(300, 300, true, true);
        header("Content-Type: image/jpg");
//    echo $imagick;
    }
    array_push($result, array('url' => $row['photo'], 'location' => $row['location']));
//     $test = $row['photo'];
//   foreach ($result as $row['photo']){
//     $imagick = new Imagick($row['photo']);
//    $imagick->thumbnailImage(300, 300, true, true);
//    header("Content-Type: image/jpg");
//        echo $imagick;
//
//     }
}


echo json_encode(array("result" => $result));

mysqli_close($con);

Upvotes: 0

Views: 131

Answers (1)

Iarwa1n
Iarwa1n

Reputation: 460

I don't get the difference between 'photo' and 'location'. To the browser you should only send URLs not local filepaths.

Anyway, you need to store the thumbnail image to a new file and then return the url to this file instead of the original one.

Could look like this:

while ($row = mysqli_fetch_array($res)) {
    $imagick = new Imagick($row['photo']);
    $imagick->thumbnailImage(300, 300, true, true);

    $thumb_path = $row['photo'] . '.thumb.jpg';
    $thumb = fopen($thumb_path, 'w'); //open new filehandle to write the thumb
    $imagick->writeImageFile($thumb);
    fclose($thumb);

    array_push($result, array('url' => $thumb_path, 'location' => $row['location']));

}

$thumb_path needs to be a local file path. To the browser you need to send a URL which is reachable from the internet

Upvotes: 0

Related Questions