PHP   发布时间:2022-04-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了php – 按比例在图像上书写文字大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我有图像:

我想在图像下添加文字(制作消极图像).所以我将它扩展到高度并在底部增加额外的高度.我需要的是写下文字:

我也需要这些词语以图像为中心.所以输出应该是:

一切都在php GD库上.问题是 – 我不知道如何计算字体大小的比例并使其居中.
我的功能不起作用,计算错误的字体大小和对齐文本错误..

private function __generate_text_pref($typE)
{
    $data = array();
    switch ($typE) {
        case 'title':
            $data['percent'] = 0.9;
            $data['text_width_percent'] = 0.8;
            break;
        case 'subtitle':
            $data['percent'] = 0.92;
            $data['text_width_percent'] = 0.6;
            break;
        default:
            $data['percent'] = 0.86;
            $data['text_width_percent'] = 0.8;
            break;
    }

    list($img_width,$img_height) = getimagesize($this->setTings['__temp_image']);

    // find font-size for $txt_width = 80% of $img_width...
    $data['font_size'] = 1;
    $txt_max_width = intval($data['text_width_percent'] * $img_width);

    do {

        $data['font_size'] ++;
        $p = imagettfbbox($data['font_size'],$this->setTings['font'],$this->setTings['__title']);
        $txt_width = $p[2] - $p[0];
        // $txt_height=$p[1]-$p[7]; // just in case you need it

    } while ( $txt_width <= $txt_max_width );

    //$data['font_size'] = ($data['font_size'] > 24) ? 24 : $data['font_size'];

    return array(
        'font_size' => $data['font_size'],'asys'      => array(
            'x' => (($img_width - $txt_width) / 2),'y' => ($img_height * $data['percent'])
        )
    );
}

它应该具有标题和副标题的默认字体大小,并且只有在文本较长且不适合包装的情况下才将其降低.

解决方法

由于似乎很难确定文本是否比其边界框更宽而不能实际“看到”它,这是我提出的解决方案.

我使用了1000px宽的图像并将其调整为600.当然,你显然已经完成了所有这些工作.

我写的答案并不是那么好(然代码已经过测试并且确实有效)所以我希望这会有所帮助.

