踩坑原生php函数imagecreatefromstring


背景

最近开发中,使用imagecreatefromstring原生php函数出现这样一种情况:

明明是一张“竖着的图”,将其转存后,竟然变成了“横着的图”

相关代码如下:

//1.获取jpg图片内容字符串
$img = file_get_contents('before.jpg');

//2.使用`imagecreatefromstring`生成resource
$imgResource = imagecreatefromstring($img);

//3.将resource新建(保存)成一张图片
imagejpeg($imgResource, 'after.jpg');

代码运行结果图片示例:
在这里插入图片描述


分析

其实图片中,包含着“EXIF”信息,里面有着图片相关的内容。而用不同设备拍摄出的照片,包含的图片信息内容各不相同,其中,Apple手机又有自己独特的信息

这个图片是随手拿来画来示例的,包含的信息其实是比较少的

(这里就给蜂巢阅读器打个免费广告吧)
在这里插入图片描述

那么,我们借助php自带的函数来查看图片的EXIF信息看看吧

代码如下:

$exif = exif_read_data('before.jpg');
print_r($exif);

示例结果(由于EXIF读取的内容过多,这里只保留关键字段):

Array
(
    [FileName] => before.jpg
    [FileDateTime] => 1624621614
    [FileSize] => 2769146
    [FileType] => 2
    [MimeType] => image/jpeg
    [SectionsFound] => ANY_TAG, IFD0, THUMBNAIL, EXIF, GPS
    [Make] => Apple
    [Model] => iPhone 6s
    [Orientation] => 6
    [XResolution] => 72/1
    [YResolution] => 72/1
    [ResolutionUnit] => 2
}

返回的内容中,有一个关键字段“Orientation”,值为6,这是什么意思呢?

引用下官方文档Note中的相关内容:

When the new update came out from Apple for iOS6 it provided the ability for iPad, iPod, and iPhones to be able to upload files from the device through Safari. Obviously this will open up an array of implementations where at one point it was just not possible.

The issue comes when a photo is uploaded it will be dependent on the location of the “button” when the photo was taken. Imagine if you will that you have your iPhone turned with the button at the top and you take a photo. The photo when uploaded to your server might be “upside down”.

简单转化成本文相关内容就是:自IOS6起,Apple产品将会携带Orientation相关EXIF信息,用于识别图片“是否颠倒”

如果直接使用imagecreatefromstring函数来进行转换保存图片的话,就会自动识别相关信息,将我们的图片给处理成“方向正确的图片”


解决

其实这个问题在“8 years ago”就已经被解决了,官方已经给出了解决方法:

//1.获取jpg图片内容字符串
$img = file_get_contents('before.jpg');

//2.使用`imagecreatefromstring`生成resource
$imgResource = imagecreatefromstring($img);

//3.获取原图的exif信息,根据exif信息中的Orientation信息进行旋转
$exif = exif_read_data('before.jpg');
if (!empty($exif['Orientation'])) {
    switch ($exif['Orientation']) {
        case 8:
            $imgResource = imagerotate($imgResource, 90, 0);
            break;
        case 3:
            $imgResource = imagerotate($imgResource, 180, 0);
            break;
        case 6:
            $imgResource = imagerotate($imgResource, -90, 0);
            break;
    }
}

//4.将resource新建(保存)成一张图片
imagejpeg($imgResource, 'after.jpg');

这样一来,才能够保证原本“竖着的图”,转换保存之后也一定是“竖着的图”

无知真是造孽啊


参考文献

https://www.php.net/manual/zh/function.exif-read-data.php#110894

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值