You are here:  » Image Caching with resize and proxy only mode


Image Caching with resize and proxy only mode

Submitted by support on Sun, 2015-10-04 12:16 in

Hi everyone,

I've collated the most frequent requests (resizing and more recently proxy only mode) into a single new version that combines these features as required. With merchant image sizes and aspect ratios varying widely, this new version supports tidy resizing to a fixed perfectly square image padded either top and bottom or left and right depending on the dimensions of the original image. For search results with considerable variation in merchant image dimensions this can improve the aesthetics of the search results considerably. To enable resizing, change the $imageCacheResize variable from FALSE to an integer value of the size required, e.g:

  $imageCacheResize = 250;

Proxy mode is something that has come about more recently with the move towards the secure web and search engines encouraging the use of https as standard. Most web browsers will display an exclamation mark icon in the address bar if an https page includes non-https resources - not a good look - so this feature enables you to use the script (with optional resizing) whilst only taking the bandwidth hit for image delivery rather than bandwidth + storage requirements. To use the script in proxy only mode, simply change the value of $imageCacheTime to 0:

  $imageCacheTime = 0;

This version also makes use of the $config_automationHandler variable, to support source image fetching using either PHP internal URL wrappers or CURL.

imageCache.php

<?php
  
require("includes/common.php");
  
$imageCacheDir "cache/"// set to writable folder for image cache storage
  
$imageCacheTime 604800;  // cache period in seconds, set to zero for proxy only mode
  
$imageCacheResize FALSE// set to resize dimension to enable  e.g. $imageCacheResize = 250;
  
function cacheFetch_auto($src)
  {
    if (
function_exists("curl_init"))
    {
      return 
cacheFetch_curl($src);
    }
    else
    {
      return 
cacheFetch_php($src);
    }
  }
  function 
cacheFetch_curl($src)
  {
    
$ch curl_init($src);
    
curl_setopt($ch,CURLOPT_HEADER,0);
    
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,TRUE);
    
curl_setopt($chCURLOPT_RETURNTRANSFER1);
    
$img curl_exec($ch);
    return 
$img;
  }
  function 
cacheFetch_php($src)
  {
    return 
file_get_contents($src);
  }
  function 
cacheFetch($src)
  {
    global 
$config_automationHandler;
    global 
$imageCacheDir;
    global 
$imageCacheTime;
    global 
$imageCacheResize;
    
$filename $imageCacheDir.md5($src);
    
$fetch = (
      (!
$imageCacheTime)
      ||
      (!
file_exists($filename))
      ||
      (
filemtime($filename) < (time()-$imageCacheTime))
      );
    if (
$fetch)
    {
      
$cacheFetch_fn "cacheFetch_".$config_automationHandler;
      
$img $cacheFetch_fn($src);
    }
    else
    {
      
$img file_get_contents($filename);
    }
    if (!
$res = @imagecreatefromstring($img)) return FALSE;
    if (
$imageCacheResize)
    {
      
$oldX imagesx($res);
      
$oldY imagesy($res);
      
$new imagecreatetruecolor($imageCacheResize,$imageCacheResize);
      
$newBackground imagecolorallocate($new,255,255,255);
      
imagefill($new,1,1,$newBackground);
      if (
$oldX $oldY)
      {
        
$newX $imageCacheResize;
        
$xMultiplier = ($newX $oldX);
        
$newY intval($oldY $xMultiplier);
        
$dstX 0;
        
$dstY = ($imageCacheResize 2) - ($newY 2);
      }
      else
      {
        
$newY $imageCacheResize;
        
$yMultiplier = ($newY $oldY);
        
$newX intval($oldX $yMultiplier);
        
$dstX = ($imageCacheResize/2)-($newX/2);
        
$dstY 0;
      }
      
imagecopyresized($new,$res,$dstX,$dstY,0,0,$newX,$newY,$oldX,$oldY);
      
ob_start();
      
imagepng($new);
      
$img ob_get_contents();
      
ob_end_clean();
    }
    if (
$fetch && $imageCacheTime)
    {
      
$fp fopen($filename,"w");
      
fwrite($fp,$img);
      
fclose($fp);
    }
    return 
$img;
  }
  
$src base64_decode($_GET["src"]);
  if (!
$img cacheFetch($src))
  {
    
header("HTTP/1.0 404 Not Found");
    exit();
  }
  else
  {
    
header("Content-Type: image");
    print 
$img;
    exit();
  }
?>

To implement image caching for Featured Products; look for the following code for the src attribute of the img tag at line 17 of html/featured.php:

src='<?php print htmlspecialchars($product["image_url"],ENT_QUOTES,$config_charset); ?>'

...and REPLACE with:

src='<?php print $config_baseHREF."imageCache.php?src=".base64_encode($product["image_url"]); ?>'

For Search Results, look for the following code for the src attribute of the img tag at line 19 of html/searchresults.php:

src='<?php print htmlspecialchars($product["image_url"],ENT_QUOTES,$config_charset); ?>'

...and REPLACE with:

src='<?php print $config_baseHREF."imageCache.php?src=".base64_encode($product["image_url"]); ?>'

And for the main product image, look for the following code for the src attribute of the img tag at line 32 of html/product.php:

src='<?php print htmlspecialchars($product_main["image_url"],ENT_QUOTES,$config_charset); ?>'

...and REPLACE with:

src='<?php print $config_baseHREF."imageCache.php?src=".base64_encode($product_main["image_url"]); ?>'

Proxy only mode only for non-https URLs

To implement proxy only mode and only for non-https image URLs on an https installation, a PHP ternary (short-hand if/then/else) can be used to render either the https or imageCache URL as required, for example for Featured Products, look for the following code for the src attribute of the img tag at line 17 of html/featured.php:

src='<?php print htmlspecialchars($product["image_url"],ENT_QUOTES,$config_charset); ?>'

...and REPLACE with:

src='<?php print (strpos($product["image_url"],"https")===FALSE?
           $config_baseHREF."imageCache.php?src=".base64_encode($product["image_url"]):
           htmlspecialchars($product["image_url"],ENT_QUOTES,$config_charset)); ?>'

Cheers!
David
--
PriceTapestry.com

Submitted by keshavkshirsagar on Wed, 2015-10-07 11:31

Hello David

Can we add image extension for cathced image
So I can add cache validator

Submitted by support on Wed, 2015-10-07 12:10

Hi,

Sure - only the one change required to include an extension in the cached filename, where you have the following code at line 36:

  $filename = $imageCacheDir.md5($src);

...REPLACE with:

  $filename = $imageCacheDir.md5($src).".png";

Cheers,
David.
--
PriceTapestry.com

Submitted by keshavkshirsagar on Wed, 2015-10-07 13:03

Hi David,

Thanks - works well.

Submitted by keshavkshirsagar on Mon, 2015-10-12 08:48

Hello David

If image not found how to set default no_image

Submitted by support on Mon, 2015-10-12 09:42

Hi,

If you upload your default fall-back image as

images/no-image.png

Then where you have the following code at line 53:

  if (!$res = imagecreatefromstring($img)) return FALSE;

...REPLACE with:

  if (!$res = imagecreatefromstring($img))
  {
    return file_get_contents("images/no-image.png");
  }

Cheers,
David.
--
PriceTapestry.com

Submitted by keshavkshirsagar on Mon, 2015-10-12 12:24

Thanks for your quick support

Submitted by wesse249 on Mon, 2015-10-12 18:48

Hello,

I placed imageCache.php in the root and made the changes in featured, searchresults and products. But when i upload it al the images are gone.

Greetings Jan Roel

Submitted by support on Tue, 2015-10-13 08:06

Hello Jan,

It may be that the cache/ folder is not writable by PHP. The easiest way to do this is normally using your FTP program. In the remote window, right-click on the cache/ folder and look for Permissions... or maybe Properties... and then Permissions. Then give WRITE access to all users (Owner / Group / World) and that should be all it is...

Cheers,
David.
--
PriceTapestry.com

Submitted by wesse249 on Thu, 2015-10-15 07:49

Hello David,

I work a lot with subdomains. http://www.pricetapestry.com/node/5653

But the images aren't cached in the subdain cache folder. Do i have to change this line?

require("includes/common.php");

Because this is my common.php:

{code saved}

Submitted by support on Thu, 2015-10-15 08:13

Hello Jan,

The cache/ folder is relative to the script as executed so they should be saving in the individual cache/ folder of each sub-domain. Is caching working, but images are all being saved in a single folder due to the setup?

Cheers,
David.
--
PriceTapestry.com

Submitted by wesse249 on Thu, 2015-10-15 20:37

How can i check if it works? My cache folder is empty. I made him writeable to 777.

Further is made al changes to featured, searchresults and product in HTML

Submitted by support on Fri, 2015-10-16 08:28

Hello Jan,

Having made the changes, are images displaying correctly on your site?

What value are you using for $imageCacheTime? If that was set to zero for proxy only mode then no files would appear in the cache/ folder. if you'd like me to take a look at your site let me know an installation URL where imageCache.php is in use (I'll remove before publishing your reply) and I'll check it out for you...

Cheers,
David.
--
PriceTapestry.com

Submitted by keshavkshirsagar on Wed, 2015-11-04 07:51

Hi David,

1. How We Can stop image Cache if image already Cached previously ?

2. And Can We set name of Cached img with product name with its id ?

Submitted by support on Wed, 2015-11-04 08:54

Hi,

To prevent fetching of images cached previously is essentially caching for an unlimited period, so the fetching logic can simply be reduced to just whether or not the file exists; so where you have this code beginning at line 37:

    $fetch = (
      (!$imageCacheTime)
      ||
      (!file_exists($filename))
      ||
      (filemtime($filename) < (time()-$imageCacheTime))
      );

...REPLACE with just:

    $fetch = (
      (!file_exists($filename))
      );

If you would prefer to pass the product name through rather than image URL (perhaps for SEO purposes) then using name as the parameter in place of src, within your html/ files where you have added calls to imageCache.php e.g.

src='<?php print $config_baseHREF."imageCache.php?src=".base64_encode($product["image_url"]); ?>'

...use:

src='<?php print $config_baseHREF."imageCache.php?name=".tapestry_hyphenate($product["normalised_name"]); ?>'

...or for the main product image in html/product.php:

src='<?php print $config_baseHREF."imageCache.php?name=".tapestry_hyphenate($product_main["normalised_name"]); ?>'

And then in imageCache.php at line 91:

  $src = base64_decode($_GET["src"]);

...REPLACE with:

  $src = "";
  $name = tapestry_normalise($_GET["name"]);
  $sql = "SELECT image_url FROM `".$config_databaseTablePrefix."products` WHERE normalised_name = '".database_safe($name)."' AND image_url <> '' ORDER BY price ASC";
  if (database_querySelect($sql,$rows))
  {
    $src = $rows[0]["image_url"];
  }

Ordering by price will ensure that the same image is used in all instances...

Cheers,
David.
--
PriceTapestry.com

Submitted by keshavkshirsagar on Wed, 2015-11-04 11:17

Thanks David

Submitted by wesse249 on Thu, 2015-12-10 10:20

Hello David,

Images aren't showed. Map Cache is writeable 777. It also contains files.

But image aren't showed up. {link saved}

Do you have an answer?

Thanks Jan Roel

Submitted by support on Thu, 2015-12-10 11:11

Hello Jan,

I looks like your imageCache.php script has content outside of the <?php and ?> tags - possibly UTF-8 "Byte Order Markers". Open the file in your text editor, and first make sure that there are no new-lines or white space outside of the PHP code. Next, use your editor's File > Save As... menu and on the dialog look for a Character Encoding drop-down and see if you have a "UTF-8 NO BOM" option. Alternatively, "Include Byte Order Markers" may be an option in your editor's configuration, and if set disable the setting, save and re-upload the file and that should be all it is.

If still no joy, if you could email me your imageCache.php I'll check it out further for you...

Cheers,
David.
--
PriceTapestry.com

Submitted by wesse249 on Thu, 2015-12-10 11:14

Thank you very much. That was the problem.

Submitted by philstone on Thu, 2015-12-10 14:56

Hi David

I was wondering is there a way to stop .png or .gif (transparent product images) coming up with a black background? using imagecache.php?

Thanks

Phil

Submitted by support on Thu, 2015-12-10 15:17

Hi Phil,

I assume that's a function of using resize, so where you have the following line:

      $newBackground = imagecolorallocate($new,255,255,255);

...REPLACE with:

      $newBackground = imagecolorallocatealpha($new,255,255,255,127);

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by philstone on Thu, 2015-12-10 15:49

Thanks David

I will try this!!

P

Submitted by dflsports on Wed, 2015-12-30 04:58

Hello. The image caching works fine until I try to implement the "If you would prefer to pass the product name through rather than image URL (perhaps for SEO purposes) then using name as the parameter in place of src, within your html/ files where you have added calls to imageCache.php "

I added the code the following to product.php

src='<?php print $config_baseHREF."imageCache.php?name=".tapestry_hyphenate($product["normalised_name"]); ?>'

and to imageCache
$src = "";
  $name = tapestry_normalise($_GET["name"]);
  $sql = "SELECT image_url FROM `".$config_databaseTablePrefix."products` WHERE normalised_name = '".database_safe($name)."' AND image_url <> '' ORDER BY price ASC";
  if (database_querySelect($sql,$rows))
  {
    $src = $rows[0]["image_url"];
  }

Image links broken "<img alt="Image of Nebo Slyde" src="/imageCache.php?name=" data-pin-nopin="true">'

I see the following in the errlog

[30-Dec-2015 04:16:55 UTC] PHP Warning: imagecreatefromstring(): Empty string or invalid image in /home/XXX/public_html/imageCache.php on line 53
[30-Dec-2015 04:16:55 UTC] PHP Warning: Cannot modify header information - headers already sent by (output started at /home/XXX/public_html/imageCache.php:53) in /home/XXX/public_html/imageCache.php on line 100

Any assistance is appreciated.

Submitted by support on Wed, 2015-12-30 09:09

Hi dflsports,

My apologies - for the product page (html/product.php) the $product_main variable should be used instead of $product - have a go with:

src='<?php print $config_baseHREF."imageCache.php?name=".tapestry_hyphenate($product_main["normalised_name"]); ?>'

Now updated in the original post also...

Cheers,
David.
--
PriceTapestry.com

Submitted by stevebi on Wed, 2015-12-30 09:15

Hello David,

May I ask if I can apply image caching at my distribution and if I will need more disc space?

It will definitely help a lot

Great work

Cheers

Steve

Submitted by support on Wed, 2015-12-30 09:24

Hi Steve,

Assuming an average image size of say, 25K (25000 bytes) the disk space required would be approximately this times by the number of products on your site, so for an installation of 100,000 products this would be about 2.5GB. You can check the disk space available on your server using the disk free (df) command:

df -h

The -h flag displays the volume information in human readable format e.g. MB / GB rather than blocks...

Cheers,
David.
--
PriceTapestry.com

Submitted by stevebi on Wed, 2015-12-30 11:15

Thank you very much David,

And since I have several sites sharing the same database can I create an image folder from which all the websites will retrieve cached images?

Cheers

Steve

Submitted by support on Wed, 2015-12-30 12:00

Hello Steve,

Sure - the simplest approach would simply be to have your sub-domain installation image URLs point to the imageCache.php of the www. installation, so in the modifications to the html/ files to use imageCache.php in place of:

$config_baseHREF

...you would use:

"http://www.example.com/"

If you wanted to avoid linking between installations in that way an alternative option would be to create a new sub-domain on which to host imageCache.php, for example:

http://images.example.com/

You would not need to put a Price Tapestry installation in this sub-domain host, simply create the cache/ folder as usual, make sure it is writeable, and then upload imageCache.php modified as follows - where you have the following code at line 2:

  require("includes/common.php");

...REPLACE with:

  $config_automationHandler = "auto";

(to get the value of that variable is the only reason the require() is included)

Then, just as above to use the images. subdomain, in your modifications to the html/ files in place of:

$config_baseHREF

...you would use:

"http://images.example.com/"

(note the quotation marks in the above - these are required as you are replacing a variable with a string...)

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by stevebi on Wed, 2015-12-30 22:08

Hello David,

May I ask if and how I could apply a subdomain folder for merchant logos?

Because currently for every feed that I am adding I have to upload 4 times the same logo which means 4 folders with same images

Cheers

Steve

Submitted by dflsports on Thu, 2015-12-31 01:47

Thanks David! New code works like a charm!

Regards,

Don

