Wednesday, April 20, 2016

Laravel Add Date Text in PNG and JPEG Image

In our recent project we have a requirement to add date as text in all the uploaded image. For example, check below image.


In this blog I am going to explain how you can do this.

First of open image from the path.

$publicPath = public_path();
$imagePath = $publicPath."/image/myImage.png"; //replace it with your own path

Create a date text.

$text = date('d-m-Y');

Setup font

$font = $publicPath."/fonts/RobotoCondensed-Bold.ttf"; //replace it with your own path

Now while working on this I faced two issues

1) PHP GD functions like imagecreatefrompng was not woking.
2) PNG image was having JPEG mime type.

To resolve first issue, first check your phpinfo(). It should have PNG support enabled.


If it's not enabled, enable it.

To solve second issue check mime type of image with file info function and use respective function to get image resources.

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $imagePath);

$image = null;
     
if($mime == "image/png"){

            $image = imagecreatefrompng($imagePath);
        
}else{

            $image = imagecreatefromjpeg($imagePath);       
}

Now we have image resource, we have to add text in image and save image.

$black = imagecolorallocate($image, 0, 0, 0);
imagettftext($image, 20, -45, 600, 20, $black, $font, $text);
imagepng($image,$imagePath);
imagedestroy($image);

That's it. Please note in my case all the images were of fixed width and height so I gave fix X = 600 and y = 20 coordinate for text. If you have variable width and height calculate it dynamically.

Hope this helps you.

No comments:

Post a Comment