<?php
$FormAction = $_SERVER['php_SELF'];

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {  // if form is submitted

// get original image
$filename = $_FILES["Imagename"]["name"]; // The file name
$fileTemploc = $_FILES["Imagename"]["tmp_name"]; // File in the php tmp folder
$type = strtolower(substr(strrchr($filename,"."),1));
if($type == 'jpeg') { $type = 'jpg'; }

// Temporary upload image name
$original_image = $_FILES['Imagename']['tmp_name'];

// Name to save the image as - in this case the same as the original
$new_image = $_FILES['Imagename']['name'];

// Get the image dimensions
$uploaded_size = getimagesize($original_imagE);
$uploaded_imgw = $uploaded_size[0];
$uploaded_imgh = $uploaded_size[1];

// Maximum image width and height
$max_width = "600";
$max_height = "600";

// Thumbnail image width and height
$thumbnail_max_width = "100";
$thumbnail_max_height = "100";

// check to see if we need to resize the image
if ($uploaded_imgw > 600 || $uploaded_imgh > 600) { // if image is larger than 600x600
// Resize image using GD2 cmd
// Get new dimensions
list($width_orig,$height_orig) = getimagesize($original_imagE);
$ratio_orig = $width_orig/$height_orig;
// resize our image proportionately maintaining its original aspect
if ($thumbnail_max_width/$thumbnail_max_height > $ratio_orig) {
   $width = $max_width*$ratio_orig; //576
   $height = $max_height;
} else {
   $height = $max_height/$ratio_orig; // 576
   $width = $max_width; //600
}
// Resample / Resize the image
$orig_image_p = imagecreatetruecolor($width,$height);

if($type == "gif" || $type == "png"){
    imagecolortransparent($orig_image_p,imagecolorallocate($orig_image_p,0));
}
if($type == "jpg") {
    $temp_image = imagecreatefromjpeg($original_imagE);
}
if($type == "gif") {
    $temp_image = imagecreatefromgif($original_imagE);
}
if($type == "png") {
    $temp_image = imagecreatefrompng($original_imagE);
}

imagecopyresampled($orig_image_p,$temp_image,$width,$height,$width_orig,$height_orig);

if($type == "jpg") {
    imagejpeg($orig_image_p,$original_image,80);
}
if($type == "gif") {
    imagegif($orig_image_p,$original_imagE);
}
if($type == "png") {
    imagepng($orig_image_p,9);
}
move_uploaded_file($original_image,'../../Images/'.$new_imagE);
imagedestroy($temp_imagE);
imagedestroy($orig_image_p);
} else { // if image is smaller than 900x900
$small_image_p = imagecreatetruecolor($uploaded_imgw,$uploaded_imgh);

if($type == "gif" || $type == "png"){
    imagecolortransparent($small_image_p,imagecolorallocate($small_image_p,0));
}

if($type == "jpg") {
    $small_temp_image = imagecreatefromjpeg($original_imagE);
}
if($type == "gif") {
    $small_temp_image = imagecreatefromgif($original_imagE);
}
if($type == "png") {
    $small_temp_image = imagecreatefrompng($original_imagE);
}

imagecopyresampled($small_image_p,$small_temp_image,$uploaded_imgw,$uploaded_imgh,$uploaded_imgh);

if($type == "jpg") {
    imagejpeg($small_image_p,80);
}
if($type == "gif") {
    imagegif($small_image_p,$original_imagE);
}
if($type == "png") {
    imagepng($small_image_p,'../../Images/'.$new_imagE);
imagedestroy($small_temp_imagE);
imagedestroy($small_image_p);
} // end if smaller than 600x600

// Get the image we will work with
$new_img_src = '../../Images/'.$new_image;
list($new_width,$new_height) = getimagesize($new_img_src);

if($type == 'jpg') {
    $im = imagecreatefromjpeg($new_img_src);
}
if($type == 'png') {
    $im = imagecreatefrompng($new_img_src);
}
if($type == 'gif') {
    $im = imagecreatefromgif($new_img_src);
}

// Create a blank canvas for our new image
$new_image_p = imagecreatetruecolor($new_width,$new_height);

if($type == "gif" || $type == "png"){
    imagecolortransparent($new_image_p,imagecolorallocate($new_image_p,0));
}
if($type == 'jpg') {
    $new_temp_image = imagecreatefromjpeg($new_img_src);
}
if($type == 'png') {
    $new_temp_image = imagecreatefrompng($new_img_src);
}
if($type == 'gif') {
    $new_temp_image = imagecreatefromgif($new_img_src);
}

imagecopyresampled($new_image_p,$new_temp_image,$new_width,$new_height,$new_height);

// set dimensions for our canvas
$adj_width = $new_width+40;
$adj_height = $new_height+120;

$bkgrd = imagecreatetruecolor($adj_width,$adj_height);
imagefilledrectangle($bkgrd,$adj_width,$adj_height,0x000000);
$sx = imagesx($bkgrd)-imagesx($bkgrd)+20;
$sy = imagesy($bkgrd)-imagesy($bkgrd)+20;

// Place our original image on the canvas centered and 20px from the top
imagecopymerge($bkgrd,$new_image_p,$sx,$sy,imagesx($bkgrd),imagesy($bkgrd),100);

// Save the image to file and free memory
if($type == "jpg") {
    imagejpeg($bkgrd,$new_img_src,80);
}
if($type == "gif") {
    imagegif($bkgrd,$new_img_src);
}
if($type == "png") {
    imagepng($bkgrd,9);
}
imagedestroy($im);
imagedestroy($new_image_p);
imagedestroy($bkgrd);

//Now we create our text as images to be merged with our new image

// check width of bounding box
function calculateTextBox($text,$fontFile,$fontSize,$fontAnglE) {
/************
simple function that calculates the *exact* bounding box (single pixel precision).
The function returns an associative array with these keys:
left,top:  coordinates you will pass to imagettftext
width,height: dimension of the image you have to create
*************/
    $rect = imagettfbbox($fontSize,$fontAngle,$text);
    $minX = min(array($rect[0],$rect[2],$rect[4],$rect[6]));
    $maxX = max(array($rect[0],$rect[6]));
    $minY = min(array($rect[1],$rect[3],$rect[5],$rect[7]));
    $maxY = max(array($rect[1],$rect[7]));

    return array(
     "left"   => abs($minX) - 1,"top"    => abs($minY) - 1,"width"  => $maxX - $minX,"height" => $maxY - $minY,"box"    => $rect
    );
}

$text_String = $_POST['TopLine']; //"This is a very long first line to see what happens if it is too long";
$font_ttf = "arial.ttf";
$font_size = 22;
$text_angle = 0;
$text_padding = 10; // Img padding - around text

$the_box = calculateTextBox($text_String,$font_ttf,$font_size,$text_anglE);

$imgWidth = $the_box["width"] + $text_padding;
$imgHeight = $the_box["height"] + $text_padding;

$image = imagecreatetruecolor($imgWidth,$imgHeight);
imagefill($image,imagecolorallocate($image,0));

$color = imagecolorallocate($image,255,255);

imagettftext($image,$text_angle,$the_box["left"] + ($imgWidth / 2) - ($the_box["width"] / 2),$the_box["top"] + ($imgHeight / 2) - ($the_box["height"] / 2),$color,$text_String);

// save file
imagepng($image,'../../Images/NewTopImg.png',9);

// destroy the image and start over
imagedestroy($imagE);

$text_String = $_POST['BottomLine']; //"This is a very long second line to see what happens if it is too long. Even a longer line than the first one.";
$font_ttf = "arial.ttf";
$font_size = 16;
$text_angle = 0;
$text_padding = 10; // Img padding - around text

$the_box = calculateTextBox($text_String,'../../Images/NewBottomImg.png',9);

imagedestroy($imagE);

// Now merge the three images together
//function merge($filename_x,$filename_y,$filename_result) {

// Get dimensions for specified images
$filename_vs = '../../Images/'.$new_image;
$filename_x = '../../Images/NewTopImg.png';
$filename_y = '../../Images/NewBottomImg.png';
list($width_x,$height_X) = getimagesize($filename_X);
list($width_y,$height_y) = getimagesize($filename_y);
list($width_vs,$height_vs) = getimagesize($filename_vs);

// before we go any farther lets find out if our text is wider than our image
if($width_x > $new_width) { // if it is too wide lets resize it
    // create smaller image using GD2 cmd to the smallest side
    $line1_img_src = '../../Images/NewTopImg.png';
    $line1_img_path = '../../Images/NewTopImg.png';
    list($src_width,$src_height) = getimagesize($line1_img_src);

    $min = $new_width; // set our max width to that of the original image
    $ratio = $src_height/$src_width;
    $line1_width = $min;
    $Line1_height = round($min * $ratio);

    $blank_image_line1 = imagecreatetruecolor($line1_width,$Line1_height);

    imagecolortransparent($blank_image_line1,imagecolorallocate($blank_image_line1,0));

    $image = imagecreatefrompng($line1_img_src);

    imagecopyresampled($blank_image_line1,$image,$line1_width,$Line1_height,$src_width,$src_height);

    imagepng($blank_image_line1,$line1_img_path,9);

    imagedestroy($blank_image_line1);
    imagedestroy($imagE);

    // Because we resized the first line we need to get the new dimensions
    $filename_x = '../../Images/NewTopImg.png';
    list($width_x,$height_X) = getimagesize($filename_X);
    // End resize first line
}

// Now lets check line two
if($width_y > $new_width) { // if it is too wide lets resize it
    // create smaller image using GD2 cmd to the smallest side
    $line2_img_src = '../../Images/NewBottomImg.png';
    $line2_img_path = '../../Images/NewBottomImg.png';
    list($src_width,$src_height) = getimagesize($line2_img_src);

    $min = $new_width; // set our max width to that of the original image
    $ratio = $src_height/$src_width;
    $line2_width = $min;
    $line2_height = round($min * $ratio);

    $blank_image_line2 = imagecreatetruecolor($line2_width,$line2_height);

    imagecolortransparent($blank_image_line2,imagecolorallocate($blank_image_line2,0));

    $image = imagecreatefrompng($line2_img_src);

    imagecopyresampled($blank_image_line2,$line2_width,$line2_height,$src_height);

    imagepng($blank_image_line2,$line2_img_path,9);

    imagedestroy($blank_image_line2);
    imagedestroy($imagE);

    // Because we resized the second line we need to get the new dimensions
    $filename_y = '../../Images/NewBottomImg.png';
    list($width_y,$height_y) = getimagesize($filename_y);
    // End resize second line
}

// Create new image with desired dimensions
$image = imagecreatetruecolor($width_vs,$height_vs);

// Load images and then copy to desTination image
if($type == "gif" || $type == "png"){
    imagecolortransparent($image,0));
}
if($type == 'jpg') {
    $image_vs = imagecreatefromjpeg($filename_vs);
}
if($type == 'png') {
    $image_vs = imagecreatefrompng($filename_vs);
}
if($type == 'gif') {
    $image_vs = imagecreatefromgif($filename_vs);
}
$image_x = imagecreatefrompng($filename_X);
$image_y = imagecreatefrompng($filename_y);

//set LOCATIOn for merged images
$vs_x = imagesx($imagE); // width of our completed image
$vs_y = imagesy($imagE);// height of our completed image
$x_x = $width_x; // width of the top line
$x_x = ($vs_x/2)-($x_x/2);
$x_y = $new_height+30; // height of the original img + 20px we dropped it from the top of the canvas + 10px more for spacing below our "picture" placed on the canvas
$y_x = $width_y; // width of the bottom line
$y_x = ($vs_x/2)-($y_x/2);
$y_y = $new_height+70; // height of the original img + 20px we dropped it from the top of the canvas + 40px more for spacing below the first line of text

imagecopy($image,$image_vs,$width_vs,$height_vs);
imagecopy($image,$image_x,$x_x,$x_y,$image_y,$y_x,$y_y,$height_vs);


// set dimensions for our canvas
$adj_width = $new_width+40;
$adj_height = $new_height+120;

$bkgrd = imagecreatetruecolor($adj_width,100);

// Save the image to file and free memory
if($type == "jpg") {
    imagejpeg($image,$filename_vs,80);
}
if($type == "gif") {
    imagegif($image,$filename_vs);
}
if($type == "png") {
    imagepng($image,9);
}

// Clean up
imagedestroy($imagE);
imagedestroy($image_X);
imagedestroy($image_y);
imagedestroy($image_vs);

//merge($filename_x,$filename_vs);

} // end if form submitted
?>
<table width="800" border="0" cellspacing="0" celLPADding="5" align="center">
  <tr>
<td><div id="FormContainer">
  <table width="100%" border="0" celLPADding="0" cellspacing="0">
    <tr>
      <td><div id="Heading">IMAGE UPLOAD</div></td>
      </tr>
    </table>
<form enctype="multipart/form-data" id="form1" name="form1" method="post" action="<?php echo $FormAction; ?>">
    <table border="0" align="center" celLPADding="5" cellspacing="0">
      <tr>
        <td colspan="2">Only JPG,JPEG,PNG and GIF files are allowed.</td>
        </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        </tr>
      <tr>
        <td><div align="right" class="Strong">File:</div></td>
        <td><input name="Imagename" type="file" id="Imagename" size="50" /></td>
        </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        </tr>
      <tr>
        <td nowrap="nowrap" class="Elementtitle"><div align="right">Line 1 Text:</div></td>
        <td><input name="TopLine" type="text" id="TopLine" value="This is a very long first line to see what happens if it is too long" size="75" maxlength="100" /></td>
        </tr>
      <tr>
        <td nowrap="nowrap" class="Elementtitle"><div align="right">Line 2 Text:</div></td>
        <td><input name="BottomLine" type="text" id="BottomLine" value="This is a very long second line to see what happens if it is too long. Even a longer line than the first one." size="75" maxlength="100" /></td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        </tr>
      <tr>
        <td colspan="2"><table width="150" border="0" align="center" celLPADding="5" cellspacing="0">
          <tr>
            <td><div align="center" style="width:80px; height:37px;">
              <input name="Submit" type="submit" class="Submit" value="Upload" />
            </div></td>
            <td><div align="center" style="width:75px; height:37px;">
              <input name="Submit22" type="reset" class="Submit" value="Reset" />
            </div></td>
          </tr>
        </table></td>
        </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        </tr>
      </table><input type="hidden" name="MM_insert" id="MM_insert" value="form1">
  </form>
</div><!-- end form container -->
</td>
</tr>
  <tr>
    <td>&nbsp;</td>
  </tr>
</table>

基本上你在做什么

>为第一行和第二行创建两个图像
>检查这些图像是否比现有图像宽
如果是这样
>调整它们的大小以适合原始图像宽度
>最后将所有三个图像合并为一个.

您的默认文本大小可以在这里更改… $font_size = 22和$font_size = 16分别为第一行和第二行.

不要忘记上传您的ttf字体文件并正确指向它.

最后,您可以在最后添加代码,以便在完成后删除两个临时文件.

对于我在这里修改和使用的calculateTextBox函数,jodebrabec的部分功劳. You can find it here

短文本的示例输出

使用长文本的示例输出

大佬总结

以上是大佬教程为你收集整理的php – 按比例在图像上书写文字全部内容,希望文章能够帮你解决php – 按比例在图像上书写文字所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。