对齐中心,左,右和从imagettftext函数转换为文本的字体

时间:2014-05-09 07:06:23

标签: php image text-align imagettftext

我使用imagettftext()函数从文本转换图像。现在我正在尝试将转换后的图像文本对齐到中心,左,右,但我没有任何方法可以理清。如果有任何身体知道如何要做到这一点让我知道.Bellow是我用来转换php中文本图像的代码。

演示链接: - Click Here

 <?php
  header("Content-type: image/png");
$myArray = explode(',', $_GET['img']);  
$fontarray = explode(',' , $_GET['fontsize']);   

####################### BEGIN USER EDITS #######################
$imagewidth = 1000;
$imageheight = 1000;
$fontangle = "0";
$font = "ByzantineEmpire.ttf";
$backgroundcolor = "FFFFFF";
$textcolor = "#000000";
######################## END USER EDITS ########################

### Convert HTML backgound color to RGB
if( @eregi( "([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $backgroundcolor, $bgrgb ) )
{$bgred = hexdec( $bgrgb[1] );   $bggreen = hexdec( $bgrgb[2] );   $bgblue = hexdec( $bgrgb[3] );}

### Convert HTML text color to RGB
if( @eregi( "([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $textcolor, $textrgb ) )
{$textred = hexdec( $textrgb[1] );   $textgreen = hexdec( $textrgb[2] );   $textblue = hexdec( $textrgb[3] );}

### Create image
$im = imagecreate( $imagewidth, $imageheight );

### Declare image's background color
$bgcolor = imagecolorallocate($im, $bgred,$bggreen,$bgblue);

### Declare image's text color
$fontcolor = imagecolorallocate($im, $textred,$textgreen,$textblue);

### Get exact dimensions of text string


### Declare completed image with colors, font, text, and text location      
$count=count($myArray);
    $box = imageTTFBbox(50,$fontangle,$font,'test');  

### Get width of text from dimensions
$textwidth = abs($box[4] - $box[0]);

### Get height of text from dimensions
$textheight = abs($box[5] - $box[1]);

### Get x-coordinate of centered text horizontally using length of the image and length of the text
$xcord = ($imagewidth/2)-($textwidth/2)-2;

### Get y-coordinate of centered text vertically using height of the image and height of the text
$ycord = ($imageheight/2)+($textheight/2);
for($i=0;$i<$count;$i++)
{
        $newcount=count($fontarray); 

        for($j=0;$j<$newcount;$j++)

{

    if($j==$i)
    {
     $xcord=$xcord+2;
   $ycord=$ycord+100;
    imagettftext ( $im, $fontarray[$j], $fontangle, $xcord, $ycord, $fontcolor, $font, $myArray[$i] );

}

 } 

}

$html=imagepng($im);

### Close the image
imagedestroy($im);   

?>

2 个答案:

答案 0 :(得分:0)

答案似乎非常简单,实际上它也在您提供的代码中。 注意这两行:

### Get x-coordinate of centered text horizontally using length of the image and length of the text
$xcord = ($imagewidth/2)-($textwidth/2)-2;

### Get y-coordinate of centered text vertically using height of the image and height of the text
$ycord = ($imageheight/2)+($textheight/2);

来自php manual - imagettftext()

  

x和y给出的坐标将定义第一个字符的基点(大致是字符的左下角)

示例中的代码将文本对齐在中心。 左对齐:

$xcord = 0;

对齐八:

$xcord = ($imagewidth)-($textwidth);

答案 1 :(得分:0)

我已经使解决方案对齐,左侧,居中,将文字分隔为使用imagettftext()函数转换的文本

答案有一些立场问题,但我们很快就会解决它

演示链接: - Click Here

所有对齐的示例输出

align output

****完整解决方案****

1)index.php

<!DOCTYPE HTML>
<html>
<head> <?php ?>
<meta charset="utf-8">
<title>Image1</title>
<link href="style.css" rel="stylesheet" type="text/css">

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){





         $('input[name="stencil-text"]').keyup(function(){

             var align123='';
            if( $('input[class=radio1]:radio:checked').length > 0 ) {

        align123= $('input[class=radio1]:radio:checked').val();


    }


       if( $('input[class=radio2]:radio:checked').length > 0 ) {

        align123= $('input[class=radio2]:radio:checked').val();
    }

       if( $('input[class=radio3]:radio:checked').length > 0 ) {

       align123= $('input[class=radio3]:radio:checked').val();
    }

    if( $('input[class=radio4]:radio:checked').length > 0 ) {

       align123= $('input[class=radio4]:radio:checked').val();
    }


               var img_text = $('input[name="stencil-text"]').map(function(){

                   return $(this).val();
              }).get();

               var fontsize = $('input[name="stencil-text-size"]').map(function(){
                   return $(this).val();
              }).get();

               var fontsize = $('input[name="stencil-text-size"]').map(function(){
                   return $(this).val();
              }).get();

                // var img = $("<img />").attr('src', 'some.php?img=' + img_text+'&fontsize='+fontsize).load(function() { 
              var img = $("<img />").attr('src', 'some.php?img=' + img_text+'&fontsize='+fontsize+'&align='+align123).load(function() { 

                    if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
                        alert('broken image!');
                    } else {
                        //alert(fontsize);
                        $("#stencil-main").html(img);
                    }
                });     

            });  
              $('input[name="stencil-text-size"]').keyup(function(){


                   var align123='';
            if( $('input[class=radio1]:radio:checked').length > 0 ) {

        align123= $('input[class=radio1]:radio:checked').val();
    }


       if( $('input[class=radio2]:radio:checked').length > 0 ) {

        align123= $('input[class=radio2]:radio:checked').val();
    }

       if( $('input[class=radio3]:radio:checked').length > 0 ) {

       align123= $('input[class=radio3]:radio:checked').val();
    }

    if( $('input[class=radio4]:radio:checked').length > 0 ) {

       align123= $('input[class=radio4]:radio:checked').val();
    }

               var img_text = $('input[name="stencil-text"]').map(function(){

                   return $(this).val();
              }).get();

               var fontsize = $('input[name="stencil-text-size"]').map(function(){
                   return $(this).val();
              }).get();




                 //var img = $("<img />").attr('src', 'some.php?img=' + img_text+'&fontsize='+fontsize).load(function() { 
                var img = $("<img />").attr('src', 'some.php?img=' + img_text+'&fontsize='+fontsize+'&align='+align123).load(function() { 

                    if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
                        alert('broken image!');
                    } else {
                        //alert(fontsize);  
                        $("#stencil-main").html(img);
                    }
                }); 








            });    




            $('input[name=align]').change(function(){
                //alert("change");
   // var align   = $( 'input[name=align]:checked' ).val();
           //  var align1   = $( 'input[name=radio1]:radio]' );
           var align123='';
            if( $('input[class=radio1]:radio:checked').length > 0 ) {

        align123= $('input[class=radio1]:radio:checked').val();

    }


       if( $('input[class=radio2]:radio:checked').length > 0 ) {

        align123= $('input[class=radio2]:radio:checked').val();

    }

       if( $('input[class=radio3]:radio:checked').length > 0 ) {

       align123= $('input[class=radio3]:radio:checked').val();

    }

    if( $('input[class=radio4]:radio:checked').length > 0 ) {

       align123= $('input[class=radio4]:radio:checked').val();

    }


  //    alert(align1.checked);
    var img_text = $('input[name="stencil-text"]').map(function(){

                   return $(this).val();
              }).get();
           //  alert(img_text);

               var fontsize = $('input[name="stencil-text-size"]').map(function(){
                   return $(this).val();
              }).get();

                 //  alert(fontsize);


                 var img = $("<img />").attr('src', 'some.php?img=' + img_text+'&fontsize='+fontsize+'&align='+align123).load(function() { 
                    if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
                        alert('broken image!');
                    } else {
                        //alert(fontsize);  
                        $("#stencil-main").html(img);
                    }
                });





    //alert(value);
});







        });
    </script>
</head>

<body>
<br><br>
<div class="main">
<div class="leftbar" id="stencil-main" style="margin-left: -359px;margin-top: -406px;">
Preview of stencil

<br><br>

Preview of stencil

</div>

<div class="rightbar" style="margin-right: -200px;">
<div class="step1">
<div>
<font size="+1">STEP 1 :</font> Enter your text
</div>
<br>
<div class="line">
Line 1<br>
Line 2<br>
Line 3<br>
Line 4
</div>


<div class="txt">   
<input name="stencil-text" type="text" class="name" value="BOBS DINER">
<br>
<input name="stencil-text" type="text" class="name" placeholder="Enter text for Line 2">
<br>
<input name="stencil-text" type="text" class="name" placeholder="Enter text for Line 3">
<br>
<input name="stencil-text" type="text" class="name" placeholder="Enter text for Line 4">

</div>


<div class="ht">
<div>Line 1 <br>
Height
</div>

<div>
Line 2 <br>
Height
</div>
<div>
Line 3 <br>
Height
</div>
<div>
Line 4<br>
Height
</div>

</div>


<div class="no">

<input name="stencil-text-size" type="text" class="num" value="12'' ">
<br>
<input name="stencil-text-size" type="text" class="num" value="12'' ">
<br>
<input name="stencil-text-size" type="text" class="num" value="12'' ">
<br>
<input name="stencil-text-size" type="text" class="num" value="12'' ">

</div>


</div>





<div class="step2">
<div>
<font size="+1">STEP 2 :</font> Choose Options
</div>
<br>

<div class="one">
<font size="+1">Choose Layout :</font>
</div>

<div class="two">
<input type="radio" value="center"  class="radio1" name="align" checked="checked"> Center justified <img src="center.png"><br>
<input  type="radio" value="left"  class="radio2" name="align">Left  <img src="left.png"> 
 <input name="align" type="radio" class="radio3" value="right" >Right  <img src="right.png"><br>
<input  type="radio" value="each" class="radio4"   name="align" > Each stencil indivisual
</div>

<div style="clear:both; margin-top:20px;"></div>
<br>

<div class="one">
<font size="+1"><font color="#CC0000">*</font> Choose Layout <br> &nbsp; stencil material</font>
</div>

<div class="two">
<input name="price" type="radio" value="15"  > 5/64'' (.080'') 5052 Aluminium<br>
<input name="price" type="radio" value="10">1/8'' (.125'') PRO-Grade LDPE <br>
 <input name="price" type="radio" value="12">1/16'' (.062'') Light Duty LDPE<br>
<input name="price" type="radio" value="13"> 5/32'' (.030'') Economy PVC
</div>



<br>

</div>


<div class="step3">
<div>
<font size="+1">STEP 2 :</font> Check out
</div>
<br>

<div class="one">
<font size="+1">Custom Stencil Cost :<br>
&nbsp;&nbsp;&nbsp;&nbsp; <em><strong>$75</strong></em>
</font>
</div>

<div class="three">
<form class="paypal" action="payments.php" method="post" id="paypal_form" target="_blank">    
    <input type="hidden" name="cmd" value="_xclick" /> 
    <input type="hidden" name="no_note" value="1" />
    <input type="hidden" name="lc" value="UK" />
    <input type="hidden" name="currency_code" value="GBP" />
    <input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynow_LG.gif:NonHostedGuest" />
    <input type="hidden" name="first_name" value="Customer's First Name"  />
    <input type="hidden" name="last_name" value="Customer's Last Name"  />
    <input type="hidden" name="payer_email" value="customer@example.com"  />
    <input type="hidden" name="item_number" value="123456" / >
    <input type=image src="cart.png"/>     

</div>

</div>


</div>
  </div>



</body>
</html>

2)some.php

<?php
  header("Content-type: image/png");
$myArray = explode(',', $_GET['img']);  
$fontarray = explode(',' , $_GET['fontsize']);   
$align =$_GET['align'];

####################### BEGIN USER EDITS #######################
$imagewidth = 1000;
$imageheight = 1000;
$fontangle = "0";
$font = "ByzantineEmpire.ttf";
$backgroundcolor = "FFFFFF";
$textcolor = "#000000";
######################## END USER EDITS ########################

### Convert HTML backgound color to RGB
if( @eregi( "([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $backgroundcolor, $bgrgb ) )
{$bgred = hexdec( $bgrgb[1] );   $bggreen = hexdec( $bgrgb[2] );   $bgblue = hexdec( $bgrgb[3] );}

### Convert HTML text color to RGB
if( @eregi( "([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $textcolor, $textrgb ) )
{$textred = hexdec( $textrgb[1] );   $textgreen = hexdec( $textrgb[2] );   $textblue = hexdec( $textrgb[3] );}

### Create image
$im = imagecreate( $imagewidth, $imageheight );

### Declare image's background color
$bgcolor = imagecolorallocate($im, $bgred,$bggreen,$bgblue);

### Declare image's text color
$fontcolor = imagecolorallocate($im, $textred,$textgreen,$textblue);
  if($align=='center')
         {
### Get exact dimensions of text string

       $ycord=0;

//$ycord = ($imageheight/2)-($textheight/2)*2 ; 
       $testcount=0;
### Declare completed image with colors, font, text, and text location      
$count=count($myArray); 

$testnewcount=0;
for($i=0;$i<$count;$i++)
{
        $newcount=count($fontarray); 

        for($j=0;$j<$newcount;$j++)

{


    if($j==$i)
    {



            //$box = imageTTFBbox(50,$fontangle,$font,'test');  
       $box = imageTTFBbox($fontarray[$j],$fontangle,$font,$myArray[$i]);    

### Get width of text from dimensions
$textwidth = abs($box[4] - $box[0]);      

### Get height of text from dimensions
$textheight = abs($box[5] - $box[1]);

### Get x-coordinate of centered text horizontally using length of the image and length of the text
//$xcord = ($imagewidth/2)-($textwidth/2)-2;




### Get y-coordinate of centered text vertically using height of the image and height of the text
//$ycord = ($imageheight/2)+($textheight/2); 

        // if($align=='center')
        // {
           $xcord = ($imagewidth/2)-($textwidth/2)-2;   

       // $ycord =(( ($imageheight/2)+($textheight/2))  )+$testcount; 
        // $testcount=$testcount+65;  
        if($i==0)
        {
             $testnewcount= $fontarray[$j];      
        }
              //$testcount=$testcount+$fontarray[$j]/2;    
            if($testnewcount<$fontarray[$j])
            {
                  $testcount=$testcount+$fontarray[$j]/2;

                  $ycord =(( ($imageheight/2)+($textheight/2))  )+$testcount;  

            }
            else
            {
                $ycord =(( ($imageheight/2)+($textheight/2))  )+$testcount;  


            }

         $testcount=$testcount+$fontarray[$j]; 

         $testnewcount= $fontarray[$j];     
//$ycord = ($imageheight/2)+($textheight/2);
/*
for($i=0;$i<$count;$i++)
{
        $newcount=count($fontarray); 

        for($j=0;$j<$newcount;$j++)

{

    if($j==$i)
    {     */
   //  $xcord=$xcord+2;
 //  $ycord=$ycord+100;
  // imagettftext ( $im, $fontarray[$j], $fontangle, $xcord, $ycord, $fontcolor, $font, $myArray[$i] );       
    //    imagettftext ( $im, $fontarray[$j], $fontangle, $xcord, $ycord, $fontcolor, $font, $ycord );   

    imagettftext ( $im, $fontarray[$j], $fontangle, $xcord, $ycord, $fontcolor, $font, $myArray[$i] );   
         }

         }

 } 

}
         if($align=='left')
         {


         $count=count($myArray);
    $box = imageTTFBbox(50,$fontangle,$font,'test');  

### Get width of text from dimensions
$textwidth = abs($box[4] - $box[0]);

### Get height of text from dimensions
$textheight = abs($box[5] - $box[1]);

### Get x-coordinate of centered text horizontally using length of the image and length of the text
$xcord = ($imagewidth/2)-($textwidth/2)-2;

### Get y-coordinate of centered text vertically using height of the image and height of the text
//$ycord = ($imageheight/2)+($textheight/2);
for($i=0;$i<$count;$i++)
{
        $newcount=count($fontarray); 

        for($j=0;$j<$newcount;$j++)

{

    if($j==$i)
    {

         if($i==0)
        {
             $testnewcount= $fontarray[$j];      
        }
              //$testcount=$testcount+$fontarray[$j]/2;    
            if($testnewcount<$fontarray[$j])
            {
                  $testcount=$testcount+$fontarray[$j]/2;

                  $ycord =(( ($imageheight/2)+($textheight/2))  )+$testcount;  
            }
            else
            {
                $ycord =(( ($imageheight/2)+($textheight/2))  )+$testcount;    
            }

         $testcount=$testcount+$fontarray[$j]; 

        // $testnewcount= $fontarray[$j];     
    //$xcord=$xcord+2;
    // $ycord=$ycord+2;
   //$ycord=$ycord+20 +$fontarray[$j]; 
   imagettftext ( $im, $fontarray[$j], $fontangle, $xcord, $ycord, $fontcolor, $font, $myArray[$i] );



}

 } 

}       



              // imagettftext ( $im, $fontarray[$j], $fontangle, $xcord, $ycord, $fontcolor, $font, $myArray[$i] );   

         }
      //imagettftext ( $im, $fontarray[$j], $fontangle, $xcord, $ycord, $fontcolor, $font, $myArray[$i] );



//}

// } 

//}

if($align=='right')
         {
### Get exact dimensions of text string

       $ycord=0;

//$ycord = ($imageheight/2)-($textheight/2)*2 ; 
       $testcount=0;
### Declare completed image with colors, font, text, and text location      
$count=count($myArray); 

$testnewcount=0;
for($i=0;$i<$count;$i++)
{
        $newcount=count($fontarray); 

        for($j=0;$j<$newcount;$j++)

{


    if($j==$i)
    {



            //$box = imageTTFBbox(50,$fontangle,$font,'test');  
       $box = imageTTFBbox($fontarray[$j],$fontangle,$font,$myArray[$i]);    

### Get width of text from dimensions
$textwidth = abs($box[4] - $box[0]);      

### Get height of text from dimensions
$textheight = abs($box[5] - $box[1]);

### Get x-coordinate of centered text horizontally using length of the image and length of the text
//$xcord = ($imagewidth/2)-($textwidth/2)-2;




### Get y-coordinate of centered text vertically using height of the image and height of the text
//$ycord = ($imageheight/2)+($textheight/2); 

        // if($align=='center')
        // {
           $xcord = ($imagewidth)-($textwidth)-2;   

       // $ycord =(( ($imageheight/2)+($textheight/2))  )+$testcount; 
        // $testcount=$testcount+65;  
        if($i==0)
        {
             $testnewcount= $fontarray[$j];      
        }
              //$testcount=$testcount+$fontarray[$j]/2;    
            if($testnewcount<$fontarray[$j])
            {
                  $testcount=$testcount+$fontarray[$j]/2;

                  $ycord =(( ($imageheight/2)+($textheight/2))  )+$testcount;  

            }
            else
            {
                $ycord =(( ($imageheight/2)+($textheight/2))  )+$testcount;  


            }

         $testcount=$testcount+$fontarray[$j]; 

         $testnewcount= $fontarray[$j];     
//$ycord = ($imageheight/2)+($textheight/2);
/*
for($i=0;$i<$count;$i++)
{
        $newcount=count($fontarray); 

        for($j=0;$j<$newcount;$j++)

{

    if($j==$i)
    {     */
   //  $xcord=$xcord+2;
 //  $ycord=$ycord+100;
  // imagettftext ( $im, $fontarray[$j], $fontangle, $xcord, $ycord, $fontcolor, $font, $myArray[$i] );       
    //    imagettftext ( $im, $fontarray[$j], $fontangle, $xcord, $ycord, $fontcolor, $font, $ycord );   
      $xcord=$xcord-500;
    imagettftext ( $im, $fontarray[$j], $fontangle, $xcord, $ycord, $fontcolor, $font, $myArray[$i] );   
         }

         }

 } 

}



if($align=='each')
         {


              $box = imageTTFBbox($fontarray[$j],$fontangle,$font,$myArray[$i]);    

### Get width of text from dimensions
$textwidth = abs($box[4] - $box[0]);      

### Get height of text from dimensions
$textheight = abs($box[5] - $box[1]);

### Get x-coordinate of centered text horizontally using length of the image and length of the text
$xcord = ($imagewidth/2)-($textwidth/2)-2;




### Get y-coordinate of centered text vertically using height of the image and height of the text
$ycord = ($imageheight/2)+($textheight/2); 



    $count=count($myArray); 

$testnewcount=0;
for($i=0;$i<$count;$i++)
{
        $newcount=count($fontarray); 

        for($j=0;$j<$newcount;$j++)

{


    if($j==$i)
    {



        $stringnewstr='';
        $string=$myArray[$i];
                for($k=0; $k < strlen($string); $k++){ 
$stringnewstr=$stringnewstr." ".$string[$k]; 
} 
                $ycord = $ycord + 20;      
           imagettftext ( $im, $fontarray[$j], $fontangle, $xcord , $ycord, $fontcolor, $font, $stringnewstr);   
          // $xcord = $xcord + 20;  
          $ycord = $ycord + 20;      
    }           

         }




}
}



$html=imagepng($im);

### Close the image
imagedestroy($im);   

?>