note 56668 rejected from function.imagecreatefromstring by derek

From: Date: Mon, 12 Sep 2005 02:13:03 +0000
Subject: note 56668 rejected from function.imagecreatefromstring by derek
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-95029@lists.php.net to get a copy of this message
Note Submitter: citizenkahn at gmail dot com ---- I am storing images in a mysql database and wanted to scale them to be at a thumbnail and regular size. It was quiet difficult for me to locate an appopriate example. It is my hope the next poor fool searching on mysql database thumbnail and image jped or bmp will find this and not wander as much as I did. Pseudo code: 1. obtain user params 2. query db for binary object that is jpeg file 3. resize object is called for 4. output image hope this is of assistance. <?php // view.php?file=<id>&scale=<real number for scale size // Retrieve raw BLOB for image assuming JPEG // TODO: put in switch statement logic for multiple types // Note this is written with php4 with mysql and gd include 'db.inc'; // Secure the user data by escaping characters // and shortening the input string $file = clean($_GET['file'], 4); $scale = clean($_GET['scale'], 4); // file db id is required if (empty($file)) exit; // default scale 1.0 if (empty($scale)) $scale = 1.0; // Connect to DB and obtain BLOB for JPEG if (!($connection = @ mysql_pconnect($hostName, $username, $password))) showerror(); if (!mysql_select_db("test", $connection)) showerror(); $query = "SELECT mimeType, fileContents FROM files WHERE id = $file"; if (!($result = @ mysql_query ($query,$connection))) showerror(); $data = @ mysql_fetch_array($result); // Found blob? if (!empty($data["fileContents"])) { // convert binary data into image object // to allow for manipulation via GD image routines $img=imagecreatefromstring($data["fileContents"]); // Get image size and scale ratio $width = imagesx($img); $height = imagesy($img); // calculate new scale $new_width = floor($scale*$width); $new_height = floor($scale*$height); if ($width != $new_width) { // Create a new temporary image $tmp_img = imagecreatetruecolor($new_width, $new_height); // Copy and resize old image into new image imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height); imagedestroy($img); $img = $tmp_img; } // Output the MIME header header("Content-Type: {$data["mimeType"]}"); imagejpeg($img); imagedestroy($img); } ?>

« previous php.notes (#95029) next »