php - 图像无法正确保存

标签 php image text

这是我正在制作的项目的链接:http://1-to-n.com/ik/

很简单,您输入任何内容并按提交,然后它会转到下一页并在图片上显示文本。一切工作都很好,但是当我右键单击图片并尝试保存它时,扩展名很奇怪,例如“picture.php.jpe”。

图片生成页面代码如下

<?php
//Set the Content Type
header('Content-type: image/jpeg');

// Create Image From Existing File
$jpg_image = imagecreatefromjpeg('vote.jpg');

// Allocate A Color For The Text
$white = imagecolorallocate($jpg_image, 47, 45, 46);

// Set Path to Font File
$font_path = 'MISTRAL.TTF';

// Set Text to Be Printed On Image
$text = $_POST['name'];

// Print Text On Image
imagettftext($jpg_image, 75, 0, 500, 130, $white, $font_path, $text);

// Send Image to Browser
imagejpeg($jpg_image);

// Clear Memory
imagedestroy($jpg_image);
?> 

最佳答案

这里的解决方案是Content-Disposition,但您想要什么取决于您希望 UI 如何工作。

您要设置:

header('Content-Disposition: %token%; filename="%name_of_file%"');

地点:

  • %name_of_file% 是您希望用户查看的文件的名称

  • %token%附件内联 之一。如果将其设置为附件,将立即提示用户下载文件,浏览器将不会像当前那样显示图像。如果您设置内联,用户将在浏览器 Pane 中按当前状态显示图像,并且他们需要右键单击 -> 另存为才能保存图像。

您需要先决定 UI 如何工作,然后才能确定使用哪个 header 。

为了清楚起见,这里有几个具体示例:

// Prompt the user to save the file immediately
header('Content-Disposition: attachment; filename="file.jpg"');

// OR

// Display the image to the user and ask them to manually save it
header('Content-Disposition: inline; filename="file.jpg"');

值得注意的是,IIRC(旧版本的 IE)存在内联问题,因为它们没有注意到建议的文件名。不过,可以通过向 Content-Type: 添加 name="" token 来解决此问题。这是违反标准的行为,但也相当无害。

关于php - 图像无法正确保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16107925/

相关文章:

php - 正确使用依赖注入(inject)容器

php - 多个php docker容器之间的通信

php - 寻找一种将列出的数据库结果包装在 div 中的方法

php - 强制实现接口(interface)的类定义常量

javascript - 将图像指定为 css 背景图像

python - 图片类型错误 : OpenCV Python

html - 网站在手机上看起来不一样

css - div 的内联文本位置

图像分析 - 如何从瓶子中提取图像标签

从文本文件创建链表