Submitted by support on Thu, 2015-12-31 09:13

Hi Steve,

Sure - if you've made the images. subdomain for cached images as described above you can make a logos/ folder within that host and serve merchant logos for all your sites from the one location.

I know that your hosting set-up maps sub-directories to sub-domains and I've just realised that the suggestion of an images. sub-domain would conflict with the images/ sub-directory of a Price Tapestry installation so an alternative might be media e.g.

http://media.example.com/

- for imageCache.php and cache/ folder, and

http://media.example.com/logos/

With this set-up, the physical location of logo files within your hosting account would be

/home/example/public_html/media/logos/

To apply the changes within the files, first edit includes/tapestry.php and look for the following code at line 490:

  if (file_exists((is_dir("logos")?"logos/":"../logos/").$filename))

...and REPLACE with:

  if (file_exists("/home/example/public_html/media/logos/".$filename))

And then in html/prices.php look for the src attribute of the logo img tag at line 49:

  src='<?php print $config_baseHREF."logos/".$logoFilename?>'

...and REPLACE with:

  src='http://media.example.com/logos/<?php print $logoFilename?>'

And in merchants.php look for the following code at line 15:

  $item["logo"] = $config_baseHREF."logos/".$logoFilename;

...and REPLACE with:

  $item["logo"] = "http://media.example.com/logos/".$logoFilename;

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by wesse249 on Sat, 2016-01-09 20:27

Hello David,

When i add the cache src to my file searchresults.php the page is never stopping loading? When i replace

<?php
 
print $config_baseHREF."imageCache.php?src=".base64_encode($product["image_url"]); 
?>
' /> with orginal one then it stops.

Do you know how this is possible?

This is the code of my page:

{code saved}

Submitted by support on Mon, 2016-01-11 09:14

Hello Jan,

The page appearing to load continuously would indicate at least one of the imageCache.php image requests taking a long time to load. I have come across instances where, and i'm not yet entirely sure why, passing of the image URL using base64 encoding is resulting in corruption of the URL, so the first thing I would suggest is to pass using standard URL encoding instead.

To try this, in your imageCache.php file, replace base64_decode with urldecode and in your replacement to the html/ files, replace base64_encode with urlencode and that might do the trick. I am currently investigating this further, together with issues regarding extended utf-8 characters (e.g. accented vowels) that appear to be related...

Cheers,
David.
--
PriceTapestry.com

Submitted by keshavkshirsagar on Mon, 2016-03-21 06:30

Hello David

Cached Images load quickly, But when images will cached newly it will take time to load on browser
because it will store first in cache folder then it will load

Now My question is How we can add image Lazy Load concept for this situation ?

Submitted by support on Mon, 2016-03-21 09:52

Hi,

It looks like there are a few Lazy Load jQuery extensions, for example this one but there are a number of them available. They work by having the image URL in a data attribute rather than the src attribute of an img tag, and then the lazyload function attached to such images via JavaScript / jQuery at the end of the page.

Firstly make sure that your chosen script is loaded in the header. Add the necessary code to html/header.php e.g.

  <script src='<?php print $config_baseHREF?>html/vendor/jquery.lazyload.js'></script>

And then to modify search results image tags, edit html/searchresults.php and locate the src attribute of the img tag around line 18:

src='<?php print htmlspecialchars($product["image_url"],ENT_QUOTES,$config_charset); ?>'

...and replace with:

class='lazy' data-original='<?php print htmlspecialchars($product["image_url"],ENT_QUOTES,$config_charset); ?>'

And then finally in html/footer.php

<script type='text/JavaScript'>
$(function() {
    $("img.lazy").lazyload();
});
</script>

Hope this points you in the right direction!

Cheers,
David.
--
PriceTapestry.com

Submitted by keshavkshirsagar on Mon, 2016-03-28 11:08

Thanks David

Submitted by keshavkshirsagar on Tue, 2016-08-09 17:47

Hello David

Can we store original size image in Cache folder
What will be value for $imageCacheResize to store original image?

Submitted by support on Wed, 2016-08-10 08:24

Hi,

Use;

  $imageCacheResize = FALSE;

...to disable resizing.

Cheers,
David.
--
PriceTapestry.com

Submitted by keshavkshirsagar on Sat, 2016-08-13 11:38

