Hey i have upload an image on my database (mysql) and i want to retrieve the blob image on a specific size.
until now with this code i can fully retrieve the image on the same dimensions that i have uploaded.
The uploaded image has the dimensions 1024X728.
I want the new image to have the dimensions 200X150.
Thank you

<?php
    require_once('connection.php');
 
    try {
        if (!isset($_GET['id'])) {
            throw new Exception('ID not specified');
        }
 
        $id = (int) $_GET['id'];
 
        if ($id <= 0) {
            throw new Exception('Invalid ID specified');
        }
 
        $query  = sprintf('select * from images where image_id = %d', $id);
        $result = mysql_query($query, $db);
 
        if (mysql_num_rows($result) == 0) {
            throw new Exception('Image with specified ID not found');
        }
 
        $image = mysql_fetch_array($result);
    }
    catch (Exception $ex) {
        header('HTTP/1.0 404 Not Found');
        exit;
    }
 
    header('Content-type: ' . $image['mime_type']);
    header('Content-length: ' . $image['file_size']);
 
    echo $image['file_data'];
?>

Dani AI

Generated

Short version: either resize when you upload and save a thumbnail (fast and simple, as and suggested), or resize on demand and cache the result. If you must resize "while retrieving the blob" (no filesystem thumbs), use GD or Imagick to decode the blob in memory, resize/crop, then stream the result. Also move off the old mysql_* API — use PDO or mysqli with prepared statements.

Example (on-the-fly resize + crop to 200x150 using PDO + GD):

