在开发Sax的时候就在考虑怎么实现自动生成缩略图的方案,比较好的方案是使用阿里云或者腾讯云的对象存储,自动生成压缩后的图片,但是对于小博客而已确实大材小用,后来也试过使用timthumb的方案,好处是可以本地处理,自动缓存,不好的就是托一长串链接,还要修改主题。同时也发现写的function.php方法获取缩略图有bug,考虑可以在获取缩略图的方法里处理。

function get_postthumb($obj) {
    require_once('assets/thumb.php');

    preg_match_all( "/<[img|IMG].*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/", $obj->content, $matches );
    $thumb = '';
    $attach = $obj->attachments(1)->attachment;
    if($obj->fields->img) {
        $thumb = $obj->fields->img;
    }elseif(isset($attach->isImage) && $attach->isImage == 1){
        $thumb = $attach->url;
    }elseif(isset($matches[1][0])){
        $thumb = $matches[1][0];
    } else {
        $thumb = '';
    }

    if($thumb) {
        preg_match('/\/([^\/]+\.[a-z]+)[^\/]*$/',$thumb,$match);
        $tempurl = str_replace('.','_thumb.',$match[1]);
        if(!is_file('thumb/'.$tempurl)) {
            createThumbnail($thumb,220,150,'thumb/',$tempurl);
        }
        return 'https://www.nsvita.com/thumb/'.$tempurl;
    } else {
        return '';
    }
}

获取内容的同时会在根目录thumb下生成一个指定大小的缩略图。

thump.php源码


<?php

function createThumbnail( $src, $width, $height, $dir, $fle ) {
    $img_url = file_get_contents( $src );
    $img = imagecreatefromstring( $img_url );

    $o_width = imagesx($img); //取得原图宽
    $o_height = imagesy($img); //取得原图高

    //判断处理方法
    if($width>$o_width || $height>$o_height){//原图宽或高比规定的尺寸小,进行压缩
        $newwidth=$o_width;
        $newheight=$o_height;
    }
    if($o_width>$width){
        $newwidth=$width;
        $newheight=$o_height*$width/$o_width;
    }
    if($newheight>$height){
        $newwidth=$newwidth*$height/$newheight;
        $newheight=$height;
    }

    $thumb = imagecreatetruecolor( $newwidth, $newheight );

/**
    I quoted this one out since I ran in compatibility issues, I'm using PHP 5.3.x
    and imagesetinterpolation() doesn't exist in this version

    imagesetinterpolation( $thumb, IMG_SINC ); // Recommended Downsizing Algorithm
**/

    imagecopyresampled( $thumb, $img, 0, 0, 0, 0, $newwidth, $newheight, $o_width, $o_height );

    $result = imagejpeg( $thumb, $dir . $fle );

    imagedestroy( $thumb ); 
    imagedestroy( $img );

    return $result;
}

目前这些代码不建议直接拿来用,缩略图生成尺寸有问题