溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

php實(shí)現(xiàn)圖片格式轉(zhuǎn)換的方法是什么

發(fā)布時(shí)間:2020-08-25 09:17:27 來源:億速云 閱讀:152 作者:小新 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)php實(shí)現(xiàn)圖片格式轉(zhuǎn)換的方法是什么,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

php實(shí)現(xiàn)圖片格式轉(zhuǎn)換的方法:首先轉(zhuǎn)換后保存在【test.png】,代碼為【transform_image($url, 'png', './test.png')】;然后轉(zhuǎn)換后二進(jìn)制結(jié)果直接返回。

php實(shí)現(xiàn)圖片格式轉(zhuǎn)換的方法是什么

php實(shí)現(xiàn)圖片格式轉(zhuǎn)換的方法:

開發(fā)過程中總會(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 <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');

關(guān)于php實(shí)現(xiàn)圖片格式轉(zhuǎn)換的方法是什么就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI