当前位置: 首页 > 知识库问答 >
问题:

对准中心,左,右

樊博雅
2023-03-14

我使用imagettftext()函数从文本转换图像。现在,我正试图将转换后的图像文本对齐到中心、左侧和右侧,但我找不到任何方法进行排序。如果有人知道如何做到这一点,请告诉我。下面是我用来在php中转换文本图像的代码。

演示链接:-点击这里

 <?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个答案

丌官瀚
2023-03-14

我已经提出了一种解决方案,可以将左对齐、居中、单独的字母转换为文本,并使用imagettftext()函数进行转换

答案是有一些位置问题,但很快我们会解决它

演示链接:-单击此处

所有align的示例输出

完整解决方案

1) 索引。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>

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

?>
艾弘义
2023-03-14

答案似乎很直截了当,实际上也在您提供的代码中。请注意以下两行:

### 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手册-imagettftext()

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

示例中的代码在中间对齐文本。向左对齐:

$xcord = 0;

要对齐八个:

$xcord = ($imagewidth)-($textwidth);
 类似资料:
  • 问题内容: 我想将a浮动到中心。可能吗?在IE中无法正常工作。 问题答案: 本身没有浮子居中。如果要将块元素居中放置在另一个元素中,请执行以下操作: 与: 现在,这不会使文本环绕(就像使用左右浮动),但是就像我说的:没有浮动中心。

  • 我有一个Flexbox。它的内容是NxN个正方形。我想要容器适合尽可能多的这些方块给定的显示宽度。我想让flexbox在页面中对齐。 然而问题是当我使用 则最后一行不向左对齐。但是,如果我更改为 则整个容器在页面上不再以中心对齐的方式显示。我能以某种方式实现两个的混合吗,所以就是这个例子,我将对齐5个项目,但最后一行将对齐前几行中的第一个项目? 最小再现:

  • 我读过关于.NET标准和.NET核心之间的区别,但我真的不知道区别是什么,也不知道什么时候选择.NET标准库项目,什么时候选择.NET核心库项目。

  • 你好,堆栈溢出成员 这是列标题的数组。我希望列1到列5左对齐(列1到列5的所有标题、子标题和表格数据单元格左对齐),而我希望列6到列8居中对齐(列1到列5的所有标题、子标题和表格数据单元格居中对齐)。请帮我解决这个问题,因为我只能使所有列居中或左对齐。 如果你能帮助我,请提供一个关于CodeSandbox的演示 这是我的标题数据

  • 我正在用数字键盘制作登录屏幕,我似乎不能在窗格中对齐按钮的网格窗格。我做错了什么? GUI代码很冗长,而且这个帖子编辑器不允许我按原样发布问题,所以我需要这些额外的行让它接受我的问题。如果我认为我可以把代码缩减到数字广告。设置对齐(Pos.Center),并且仍然清楚地表明我是如何尝试将网格窗格居中的。我真诚地感谢那些可能借给我时间帮助我解决这个问题的人。 我的问题是GridPane本身绘制在屏幕

  • 有一个页面站点视图。有一段代码(我想将图像)居中) null null 如下图所示(我想将图像)居中) Youtube图标 如何实现像第一个链接上的显示?(我想将按钮居中)