Thanks David

Submitted by sirmanu on Thu, 2016-09-22 23:02

Sometimes, I get this warning:

"PHP Warning: imagecreatefromstring(): Data is not in a recognized format in /imageCache.php on line 54"

Line 54 is
if (!$res = imagecreatefromstring($img)) return FALSE;

http://php.net/manual/en/function.imagecreatefromstring.php

As I see is because sometimes the images are down (404 not found). Is it possible that in order to avoid this error, set up a generic image from my images folder?

Submitted by support on Fri, 2016-09-23 08:39

Hi,

Sure - upload your generic "no image" image as, for example images/generic.jpg and then in place of the following code that issues the 404;

    header("HTTP/1.0 404 Not Found");
    exit();

...have a go with:

    $img = file_get_contents("images/generic.jpg");
    header("Content-Type: image");
    print $img;
    exit();

Cheers,
David.
--
PriceTapestry.com

Submitted by sirmanu on Fri, 2016-09-23 09:08

But modifying that, I will still having that warning, isn't it?
By the way, images with spaces, are not displayed.
I think it might be of your interest add this piece of code

str_replace(" ","%20",$image)

Submitted by support on Fri, 2016-09-23 09:18

Hi,

Sorry I missed that part - the warning can be suppressed with the @ prefix, so where you have:

    if (!$res = imagecreatefromstring($img)) return FALSE;

...REPLACE with:

    if (!$res = @imagecreatefromstring($img)) return FALSE;

I will look into the %20 encoding further, Image URLs should be correctly formatted from source, consider that there is no processing of the URLs before rendering directly into a page.

Cheers,
David.
--
PriceTapestry.com

Submitted by Keeop on Mon, 2016-10-03 21:39

Hi David,

Getting grief from a particular merchant for hammering their servers with image requests. From what I can tell, it's bots and spiders crawling my site pinging off the GET requests at a rapid rate. Is there any way alter the image cache script to detect spiders/bots etc. and stop them from firing off these requests?

Cheers.
Keeop

Submitted by support on Tue, 2016-10-04 08:10

Hi Keeop,

This is one of the downsides of caching of course - one may come across merchant's who's servers are configured to detect repeated requests from a single IP and may even block under some conditions.

You could try adding a check for an HTTP_REFERER - bots often don't include the referer - to try this, where you have the following code:

  $src = base64_decode($_GET["src"]);

...REPLACE with:

  if (!isset($_SERVER["HTTP_REFERER"]) || !$_SERVER["HTTP_REFERER"]) exit();
  $src = base64_decode($_GET["src"]);

Also, if not already in place, it might be worth adding a crawl-delay to robots.txt:

User-agent: *
Crawl-delay: 2

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by Keeop on Thu, 2016-10-06 13:39

Thanks David, I'll give those a go. And yes, my IP is currently banned by that merchant because of it!

Cheers.
Keeop

Submitted by Retro135 on Tue, 2016-11-15 06:33

Is there any way to add width/height to the cached image URLs?

Submitted by support on Tue, 2016-11-15 09:21

Hi,

It would be no problem to pass the resize width in as a parameter in the URL, allowing for differently resized images for use in different scenarios (e.g. Featured Products / main product image). Note that this will result in potentially doubling the number of files held in the cache folder so consider this in terms of bandwidth / disk space impact.

To do this, where you have the following code at line 5:

  $imageCacheResize = FALSE;

...REPLACE with:

  $imageCacheResizeMax = 1024; // set to the maximum width you are likely to use
  $imageCacheResize = intval($_GET["w"]);
  if ($imageCacheResize > $imageCacheResizeMax) exit();

And then the following code at line 36:

    $filename = $imageCacheDir.md5($src);

...and REPLACE with:

    $filename = $imageCacheDir.md5($src)."_".$imageCacheResize;

And then to use, where you would now have for, say, Featured Products:

src='<?php print $config_baseHREF."imageCache.php?src=".base64_encode($product["image_url"]); ?>'

...add the w parameter in the src URL for example:

src='<?php print $config_baseHREF."imageCache.php?w=100&src=".base64_encode($product["image_url"]); ?>'

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by Retro135 on Tue, 2016-11-15 16:36

