PHP 类生成图像的问题

发布于 2024-12-05 07:00:05 字数 853 浏览 2 评论 0原文

我编写了这段代码:

class Generate{
    private $canvas;
    function __construct($width, $height){
        $this->canvas = imagecreatetruecolor($width, $height);
    }
    public function bg($r=0,$g=0,$b=0){
        $color = imagecolorallocate($this->canvas, $r, $g, $b);
        imagefill($this->canvas, 0, 0, $color);
    }
    public function gen(){
        header('Content-Type: image/png');
        imagepng($this->canvas, NULL, 9);
        imagedestroy($this->canvas);
    }
}

并用以下方式调用它:

$G = new Generate(100, 100);
$G->bg(255, 255, 255);
$G->gen();

当我注释掉 gen() 函数中的标头并将其设置为保存图像时,它生成的图像很好。像这样:

imagepng($this->canvas, 'img.png', 9);

但我希望它发送标头(输出图像),但它给了我一个错误。有人可以告诉我我做错了什么吗?你甚至可以在 PHP 类中发送标头吗?

当我不使用 OOP 时,这段代码工作正常

i wrote this code:

class Generate{
    private $canvas;
    function __construct($width, $height){
        $this->canvas = imagecreatetruecolor($width, $height);
    }
    public function bg($r=0,$g=0,$b=0){
        $color = imagecolorallocate($this->canvas, $r, $g, $b);
        imagefill($this->canvas, 0, 0, $color);
    }
    public function gen(){
        header('Content-Type: image/png');
        imagepng($this->canvas, NULL, 9);
        imagedestroy($this->canvas);
    }
}

and called it with this:

$G = new Generate(100, 100);
$G->bg(255, 255, 255);
$G->gen();

its generating image fine when i comment out the header in the gen() function and set it to save the image. Like this:

imagepng($this->canvas, 'img.png', 9);

but i want it to send the header(output the image) but it gives me an error. can someone please tell me what i'm doing wrong? can you even send headers with-in a PHP class?

this code works fine when i don't use OOP

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

天冷不及心凉 2024-12-12 07:00:05

您问题的答案是,您可以。您可以在将任何输出发送给客户端之前随时发送标头,我怀疑这是您的问题。

您还可以检查要保存文件的编码。如果将文件保存为UTF-8,请确保在没有字节订单标记的情况下保存它。这将其视为输出,并且将始终是文件中的第一个字符,意味着header()的任何调用都会生成警告。

The answer to your question is yes, you can. You can send headers at any time before you send any output to the client, which I suspect is what your issue is.

You can also check the encoding that you're saving your file in. If you are saving your file as UTF-8, make sure you save it without a byte order mark. This counts as output, and will always be the first character in your file meaning any call to header() will generate a warning.

草莓酥 2024-12-12 07:00:05

当您发布时,该代码对我来说非常适合我;您确定您不仅在白色背景上丢失了100x100白色图像吗?尝试将颜色更改为127,255,255(可爱的aqua),看看它是否显示。

The code works perfectly for me when I run it as you posted it; are you sure that you aren't just losing your 100x100 white image on a white background? Try changing the color to, say, 127,255,255 (a lovely aqua) and see if it shows up.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文