You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP GD库将添加文字后的JPG图片保存为300DPI

解决方案

PHP 内置 GD 库的 imagejpeg() 方法默认输出的JPEG图片固定为72DPI,且没有提供直接调整DPI的官方参数,可通过以下两种方法修改:

方案1:使用Imagick扩展(推荐,稳定性最高)

如果你的服务器允许安装Imagick扩展,这是最可靠的修改方式,无需手动处理二进制文件,示例代码如下:

// 原GD逻辑处理图片加文字
$jpg_image = imagecreatefromjpeg('pic.jpg');
$white = imagecolorallocate($jpg_image, 255, 255, 255);
$font_path = 'arialbd.ttf';
$text = "This is a sunset!";
imagettftext($jpg_image, 25, 0, 75, 300, $white, $font_path, $text);

// 临时保存GD处理后的图片
$temp_path = 'temp.jpg';
imagejpeg($jpg_image, $temp_path, 100);
imagedestroy($jpg_image);

// 用Imagick修改DPI
$imagick = new Imagick($temp_path);
// 设置为300DPI,可按需修改数值
$imagick->setImageResolution(300, 300);
$imagick->setImageUnits(Imagick::RESOLUTION_PIXELSPERINCH);
// 保存最终文件
$imagick->writeImage('a.jpg');
$imagick->destroy();
// 删除临时文件
unlink($temp_path);

// 如果需要输出到浏览器,加上以下代码
// header('Content-type: image/jpeg');
// echo $imagick->getImageBlob();

方案2:仅用GD库,手动修改JPEG的JFIF头

如果无法安装Imagick,可通过修改JPEG文件开头的JFIF标记段的DPI字节实现修改,无需额外扩展:

// 原GD处理逻辑
$jpg_image = imagecreatefromjpeg('pic.jpg');
$white = imagecolorallocate($jpg_image, 255, 255, 255);
$font_path = 'arialbd.ttf';
$text = "This is a sunset!";
imagettftext($jpg_image, 25, 0, 75, 300, $white, $font_path, $text);

// 先把图片内容存到变量里不落地
ob_start();
imagejpeg($jpg_image, null, 100);
$jpeg_content = ob_get_clean();
imagedestroy($jpg_image);

// 修改JFIF头里的DPI信息,这里修改为300DPI
$dpi = 300;
// JFIF头固定位置:第13、14字节是X方向DPI,15、16字节是Y方向DPI
$jpeg_content[13] = chr($dpi >> 8);
$jpeg_content[14] = chr($dpi & 0xff);
$jpeg_content[15] = chr($dpi >> 8);
$jpeg_content[16] = chr($dpi & 0xff);

// 保存最终文件
file_put_contents('a.jpg', $jpeg_content);

// 如果需要输出到浏览器
// header('Content-type: image/jpeg');
// echo $jpeg_content;

注意:DPI是图片的元数据,仅会影响打印、排版类软件中图片的显示/输出尺寸,不会改变图片本身的像素总量和屏幕显示效果。

内容的提问来源于stack exchange,提问作者KOFF

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 02:06:03