Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9267323
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T14:31:27+00:00 2026-06-18T14:31:27+00:00

I’ve got a script which caches images from an external feed and stores them

  • 0

I’ve got a script which caches images from an external feed and stores them in a directory on my server when the image is viewed on site.

At the moment it is working great – storing the original image on my server and also creating two additional thumbnails, with their widths re-sized at 300px and 150px.

I’d like to change this slightly so that the following occurs:

  1. Full/Original image is stored on server (as normal)
  2. Both a square 300x300px & 150x150px .jpg thumbnail are created

However, is it possible, so that once the image width/height is resized, the additional canvas width/height is then added to make it completely square? I guess one of the issues here is determining if the image is a ‘portrait’ or ‘landscape’ first?

Also, currently I’m getting a black background with transparent PNG images. Is there any way to overcome this and fill the background with white instead?

Thank you very much for any help!! 🙂

Here is the code which is doing the resizing (imageCache.php):

<?php
  function cacheFetch($url,$size,$age)
  {
// directory in which to store cached files, must be writable by PHP
$cacheDir = "cache/";
// cache filename constructed from MD5 hash of URL
$filename = $cacheDir.md5($url);
// append size to filename if not 0
if ($size) $filename .= "_".$size;
// default to fetch the file
$fetch = true;
// but if the file exists, don't fetch if it is recent enough
if (file_exists($filename))
{
  $fetch = (filemtime($filename) < (time()-$age));
}
// fetch the file if required
if ($fetch)
{
  if (substr($url,0,4)=="http")
  {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    $data = curl_exec($ch);
    curl_close($ch);
    if (strlen($data))
    {
      $fp = fopen($filename,"w");
      fwrite($fp,$data);
      fclose($fp);
      $error = false;
    }
    else
    {
      $error = true;
    }
  }
  else
  {
    copy($url,$filename);
    $error = false;
  }
}
// return the filename only if wget did not fail
if (!$error)
{
  if ($size)
  {
    $src = file_get_contents($filename);
    $oldImage = imagecreatefromstring($src);
    $oldX = imagesx($oldImage);
    $oldY = imagesy($oldImage);
    if ($oldX && $oldY)
    {
      $newX = $size;
      $xFactor = ($newX / $oldX);
      $newY = intval($oldY * $xFactor);
      $newImage = imagecreatetruecolor($newX,$newY);
      imagecopyresized($newImage, $oldImage, 0,0,0,0, $newX, $newY, $oldX, $oldY);
      imagejpeg($newImage,$filename);
    }
  }
  return $filename;
}
else
{
  // as an error occured, delete the empty file so it is retried next time
  unlink($filename);
  // return false
  return false;
}
}
require("includes/common.php");

$id = $_GET["id"];

$size = $_GET["size"];

$sql = "SELECT image_url FROM `".$config_databaseTablePrefix."products` WHERE id='".database_safe($id)."'";
if (database_querySelect($sql,$rows))
{
$src = $rows[0]["image_url"];

$src = cacheFetch($src,$size,604800);

$img = file_get_contents($src);

header("Content-Type: image");

print $img;
  }
?>

and here is the .htaccess bit with sizes:

RewriteRule ^fullimage/(.*).jpg$ imageCache.php?id=$1&size=0 [L]
RewriteRule ^smallimage/(.*).jpg$ imageCache.php?id=$1&size=150 [L]
RewriteRule ^mediumimage/(.*).jpg$ imageCache.php?id=$1&size=300 [L]

EDIT: Re-worked code:

if ($size)
{
    $src = file_get_contents($filename);
    $oldImage = imagecreatefromstring($src);
    $oldX = imagesx($oldImage);
    $oldY = imagesy($oldImage);
    if ($oldX && $oldY)
    {
      $color = imagecolorallocate($newImage, 255,255,255);  //The three parameters are R,G,B
  imagefilledrectangle ($newImage, 0, 0, $newX,  $newY,$color);
      $size = max($newX,$newY);
      $newImage = imagecreatetruecolor($newX,$newY);
      imagecopyresized($newImage, $oldImage, ($size-$newX)/2,($size-$newY)/2,0,0, $newX, $newY, $oldX, $oldY);  //Just the coordinates was changed
      imagejpeg($newImage,$filename);
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T14:31:28+00:00Added an answer on June 18, 2026 at 2:31 pm

    Sorry, I will not add my sugestions to your code, because its is too complicated. SO just the hints.

    1. How to make resised image square?

    Obviously, we must create square of size of bigger dimension of original image. Here I assume the image has already been resized.

    $resized = /*We hae resized image downloaded from the site [note1]*/;
    $size = max(imagesx($resized), imagesy($resized)); //Make the square so the thumbnail fits in it
    $thumbNail = imagecreate($size, $size);  //Square.
    imagecopy($thumbNail, 
              ($size-imagesx($resized))/2,   //Put the image in the middle of the square
              ($size-imagesy($resized))/2, 
              0,
              0,
              imagesx($resized),
              imagesy($resized)  
    );
    

    [note1] Alternativelly, you can just compute dimensions to make $size and copyresize image on the square. This will be faster, but is more complicated to make pseudocode for it.

    2. How to change background of new images

    This is no real mystery – you just draw rectangle over whole image:

    $color = imagecolorallocate($thumbNail, 255,255,255);
    imagefilledrectangle ($thumbNail, 0, 0, imagesx($thumbNail),  imagesy($thumbNail),$color);
    

    You can even have a transparent background:

    $color = imagecolorallocatealpha($thumbNail, 255,255,255,127);
    imagealphablending($thumbNail, false);  //[note2]
    imagefilledrectangle ($thumbNail, 0, 0, imagesx($thumbNail),  imagesy($thumbNail),$color);
    imagealphablending($thumbNail, true);  //If you use it
    

    [note2] Turn off blending, because transparent+black = black again

    3. Code related to answer

    First the resizing, copying. In the original code, we have the computed new height and width in $newX and $newY. I will use theese as of the new image sizes.

    $size = max($newX,$newY);
    $newImage = imagecreatetruecolor($size, $size);
    imagecopyresized($newImage, $oldImage, ($size-$newX)/2,($size-$newY)/2,0,0, $newX, $newY, $oldX, $oldY);  //Just the coordinates was changed
    

    Then he background. Obviously, you should firs set the background, then copy the image. However, I’m separating theese steps so you can see what function does what.

     $newImage = imagecreatetruecolor($newX,$newY);
     $color = imagecolorallocate($newImage, 255,255,255);  //The three parameters are R,G,B
     imagefilledrectangle ($newImage, 0, 0, $newX,  $newY,$color);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have an autohotkey script which looks up a word in a bilingual dictionary
I have a text area in my form which accepts all possible characters from
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am using JSon response to parse title,date content and thumbnail images and place
For some reason, after submitting a string like this Jack’s Spindle from a text
I used javascript for loading a picture on my website depending on which small
I have a small JavaScript validation script that validates inputs based on Regex. I
I've got a string that has curly quotes in it. I'd like to replace

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.