Never mind! " ...this will result in potentially doubling the number of files held in the cache folder so consider this in terms of bandwidth / disk space impact." Filing this under "Be careful what you ask for!" Thank you!

Submitted by Perce2 on Thu, 2016-12-15 10:28

Hi David,

In the middle of moving my sites over to https. So far appear to be having success using your methods in this post - "Proxy only mode only for non-https URLs"

However, I have now come to stand still whilst trying to accomplish this with my Wordpress installs!
Do we still need to use ImagheCache.php ? Where do we put it ? What code changes are needed ?

Thanks for any assistance you may offer.

Submitted by support on Thu, 2016-12-15 10:46

Hi,

Firstly, edit the plugin file pto_search.php and look for the following code at line 518:

      $each = str_replace("%IMAGE_URL%",$row->image_url,$each);

...and REPLACE with:

      $each = str_replace("%IMAGE_URL%",$row->image_url,$each);
      $each = str_replace("%IMAGE_URL64%",base64_encode($row->image_url),$each);

And then edit pto_product.php and look for the following code at line 392:

      $html_product = str_replace("%IMAGE_URL%",$product->image_url,$html_product);

...and REPLACE with:

      $html_product = str_replace("%IMAGE_URL%",$product->image_url,$html_product);
      $html_product = str_replace("%IMAGE_URL64%",base64_encode($product->image_url),$html_product);

With that in place, you can then edit your Search Results / Each and Product / Main templates, and where you would currently use the %IMAGE_URL% placeholder in the src attribute of the img tag e.g.

src='%IMAGE_URL%'

...instead, create an absolute link to your imageCache.php using the new %IMAGE_URL64% placeholder added by the above modifications e.g.

src='/pt/imageCache.php?src=%IMAGE_URL64%'

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by Perce2 on Thu, 2016-12-15 13:58

Hi David,

thanks for the quick explanation.

I managed to keep up with you until "With that in place..."

Don't I need to edit the main templates: searchresults.php / featured.php / product.php as I did with the non-wordpress pt version ?

If so, not sure which part to edit, as I have in place now:

{code saved}

Where do I add:

src='/pt/imageCache.php?src=%IMAGE_URL64%'

Sorry for any confusion!

Thanks.

Submitted by support on Thu, 2016-12-15 15:13

Hi,

When using the plugin, the Price Tapestry installation's /html/ folder files aren't used at all - the content generated within your WordPress site is based on the templates which you can edit from /wp-admin/ > Settings > PriceTapestry.org. On that page, scroll down to the Templates section where you will find Search Results / Each and Product / Main templates which is where the changes need to be made...

Cheers,
David.
--
PriceTapestry.com

Submitted by Perce2 on Thu, 2016-12-15 16:20

Made the changes as instructed, now have no images on "product" and "search-results" pages!
Also, as I have a customised "pto_featured.php" I think this is effecting any changes on the main index page as the results still look the same.

Thanks David.

Submitted by support on Thu, 2016-12-15 17:31

Hi,

Ah - I forgot the same change required in pto_featured.php - line 81:

          $each = str_replace("%IMAGE_URL%",$row->image_url,$each);

...REPLACE with:

          $each = str_replace("%IMAGE_URL%",$row->image_url,$each);
          $each = str_replace("%IMAGE_URL64%",base64_encode($row->image_url),$each);

And similarly, in /wp-admin/ > Settings > PriceTapestry.org, for the Featured Products / Each template you would need to change

src='%IMAGE_URL%'

...to:

src='/pt/imageCache.php?src=%IMAGE_URL64%'

Note that in the above template modification, and the previously described changes to Search Results / Each and Product / Main, the /pt/ part is the path to the associated Price Tapestry Installation, so if not installed in /pt/ this would need to be changed, e.g. if installed in /comparison/ then the replacements would be;

src='/comparison/imageCache.php?src=%IMAGE_URL64%'

(the part in front of imageCache.php should be the same as $config_baseHREF setting in config.php of the associated Price Tapestry installation...)

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by Perce2 on Thu, 2016-12-15 18:12

Implemented all the changes as suggested but still getting all images missing!

Typical missing image link showing like:
{code saved}

What do you think ?

Submitted by support on Thu, 2016-12-15 18:19

Hi,

