简体   繁体   English

使用gd库在php上居中图像

[英]Centering image on php with gd library

hey guys i have been doing some code on php ..but its not giving me the output which i expected ..The code is 嗨,大家好,我一直在做一些关于php的代码。但是它没有给我我期望的输出。

html code HTML代码

<html>
    <body>
        <form action="images.php" method="post">
            Enter image Name :<input type="text" name="imagename">
            <br></br>
            <input type="submit" name="sumbit">
            <br></br>
        </form>
    </body>
</html>

In this html code user is allowded to type his name so that the image is generated according to the name.. 在此html代码中,允许用户键入其名称,以便根据该名称生成图像。

the php code PHP代码

<?php
    $name = $_POST['imagename'];
    if($_POST['imagename'] != ''){
        header("Content-Type: image/png");
        $name = $_POST['imagename'];
        $im = @imagecreate(800,600);
        $background_color = imagecolorallocate($im, 0xFF, 0xCC, 0xDD);
        $text_color = imagecolorallocate($im, 133, 14, 91);
        imagestring($im, 5, 300, 300,  "$name", $text_color);
        imagepng($im);
        imagedestroy($im);
    }
    else echo "no image created";
?>

This php code generates the image accrding to the name given.. 此php代码根据给定的名称生成图像。

The image is generated fine with this piece of codes but what i need is that the image created must appear on the center of the browser ...i have tried it using <img src="file.php> on the html file..but it didnt worked .. 使用这段代码可以很好地生成图像,但是我需要创建的图像必须出现在浏览器的中心...我已经尝试使用html文件上的<img src="file.php> 。但是没有用..

It will be really helpful if you guys find me a solution..Thanks in advance 如果你们找到我一个解决方案,这将非常有帮助。

If you want to center your image in the browser, you need html and css. 如果要在浏览器中居中放置图像,则需要html和CSS。

I would recommend that instead of displaying the image directly using header("Content-Type: image/png"); 我建议不要使用header("Content-Type: image/png");直接显示图像header("Content-Type: image/png"); , you save the image to a file. ,将图像保存到文件中。

Then your script can output html and include the image in an image tag or as a background image. 然后,您的脚本可以输出html,并将图像包含在图像标签中或作为背景图像。 That image can be centered in the browser easily using css. 使用CSS可以轻松地在浏览器中将图像居中。

Here you'll find an example of how to center text in a handmade image. 在这里,您将找到一个示例,说明如何在手工图像中居中放置文本。 Citing that page, you should do: 引用该页面,您应该执行以下操作:

 <?php
     $fw = imagefontwidth(5);     // width of a character
     $l = strlen("$name");        // number of characters
     $tw = $l * $fw;              // text width
     $iw = imagesx($im);          // image width, 800 for your case

     $xpos = ($iw - $tw) / 2;
     $ypos = 10;
     imagestring ($im, 5, $xpos, $ypos, "$name", $color);   

     //...
 ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM