John Davidson

php - Is it possible to cache the images returned from the imagewebp function?

0 comments
Message:


There is a php file that resizes the image and converts it to webp using the imagewebp function.


// resize.php
<?php
$filename = "../" . $_REQUEST["file"];
$w = 700;
$h = 400;
$baseImage = imagecreatefromjpeg($filename);
$image = imagecreatetruecolor($w, $h);
imagecopyresampled($image, $baseImage, 0, 0, 0, 0, $w, $h, $w, $h);
imagewebp($image);

This resize.php can be used as follows to display resized webp images.


<img src="/resize.php?file=/example.jpg">

However, currently the images returned from this resize.php do not have cache-control set.

So, I would like to have the image returned from resize.php cached.




The response header is as follows.



The image returned by resize.php has no cache-control set.


However, the normal webp file was able to set cache-control.


If the image does not exist as a file, can it be cached?



My Answer:
Yes, it is possible to cache the images returned from the imagewebp function. One way to do this is by saving the webp images to a specific directory on the server and then serving them from that directory when requested. This way, the images will be cached on the server and can be served quickly without having to resize and convert them again.

Here is an example of how you can save the webp images to a directory on the server:

php
// resize.php

// Path to the original image
$original_image = 'path/to/original/image.jpg';

// Load the original image
$source = imagecreatefromjpeg($original_image);

// Resize the image
$width = 200; // New width
$height = 200; // New height
$destination = imagecreatetruecolor($width, $height);
imagecopyresampled($destination, $source, 0, 0, 0, 0, $width, $height, imagesx($source), imagesy($source));

// Convert the image to webp format
$webp_image = 'path/to/cache/image.webp';
imagewebp($destination, $webp_image);

// Output the webp image
header('Content-Type: image/webp');
readfile($webp_image);


In this example, the resized and converted webp image is saved to the `path/to/cache` directory on the server. When the image is requested, it is served directly from this directory, saving time and resources by not having to resize and convert the image again.

Rate this post

5 of 5 based on 7418 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us