// fetch blob with PDO, then resize in memory and send image
$stmt = $pdo->prepare('SELECT mime_type, file_data FROM images WHERE image_id = ? LIMIT 1');
$stmt->execute([$id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) { header('HTTP/1.0 404 Not Found'); exit; }

$src = imagecreatefromstring($row['file_data']);
if (!$src) { header('HTTP/1.0 415 Unsupported Media Type'); exit; }

$tw = 200; $th = 150;
$sw = imagesx($src); $sh = imagesy($src);
$src_aspect = $sw / $sh; $dst_aspect = $tw / $th;

// crop to fill, center-crop source
if ($src_aspect > $dst_aspect) {
  $new_h = $sh; $new_w = (int)($sh * $dst_aspect); $sx = (int)(($sw - $new_w) / 2); $sy = 0;
} else {
  $new_w = $sw; $new_h = (int)($sw / $dst_aspect); $sx = 0; $sy = (int)(($sh - $new_h) / 2);
}

$dst = imagecreatetruecolor($tw, $th);
imagealphablending($dst, false); imagesavealpha($dst, true);
imagecopyresampled($dst, $src, 0,0, $sx,$sy, $tw,$th, $new_w,$new_h);

ob_start();
if (stripos($row['mime_type'],'png') !== false) imagepng($dst);
elseif (stripos($row['mime_type'],'gif') !== false) imagegif($dst);
else imagejpeg($dst, null, 85);
$data = ob_get_clean();

header('Content-Type: '.$row['mime_type']);
header('Content-Length: '.strlen($data));
echo $data;

imagedestroy($src); imagedestroy($dst);

Troubleshooting & tips:

  • Ensure the GD (or Imagick) extension is installed and memory_limit is high enough for large originals.
  • Preserve PNG/GIF transparency (imagealphablending/imagesavealpha) as shown.
  • For production, prefer generating and caching thumbnails (filesystem or a cache column) rather than resizing on every request — cheaper CPU and faster responses.
  • Validate uploads with getimagesize() and always use prepared statements to avoid injection.
  • If you expect many sizes or higher quality, consider Imagick for better resampling and lower memory usage.

This approach gives exact 200x150 output while keeping the original image stored as a blob, and it complements the upload-time strategy already discussed by and .

Recommended Answers

All 2 Replies

It is better to upload image on server.
Then you can resize image to new thumb image.
And use that thumb image when you want to display on page.

try this code. when you upload an image crope the image and store it. then you retrive that image. i am explaing below code.first you create partners_logs folder and in that create subfolder 250x150.

1. <?
   2.     if(is_uploaded_file($_FILES["pimage"]["tmp_name"])!='')
   3.             {
   4.             //echo"file in";exit;
   5.             //echo"in ";exit;
   6.             $rand_variable1=rand(10000,100000);
   7.             if(is_uploaded_file($_FILES["pimage"]["tmp_name"]))
   8.             {
   9.                if($hidden_image!="")
  10.                {
  11.  
  12.                @unlink("partners_logs/".$hidden_image);
  13.                 @unlink("partners_logs/250x150/".$hidden_image);
  14.  
  15.                }
  16.             $file_image13=$rand_variable1.$_FILES["pimage"]["name"];
  17.             move_uploaded_file($_FILES["pimage"]["tmp_name"], "partners_logs/".$file_image13);
  18.  
  19.                 $Attachments3=$file_image13;
  20.  
  21.             }
  22.             /************************************Resizing the image 80*60****************/
  23.             $path3="partners_logs";
  24.             $filetype3=$_FILES["pimage"]["type"];
  25.             $bgim_file_name = $path3."/".$Attachments3; 
  26.             $bgimage_attribs = getimagesize($bgim_file_name);
  27.  
  28.             if($filetype3=='image/gif')    
  29.                 {
  30.                     $bgim_old = imagecreatefromgif($bgim_file_name); 
  31.                 }    
  32.             else if(($filetype3=='image/pjpeg') || ($filetype3=='image/jpeg'))    
  33.                 {
  34.                      $bgim_old = imagecreatefromjpeg($bgim_file_name);
  35.                 }
  36.               else    if(($filetype3=='image/png') || ($filetype3=='image/x-png'))
  37.                 {
  38.                      $bgim_old = imagecreatefrompng($bgim_file_name);
  39.                      imageAlphaBlending($bgim_old, true);
  40. imageSaveAlpha($bgim_old, true);
  41.                 }
  42.  
  43.             $bgth_max_width =265; //for Album image
  44.             $bgth_max_height =150;
  45.             $bgratio = ($bgwidth > $bgheight) ? $bgth_max_width/$bgimage_attribs[0] : $bgth_max_height/$bgimage_attribs[1];
  46.  
  47.             $bgth_width =265;//$image_attribs[0] * $ratio; 
  48.             $bgth_height =150;//$image_attribs[1] * $ratio;
  49.  
  50.             $bgim_new = imagecreatetruecolor($bgth_width,$bgth_height); 
  51.             imageantialias($bgim_new,true); 
  52.             $bgth_file_name = "partners_logs/250x150/$Attachments3";
  53.             imagecopyresampled($bgim_new,$bgim_old,0,0,0,0,$bgth_width,$bgth_height, $bgimage_attribs[0], $bgimage_attribs[1]);
  54.             if($filetype3=='image/gif')    
  55.                 {
  56.                     imagegif($bgim_new,$bgth_file_name,100);
  57.                     //$bgim_old = imagegif($bgim_file_name); 
  58.                 }    
  59.             else if(($filetype3=='image/pjpeg') || ($filetype3=='image/jpeg'))    
  60.                 {
  61.                      imagejpeg($bgim_new,$bgth_file_name,100);
  62.                 }
  63.               else    if(($filetype3=='image/png') || ($filetype3=='image/x-png'))
  64.                 {
  65.                      imagepng($bgim_new,$bgth_file_name,9);
  66.                        //set the background color to your choice, paramters are int values of red,green and blue  
  67. imagecolorallocate($bgim_new,0xFF,0xFF,0xFF);
  68.                 }                
  69.             /************End Resize of 80*60*******************/
  70.  
  71.             }
  72.          else
  73.         {
  74.         //echo"file out";exit;
  75.         $Attachments3=$hidden_image;
  76.         }
  77. ?>
  78. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  79. <html xmlns="http://www.w3.org/1999/xhtml">
  80. <head>
  81. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  82. <title>Untitled Document</title>
  83. </head>
  84.  
  85. <body>
  86. <form name="UserDetails" action="" method="post"  enctype="multipart/form-data" >
  87.            
  97.             <table width="50%"  border="0" cellspacing="0" cellpadding="4">
  98.            
 103.  
 104.  
 105.  
 106.             <tr align="center">
 107.               <td>&nbsp;</td>
 108.               <td align="left">Company Logo</td>
 109.               <td><strong>:</strong></td>
 110.               <td align="left"><input type="file" name="pimage" >
 111.                <input type="hidden" name="hidden_image" value="<?php echo $images ?>" ></td>
 112.               <td>&nbsp;</td>
 113.             </tr>
 114.            
 124.  
 125.  
 126.             <tr align="center">
 127.               <td width="5%" height="1">&nbsp;</td>
 128.               <td width="29%" height="1" align="left">&nbsp;</td>
 129.               <td width="3%" height="1">&nbsp;</td>
 130.               <td width="58%" height="1">&nbsp;</td>
 131.               <td width="5%" height="1">&nbsp;</td>
 132.             </tr>
 133.             <tr>
 134.               <td height="20" colspan="4" align="right">
 135.               <input type="submit" name=submit value="submit">
 136.                           
 138.  
 139.                           </td>
 140.               <td height="20" align="right">&nbsp;</td>
 141.             </tr>
 142.         </table>
 143.         </form>
 144. </body>
 145. </html>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.