小編給大家分享一下php圖片類型的轉(zhuǎn)換方法,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
創(chuàng)新互聯(lián)公司專注于企業(yè)營(yíng)銷型網(wǎng)站、網(wǎng)站重做改版、天津網(wǎng)站定制設(shè)計(jì)、自適應(yīng)品牌網(wǎng)站建設(shè)、HTML5、商城網(wǎng)站開(kāi)發(fā)、集團(tuán)公司官網(wǎng)建設(shè)、外貿(mào)網(wǎng)站制作、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁(yè)設(shè)計(jì)等建站業(yè)務(wù),價(jià)格優(yōu)惠性價(jià)比高,為天津等各大城市提供網(wǎng)站開(kāi)發(fā)制作服務(wù)。
php圖片類型轉(zhuǎn)換的實(shí)現(xiàn)方法:首先安裝php擴(kuò)展gd和exif;然后通過(guò)“transform_image”方法實(shí)現(xiàn)圖片類型轉(zhuǎn)換;最后返回轉(zhuǎn)換結(jié)果即可。
需求
開(kāi)發(fā)過(guò)程中總會(huì)遇到一些需求需要對(duì)圖片格式進(jìn)行轉(zhuǎn)換。比如 gif轉(zhuǎn)png,jpg轉(zhuǎn)png
如最近使用某平臺(tái)的圖片文件識(shí)別,居然不支持gif格式,那么就需要將gif處理成png等。
依賴
php擴(kuò)展 gd 和 exif
實(shí)現(xiàn)
/** * 圖片格式轉(zhuǎn)換 * @param string $image_path 文件路徑或url * @param string $to_ext 待轉(zhuǎn)格式,支持png,gif,jpeg,wbmp,webp,xbm * @param null|string $save_path 存儲(chǔ)路徑,null則返回二進(jìn)制內(nèi)容,string則返回true|false * @return boolean|string $save_path是null則返回二進(jìn)制內(nèi)容,是string則返回true|false * @throws Exception * @author klinson*/ function transform_image($image_path, $to_ext = 'png', $save_path = null) { if (! in_array($to_ext, ['png', 'gif', 'jpeg', 'wbmp', 'webp', 'xbm'])) { throw new \Exception('unsupport transform image to ' . $to_ext); } switch (exif_imagetype($image_path)) { case IMAGETYPE_GIF : $img = imagecreatefromgif($image_path); break; case IMAGETYPE_JPEG : case IMAGETYPE_JPEG2000: $img = imagecreatefromjpeg($image_path); break; case IMAGETYPE_PNG: $img = imagecreatefrompng($image_path); break; case IMAGETYPE_BMP: case IMAGETYPE_WBMP: $img = imagecreatefromwbmp($image_path); break; case IMAGETYPE_XBM: $img = imagecreatefromxbm($image_path); break; case IMAGETYPE_WEBP: //(從 PHP 7.1.0 開(kāi)始支持) $img = imagecreatefromwebp($image_path); break; default : throw new \Exception('Invalid image type'); } $function = 'image'.$to_ext; if ($save_path) { return $function($img, $save_path); } else { $tmp = __DIR__.'/'.uniqid().'.'.$to_ext; if ($function($img, $tmp)) { $content = file_get_contents($tmp); unlink($tmp); return $content; } else { unlink($tmp); throw new \Exception('the file '.$tmp.' can not write'); } } }
使用
// 轉(zhuǎn)換后保存在test.png transform_image($url, 'png', './test.png'); transform_image($filepath, 'png', './test.png'); // 轉(zhuǎn)換后二進(jìn)制結(jié)果直接返回 transform_image($url, 'png'); transform_image($filepath, 'png');
看完了這篇文章,相信你對(duì)php圖片類型的轉(zhuǎn)換方法有了一定的了解,想了解更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!