How to implement php image type conversion: first install the php extensions gd and exif; then implement image type conversion through the "transform_image" method; and finally return the conversion result.
Recommended: "PHP Video Tutorial"
Requirements
There will always be encounters during the development process Some requirements require conversion of image formats. For example, gif to png, jpg to png
If you have recently used the image file recognition of a certain platform and it does not support the gif format, then you need to process the gif into png, etc.
Depends on
php extension gd and exif
implementation
/** * 图片格式转换 * @param string $image_path 文件路径或url * @param string $to_ext 待转格式,支持png,gif,jpeg,wbmp,webp,xbm * @param null|string $save_path 存储路径,null则返回二进制内容,string则返回true|false * @return boolean|string $save_path是null则返回二进制内容,是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'); } } }
use
// 转换后保存在test.png transform_image($url, 'png', './test.png'); transform_image($filepath, 'png', './test.png'); // 转换后二进制结果直接返回 transform_image($url, 'png'); transform_image($filepath, 'png');
The above is the detailed content of How to convert php image type. For more information, please follow other related articles on the PHP Chinese website!