It looks like it's missing both the enclosing ' and the path to imageCache.php - could you perhaps copy / paste into a reply your content for the following templates:

Featured Products / Each

Search Results / Each

Product / Main

Thanks!
David.
--
PriceTapestry.com

Submitted by Perce2 on Thu, 2016-12-15 18:33

FEATURED

%IF_IMAGE%
  <p><a href='%PRODUCT_URL%'><img src='/pt/imageCache.php?src=%IMAGE_URL64%' /></a></p>
%ENDIF_IMAGE%

SEARCH

%IF_IMAGE%
  <a href='%PRODUCT_URL%'><img class='pto_search_image' src='/pt/imageCache.php?src=%IMAGE_URL64%' /></a>
%ENDIF_IMAGE%

PRODUCT

%IF_IMAGE%
<div class='pto_col-s-10 pto_col-m-5 pto_pr-img'>
<img src='/pt/imageCache.php?src=%IMAGE_URL64%' />
</div>
%ENDIF_IMAGE%

Submitted by support on Fri, 2016-12-16 09:30

Hi,

That looks perfect, but for some reason it's not correlating with the output being generated that you posted previously....

Please could you check a product page again, and copy the HTML section that corresponds with the above IMAGE section of the Product / Main template - if you search in the View > Source for "pto_pr-img", then copy / paste the div / img tags....

Altermatively, if you'd like to email me a link to your installation, (example product page URL) and attach modified pto_product.php I'll follow up by email with you...

Thanks,
David.
--
PriceTapestry.com

Submitted by sirmanu on Tue, 2017-07-18 07:30

Hi David. As I noticed earlier, images with spaces was not displayed.

Example:

"https://www.example.com/images/products/BROOKS ADURO 4 BLACK RED.jpg" (working)

However, when using imagecache is not displayed.

I added these two lines an now is working:

  $src = base64_decode($_GET["src"]);
  $src = trim($src);
  $src = str_replace ( ' ', '%20', $src);

Regards and hope is useful for someone with my same problem

Submitted by nVIsion on Mon, 2017-07-31 15:04

This image cache code works great but I am wondering if it is possible to maintain the aspect ration of the image. Many of the images I am working with are different sizes and right now when I set the resize to 300 it creates a white background on the top/bottom or the sides of the images. Is there any way to restrict the width to 300 yet still keep the aspect ratio of the photo and having no new background? Thanks!

Submitted by support on Tue, 2017-08-01 16:40

Hello nVision and welcome to the forum!

The resized images should maintain the original image's aspect ratio however that will result in the white border above / below or left / right (depending on original image aspect ratio) as you are seeing however you could experiment with a transparent background instead. To try this, edit imageCache.php and where you should have the following code beginning at line 59:

      $newBackground = imagecolorallocate($new,255,255,255);

...REPLACE with:

      $newBackground = imagecolorallocatealpha($new,0,0,0,127);
      imagefill($new,1,1,$newBackground);
      imagesavealpha($new,TRUE);

Don't forget to empty the cache/ folder after uploading so that the cached files are created with the modifications in place...

Hope this helps!

Cheers,
David.
--
PriceTapestry.com

Submitted by marco on Mon, 2018-02-12 13:11

Hello,

I am, layout wise, also looking for a different image than the square one.
Would it be possible to crop the image to a fixed aspect ratio of 3:2?

Best,
Marco

Submitted by support on Mon, 2018-02-12 15:00

Hello Marco,

Make sure you're using resize and a value for $imageCacheResize that is exactly divisible by 3 for example imageCache.php at line 5:

  $imageCacheResize = 240;

And then look for the following code at line 77:

      imagecopyresized($new,$res,$dstX,$dstY,0,0,$newX,$newY,$oldX,$oldY);

...and REPLACE with:

      imagecopyresized($new,$res,$dstX,$dstY,0,0,$newX,$newY,$oldX,$oldY);
      $cropHeight = intval(($imageCacheResize / 3) * 2);
      $cropY = intval(($imageCacheResize - $cropHeight) / 2);
      $new = imagecrop($new,array("x"=>0,"y"=>$cropY,"width"=>$imageCacheResize,"height"=>$cropHeight));

Hope this helps!

Cheers,
David.
--
PriceTapestry.com