php jpg轉(zhuǎn)換成png圖片的方法:首先安裝php擴(kuò)展gd和exif;然后通過“function transform_image($image_path, $to_ext = 'png'…){…}”方法進(jìn)行轉(zhuǎn)換即可。
本文操作環(huán)境:windows7系統(tǒng)、PHP7.1版,DELL G3電腦
PHP簡單實(shí)現(xiàn)圖片格式轉(zhuǎn)換(jpg轉(zhuǎn)png,gif轉(zhuǎn)png等)
需求
開發(fā)過程中總會(huì)遇到一些需求需要對圖片格式進(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 <klinson@163.com> */ 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 開始支持) $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');
推薦學(xué)習(xí):《PHP視頻教程》