Images.php 7.27 KB
<?php

/**
 * User: Zip
 * Date: 15/10/28
 * Time: 下午13:08
 */

namespace Plugin;

class Images
{

    private static $domain = '.static.yhbimg.com';
    private static $default_image = '/2015/08/25/02/01dd632a6e07bfef457ce4beda21dd6413.png';
    private static $domainList = array(
        '01' => array(
            'img10.static.yhbimg.com',
            'img11.static.yhbimg.com',
        ),
        '02' => array(
            'img12.static.yhbimg.com',
            'img13.static.yhbimg.com'
        ),
        'yhb-head' => 'head.static.yhbimg.com'
    );
    private static $qiniuDomain = 'yhfair.qiniudn.com';

    /**
     * 缩略图模板
     * @param $fileName
     * @param $bucket
     * @param string $position ()
     * @param string $background
     * @return string
     */
    static function template($fileName, $bucket = 'yhfair', $mode = 1)
    {
        return self::url($fileName, $bucket, $mode);
    }

    /**
     * 
     * @param unknown $fileName
     * @param string $bucket
     * @return string
     */
    public static function getSourceUrl($fileName, $bucket = 'yhfair')
    {
        if (stripos($fileName, 'http://') === 0) {
            return $fileName;
        }
        $domain = self::getDomain($bucket, $fileName);
        return '//' . $domain . '/' . $bucket . $fileName;
    }

    /**
     * 根据尺寸获得图片url
     * @param unknown $fileName
     * @param unknown $width
     * @param unknown $height
     * @param number $mode
     * @param string $bucket
     * @return mixed
     */
    public static function getImageUrl($fileName, $width, $height, $mode = 2, $bucket = 'goodsimg')
    {
        if (!is_string($fileName)) {
            return self::template(self::$default_image, $bucket, $mode);
        }
        if (stripos($fileName, 'http://') !== 0) {
            $fileName = self::template($fileName, $bucket, $mode);
        }
        return strtr($fileName, array('{width}' => $width, '{height}' => $height, '{mode}' => $mode, 'http://' => '//'));
    }

    /**
     * 获取图片URL模板
     * @param $fileName
     * @param int $mode
     * @param string $bucket
     * @return string
     */
    public static function url($fileName, $bucket = 'yhfair', $mode = 1)
    {
        $domain = self::getDomain($bucket, $fileName);
        return self::getImgTemplateUrl($bucket . $fileName, $mode, $domain);
    }

    public static function getDomain($bucket, $fileName)
    {
        $domain = '';
        if (!empty(self::$domainList[$bucket])) {
            $domain = self::$domainList[$bucket];
        } else {
            $node = mb_substr($fileName, 15, 2);
            if (!empty(self::$domainList[$node])) {
                $domainList = self::$domainList[$node];
                $nodeNum = sprintf('%u', crc32($fileName)) % count($domainList);
                $domain = $domainList[$nodeNum];
            }
        }
        return $domain;
    }

    /**
     * 图片上传
     * @param string $name 文件表单name, 即用于$_FILES[$name]
     * @param string $path
     */
    public static function saveImage($name, $path = 'suggest')
    {
        if (empty($_FILES[$name])) {
            return array();
        }
        $files = $_FILES[$name];
        $images = array();
        if (is_array($files['tmp_name'])) {
            foreach ($files['tmp_name'] as $k => $tmp_name) {
                if (!empty($tmp_name)) {
                    $images[$files['name'][$k]] = $tmp_name;
                }
            }
        } else {
            $images[$files['name']] = $files['tmp_name'];
        }

        return self::uploadStreamImage($images, $path);
    }

    /**
     * 上传图片[图片上传域名限制于http://test.service.api.yohobuy.com]
     *
     * @param string | array(filename => absolute file path)  $file
     *   url:http://upload.static.yohobuy.com?project=sns&fileData=xxx
     * @param string $path
     * @return mixed
     */
    public static function uploadStreamImage($file, $path = 'suggest')
    {
        $end = "\r\n";
        $twoHyphens = "--";
        $boundary = "*****";
        $stream = '';
        $files = is_array($file) ? $file : array($file);
        foreach ($files as $name => $filename) {
            if (!file_exists($filename)) {
                continue;
            }
            $name = is_numeric($name) ? name . '.jpg' : $name;
            $stream .= $twoHyphens . $boundary . $end;
            $stream .="Content-Disposition: form-data; " . "name=\"fileData\";filename=\"" . $name . "\"" . $end; // form file element name :fileData
            $stream .= $end;
            $stream .= file_get_contents($filename);
            $stream .= $end;
        }
        if (empty($stream)) {
            return false;
        }
        $stream .= $twoHyphens . $boundary . $end;
        $stream .="Content-Disposition: form-data; " . "name=\"project\"" . $end;
        $stream .= $end;
        $stream .= $path; //project sns
        $stream .= $end;
        $stream .= $twoHyphens . $boundary . $twoHyphens . $end;
        $opts = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'content-type:multipart/form-data;boundary=' . $boundary,
                'content' => $stream
            )
        );
        $context = stream_context_create($opts);
        $result = json_decode(file_get_contents('http://upload.static.yohobuy.com', false, $context), true);
        if (!empty($result['data']['imagesList'])) {
            $imgExtra = '?imageMogr2/thumbnail/130x130/extent/130x130/background/d2hpdGU=/position/center/quality/90';
            $imgList = array('imgList' => array());

            if (count($file) == 1 || !is_array($file)) {
                $imgRelUrl = current($result['data']['imagesList']);
                $imgList['imgList'][] = array(
                    'imgUrl' => self::getSourceUrl($imgRelUrl, 'suggest') . $imgExtra,
                    'imgRelUrl' => $imgRelUrl
                );
            } else {
                $img = array();
                foreach ($result['data']['imagesList'] as $val) {
                    $img = array();
                    $img['imgUrl'] = self::getSourceUrl($val, 'suggest') . $imgExtra;
                    $img['imgRelUrl'] = $val;
                    $imgList['imgList'][] = $img;
                }
            }

            return $imgList;
        } else {
            return false;
        }
    }

    /**
     * 获取模板的图片地址
     * @param $fileName
     * @param int $width
     * @param int $height
     * @param int $mode
     * @param null $domain
     * @return string
     */
    private static function getImgTemplateUrl($fileName, $mode = 1, $domain = null)
    {
        if ($domain == null) {
            $domain = self::$qiniuDomain;
        }
        $baseUrl = self::MakeBaseUrl($domain, $fileName);
        return self::MakeTemplateRequest($baseUrl);
    }

    private static function MakeBaseUrl($domain, $key) // => $baseUrl
    {
        $keyEsc = str_replace("%2F", "/", rawurlencode($key));
        return "http://$domain/$keyEsc";
    }

    private static function MakeTemplateRequest($url)
    {
        $ops = array();
        $ops[] = '{mode}';
        $ops[] = 'w/{width}';
        $ops[] = 'h/{height}';

        if (empty($ops)) {
            return $url;
        }

        return $url . "?imageView/" . implode('/', $ops);
    }

}