PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, September 19, 2022

[FIXED] How to cache images generated by imagick?

 September 19, 2022     browser-cache, caching, imagemagick, imagick, php     No comments   

Issue

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' />";
 }

Solution

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"));


Answered By - MaKR
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing