随着iphone等设备默认使用heic(high efficiency image format)格式拍照,我们的web应用经常会收到这类图片。heic格式在文件大小上确实表现出色,能有效节省存储空间和带宽。然而,它的兼容性却远不如传统的jpg。许多浏览器、图片处理库甚至操作系统,对heic的支持都不尽如人意。
这就给开发者带来了实际的挑战:
面对这些问题,我们急需一个既简单又高效的解决方案,能够无缝地将HEIC图片转换为更通用的JPG格式,同时尽可能减少对服务器环境的依赖。
maestroerror/php-heic-to-jpg
幸运的是,PHP社区总能涌现出优秀的解决方案。
maestroerror/php-heic-to-jpg
使用Composer安装
maestroerror/php-heic-to-jpg
立即学习“PHP免费学习笔记(深入)”;
<pre class="brush:php;toolbar:false;">composer require maestroerror/php-heic-to-jpg
安装完成后,你就可以在代码中轻松使用它了。
1. 将HEIC文件保存为JPG文件:
这是最常见的需求,只需一行代码即可实现:
<pre class="brush:php;toolbar:false;">use Maestroerror\HeicToJpg;
// 假设你的HEIC文件在项目根目录下
HeicToJpg::convert("image1.heic")->saveAs("image1.jpg");
echo "image1.heic 已成功转换为 image1.jpg";2. 获取转换后的JPG图片内容(二进制):
如果你需要将转换后的图片内容直接用于其他操作(例如上传到云存储或直接输出到浏览器),可以使用
get()
<pre class="brush:php;toolbar:false;">use Maestroerror\HeicToJpg;
$jpgContent = HeicToJpg::convert("image1.heic")->get();
// 现在 $jpgContent 包含了JPG图片的二进制数据,你可以对其进行任何操作
file_put_contents("new_image.jpg", $jpgContent);
echo "image1.heic 内容已获取并保存为 new_image.jpg";3. 从URL转换HEIC图片:
如果你的HEIC图片是公开可访问的URL,
convertFromUrl()
<pre class="brush:php;toolbar:false;">use Maestroerror\HeicToJpg;
HeicToJpg::convertFromUrl("https://example.com/some-heic-image.heic")->saveAs("remote_image.jpg");
echo "远程HEIC图片已转换并保存。";4. 智能判断文件是否为HEIC:
在处理用户上传的文件时,你可能需要先判断文件是否为HEIC格式,
isHeic()
<pre class="brush:php;toolbar:false;">use Maestroerror\HeicToJpg;
$fileIsHeic = HeicToJpg::isHeic("image1.heic");
if ($fileIsHeic) {
echo "这是一个HEIC文件,可以进行转换。";
HeicToJpg::convert("image1.heic")->saveAs("image1.jpg");
} else {
echo "这不是一个HEIC文件。";
}mdat
尽管
maestroerror/php-heic-to-jpg
error reading "meta" box: got box type "mdat" instead
maestroerror/heif-converter
解决方案步骤:
安装辅助包: 确保你的项目中也安装了
maestroerror/heif-converter
<pre class="brush:php;toolbar:false;">composer require maestroerror/heif-converter
安装libheif
heif-converter
libheif
heif-converter
sudo apt install libheif-examples
自动检测或手动指定路径:
php-heic-to-jpg
heif-converter-image
heif-converter
<pre class="brush:php;toolbar:false;">use Maestroerror\HeicToJpg;
// 假设你的heif-converter二进制文件在 /usr/local/bin/heif-converter-linux
HeicToJpg::convert("samsung_image.heic", "/usr/local/bin/heif-converter-linux")->saveAs("samsung_image.jpg");
// 对于MacOS M1芯片,可能需要指定 arm64 架构和路径
HeicToJpg::convertOnMac("m1_image.heic", "arm64", "/usr/local/bin/heif-converter-macos")->saveAs("m1_image.jpg");这样,即使面对“顽固”的HEIC文件,你也能确保它们被正确转换。
maestroerror/php-heic-to-jpg
它的优势显而易见:
mdat
有了
maestroerror/php-heic-to-jpg
以上就是告别HEIC图片转换烦恼:如何使用Composer和maestroerror/php-heic-to-jpg轻松搞定!的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号