php gd保存图片,php用gd库生成图片后上载有关问题

本文探讨了如何在PHP中使用GD库生成图片后直接进行下载,而不是先保存到本地。作者遇到的问题是尝试直接下载未保存的图片失败。解决方案是通过在内存中保存图片内容,然后利用`ob_start()`和`ob_get_clean()`获取图片数据,最后设置HTTP头进行下载。这种方法避免了图片落地的过程。
摘要由CSDN通过智能技术生成

php用gd库生成图片后下载问题

是这样的,我在用GD库生成图片后,不保存图片能直接下载吗? 试了一个早上还是不行…

image.php

//创建一个真彩画布

$image = imagecreatetruecolor(400,190);

//背景创建颜色

$green = imagecolorallocate($image,255,255,255);

//填充画布颜色

imagefill($image,0,0,$green);

//输出图片

header("Content-Type: image/jpeg");

imagejpeg($image);

//销毁资源

imagedestroy($image);

index.php

imagedown.php

if(isset($_GET['filename'])){

//var_dump(getimagesize($_GET['filename']));

download($_GET['filename']);

}

function download($fileName){

header("Content-Type: image/jpeg");

header('Content-Disposition: attachment; filename="'.$fileName.'"');

header('Content-Length: '.filesize($fileName));

readfile($fileName);

}

------解决方案--------------------

不可以的,必须经过图片落地这一过程。php的gd库貌似不支持内存直接读取生成的图片内容,只能保存到本地再读取。

建议改写gd库,提供获取图片内容函数。

------解决方案--------------------

这样写download('x.jpg');

function image() {

//创建一个真彩画布

$image = imagecreatetruecolor(400,190);

//背景创建颜色

$green = imagecolorallocate($image,255,255,0);

//填充画布颜色

imagefill($image,0,0,$green);

//输出图片

//header("Content-Type: image/jpeg");

imagejpeg($image);

//销毁资源

imagedestroy($image);

}

function download($fileName){

ob_start();

image();

$s = ob_get_clean();

header("Content-Type: image/jpeg");

header('Content-Disposition: attachment; filename="'.$fileName.'"');

header('Content-Length: '.strlen($s));

echo $s;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值