简体   繁体   中英

How to cache images generated by imagick?

I am using the function below to generate an image with text on it. I am wondering how can I make it so that the image is only generated once for the user and then the image is cached in their browser. My goal is to save server resources.

Also does my imagick code look okay? I am worried i might get some kind of memory leak. Thanks for any help

function small_image($username){

$file_content = file_get_contents("https://example.com/wp-content/uploads/2019/04/image.jpg");

$imagick = new Imagick();
$imagick -> readImageBlob($file_content);

$draw = new ImagickDraw();
$pixel = new ImagickPixel( 'gray' );
$draw->setFillColor('white');

/* Font properties */
$draw->setFont('Utopia');
$draw->setFontSize( 50 );

$geo=$imagick->getImageGeometry(); 

$imagick->annotateImage($draw, 60, 185, 0, $username);

$imgBuff = $imagick->getImageBlob();
$imagick->clear(); 

$img = base64_encode($imgBuff);
$imagick -> destroy();
return "<img id='imagick-banner' width=500 alt='Embedded Image' src='data:image/png;base64,$img' />";
 }

You had mentioned saving server resources, so try making the client browser do the work. A caveat of this method is that the user would have to have the correct font, or you'd have to provide the font on the website.

HTML

<canvas id="userImage"></canvas>

JavaScript

window.onload = function() {
    var canvas = document.getElementById("userImage");
    var context = canvas.getContext("2d");
    var imageObject = new Image();
    imageObject.onload = function(){
        context.drawImage(imageObj, 10, 10);
        context.font = "50pt Utopia";
        context.fillText(username, 60, 185);
    };
    imageObject.src = userImageURI;
    document.getElementById('userImage').appendChild(imageObject);
};

As a stricter answer using imagick try localStorage in JavaScript (have your php process it the first time and use JavaScript to decide when to ask for a new image).

localStorage.setItem("userImage", base64data);
var userImage = document.body.appendChild("img");
userImage.setAttribute('src', "data:image/png;base64, " + localStorage.getItem("userImage"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM