Center watermark text on image when unknown size of text

故事扮演 提交于 2019-12-12 01:57:37

问题


I'm trying to create an image with a watermark text in it and I want it to be central on the image. The text I want to watermark can be anywhere from 5 characters to 15 characters, therefore I cannot put a final size for the text to fit every image.

This is the code I use to create the watermarked image

function watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile) { 
 list($width, $height) = getimagesize($SourceFile);
 $image_p = imagecreatetruecolor($width, $height);
 $image = imagecreatefromjpeg($SourceFile);
 imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height); 
 $black = imagecolorallocate($image_p, 0, 0, 0);
 $font = '../fonts/proxima-nova-light.otf';
 $font_size = 100; 
 imagettftext($image_p, $font_size, 0, 303, 190, $black, $font, $WaterMarkText);
 if ($DestinationFile<>'') {
   imagejpeg ($image_p, $DestinationFile, 100); 
 } else {
   header('Content-Type: image/jpeg');
   imagejpeg($image_p, null, 100);
 };
 imagedestroy($image); 
 imagedestroy($image_p); 
};

Which does an excellent job on some texts but when I try it on longer texts it looks bad.

I want to - somehow - calculate the optimal size of text and choose size, x and y from there.

Any ideas?


回答1:


After doing some research with help from @Sammitch I was able to figure it out. Here is the working code:

<?php
function watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile) { 
$font = 'fonts/your-font-here.ttf';
$font_size = 40; 

list($width, $height) = getimagesize($SourceFile);
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($SourceFile);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height); 
$black = imagecolorallocate($image_p, 0, 0, 0);
$bbox = imagettfbbox($font_size, 0, $font, $WaterMarkText);

$x = $bbox[0] + (imagesx($image) / 2) - ($bbox[4] / 2) + 10;
$y = $bbox[1] + (imagesy($image) / 2) - ($bbox[5] / 2) - 5;

imagettftext($image_p, $font_size, 0, $x, $y, $black, $font, $WaterMarkText);
if ($DestinationFile<>'') {
  imagejpeg ($image_p, $DestinationFile, 100); 
} else {
  header('Content-Type: image/jpeg');
  imagejpeg($image_p, null, 100);
};
imagedestroy($image); 
imagedestroy($image_p); 
};
?>



回答2:


Calculate the position of the watermark in the output image (the watermark shall be placed in the Center of the Image)

$watermark_pos_x = (imagesx($image)/2) - (imagesx($watermark)/2) - 15;

$watermark_pos_y = (imagesy($image)/2) - (imagesy($watermark)/2) - 10;

Use this value on function.



来源:https://stackoverflow.com/questions/22674918/center-watermark-text-on-image-when-unknown-size-of-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!