FASTDFS(六)nginx+lua+GraphicsMagick 圖片自動縮放

1.安裝GraphicsMagickhtml

--使用yum安裝GraphicsMagicknginx

Shell代碼 git

# yum install ImageMagick

--查看安裝結果github

Shell代碼 緩存

# yum list installed | grep ImageMagick*
ImageMagick.x86_64     6.5.4.7-7.el6_5  @base

--驗證安裝結果bash

Shell代碼 app

# convert -sample 200x200 desktop.jpg desktop-200x200.jpg
# convert -sample 200x200 desktop.png desktop-200x200.png

2.安裝lua-nginx-modulecurl

--下載安裝LuaJIT測試

Shell代碼 ui

# wget http://luajit.org/download/LuaJIT-2.0.4.tar.gz
# tar -zxvf LuaJIT-2.0.4.tar.gz 
# cd LuaJIT-2.0.2
# make
# make install

--安裝lua-nginx-module

下載ngx_devel_kit,nginx_lua_module解壓

Shell代碼 

// 先導入環境變量,告訴nginx去哪裏找luajit
# export LUAJIT_LIB=/usr/local/lib
# export LUAJIT_INC=/usr/local/include/luajit-2.0

// 查看ngixn版本極其編譯參數
# /usr/local/nginx/sbin/nginx -V

// 添加ngx_devel_kit,lua-nginx-module模塊,從新編譯nginx
// 切勿make install,不然就成了覆蓋安裝
# ./configure --prefix=/usr/local/nginx \
--add-module=/usr/local/src/fastdfs-nginx-module/src \
--add-module=/usr/local/src/ngx_devel_kit-0.2.19 \
--add-module=/usr/local/src/lua-nginx-module-0.9.16
# make

// 備份舊的nginx程序,用新的nginx程序覆蓋舊的
# cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak
# cp ./objs/nginx /usr/local/nginx/sbin/nginx

// 再次查看ngixn版本極其編譯參數,確認安裝成功
# /usr/local/nginx/sbin/nginx -V
/usr/local/nginx/sbin/nginx: error while loading shared libraries: libluajit-5.1.so.2: cannot open shared object file: No such file or directory
// 將libluajit-5.1.so.2安裝到/usr/lib中並從新加載
# ln -s /usr/local/lib/libluajit-5.1.so.2 /usr/lib/libluajit-5.1.so.2 
# ldconfig
# /usr/local/nginx/sbin/nginx -V

// 測試lua-nginx-module模塊
// nginx配置文件加入以下配置:
location ~* ^/2328(/.*) {
      default_type 'text/plain';
      content_by_lua 'ngx.say("hello, ttlsa lua")';
}
# curl http://localhost/2328/
hello, ttlsa lua

--配置nginx實現簡單自動生成縮略圖

Txt代碼 

// 修改nginx配置文件nginx.conf
location ~ '/images/([0-9a-z]+).jpg$' {
    root /var;
}

location ~ '/images/([0-9a-z]+)_([0-9]+)x([0-9]+).jpg$' {
    root /var;
    set $image_root '/var/images';
    set $fileName $1;
    set $width $2;
    set $height $3;
    set $origin $image_root/$fileName.jpg;
    set $file $image_root/${fileName}_${width}x$height.jpg;
    if (!-f $file) {
        rewrite_by_lua '
            local command = "convert -sample "..ngx.var.width.."x"..ngx.var.height.." "..ngx.var.origin.." "..ngx.var.file;
            os.execute(command);
         ';
  	}
}

// nginx從新加載配置
# /usr/local/nginx/sbin/nginx -s reload

// 在/var/images中上傳desktop.jpg圖片
訪問
http://192.168.117.101/images/desktop_200x200.jpg
返回404
// 查看日誌
# tail -f /usr/local/nginx/logs/error.log
convert: unable to open image `/var/images/desktop_100x100.jpg': Permission denied @ blob.c/OpenBlob/2480.

// nginx: worker process 的用戶是nobody,沒有root權限,沒法操做/var/images的文件
// 修改/var/images的權限爲全部人可修改# ps -ef | grep nginx
root     10065     1  0 00:05 ?        00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nobody   12100 10065  0 11:35 ?        00:00:00 nginx: worker process      
root     12108  9959  0 11:37 pts/1    00:00:00 grep nginx

訪問
http://192.168.117.101/images/desktop_200x200.jpg
返回縮略圖,/var/images多了對應的縮略圖

--配置nginx實現簡單自動生成縮略圖

--進階,將縮略圖文件和原圖分開存儲

Txt代碼 

location ~ '/images/thumbnail/([0-9a-z]+)_([0-9]+)x([0-9]+).jpg$' {
		root /var;
}

location ~ '/images/([0-9a-z]+)_([0-9]+)x([0-9]+).jpg$' { 
		root /var; 
    set $image_root '/var/images';  
    set $fileName $1;  
    set $width $2;  
    set $height $3;  
    set $origin $image_root/$fileName.jpg;  
    set $file $image_root/thumbnail/${fileName}_${width}x$height.jpg;
    set $uriNew /images/thumbnail/${fileName}_${width}x$height.jpg;
    if (-f $file) {  
    	rewrite ^ $uriNew;
    	break;
    }  
    if (!-f $origin) {
			return 404;
		} 
		rewrite_by_lua '  
			local width = tonumber(ngx.var.height);
			local height = tonumber(ngx.var.height);
			if width and height then
				local command = "convert -sample "..ngx.var.width.."x"..ngx.var.height.." "..ngx.var.origin.." "..ngx.var.file;  
      	os.execute(command); 
      	ngx.req.set_uri(ngx.var.uriNew, true);
			else 
				ngx.exit(ngx.HTTP_NOT_FOUND);
			end
   	';
}

3.nginx + lua-nginx-module + fastdfs 實現動態縮略圖

/usr/local/nginx

|-conf

  |-lua

    |-fastdfs.lua

    |-restyfastdfs.lua

    |-storage.lua

    |-tracker.lua

    |-utils.lua

  |-nginx.conf

--主要的配置

nginx.conf

Txt代碼 

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;
		
    <span style="color: #ff0000;">lua_package_path "/usr/local/nginx/conf/lua/?.lua;;";</span>
		
    server {
        listen       80;
        server_name  localhost;
				
	location ~ '/images/thumbnail/([0-9a-z]+)_([0-9]+)x([0-9]+).jpg$' {
		root /var;
	}
				
	location ~ '/images/([0-9a-z]+)_([0-9]+)x([0-9]+).jpg$' { 
		root /var; 
		set $image_root '/var/images';  
		set $fileName $1;  
		set $width $2;  
		set $height $3;  
		set $origin $image_root/$fileName.jpg;  
		set $file $image_root/thumbnail/${fileName}_${width}x$height.jpg;
		set $uriNew /images/thumbnail/${fileName}_${width}x$height.jpg;
		if (-f $file) {  
			rewrite ^ $uriNew;
			break;
		}  
		if (!-f $origin) {
		    	return 404;
		} 
	    	rewrite_by_lua '  
	    		local width = tonumber(ngx.var.height);
	    		local height = tonumber(ngx.var.height);
	    		if width and height then
	    			local command = "convert -sample "..ngx.var.width.."x"..ngx.var.height.." "..ngx.var.origin.." "..ngx.var.file;  
	            	        os.execute(command); 
	            	        ngx.req.set_uri(ngx.var.uriNew, true);
	    		else 
	    			ngx.exit(ngx.HTTP_NOT_FOUND);
	    		end
	         	';
		}
				
	location /group1/M00 {
            alias /var/images;

            #set $image_root "/usr/local/openresty/nginx/proxy_tmp/images";
            set $image_root "/var/images";
            if ($uri ~ "/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/(.*)") {
                set $image_dir "$image_root/$3/$4/";
                set $image_name "$5";
                set $file "$image_dir$image_name";
            }

            if (!-f $file) {
                # 關閉lua代碼緩存,方便調試lua腳本
                #lua_code_cache off;
                content_by_lua_file "conf/lua/fastdfs.lua";
            }

            #ngx_fastdfs_module;
        }
				
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

    }

}

fastdfs.lua

Txt代碼 

-- 寫入文件
local function writefile(filename, info)
    local wfile=io.open(filename, "w") --寫入文件(w覆蓋)
    assert(wfile)  --打開時驗證是否出錯		
    wfile:write(info)  --寫入傳入的內容
    wfile:close()  --調用結束後記得關閉
end

-- 檢測路徑是否目錄
local function is_dir(sPath)
    if type(sPath) ~= "string" then return false end

    local response = os.execute( "cd " .. sPath )
    if response == 0 then
        return true
    end
    return false
end

-- 檢測文件是否存在
local file_exists = function(name)
    local f=io.open(name,"r")
    if f~=nil then io.close(f) return true else return false end
end

local area = nil
local originalUri = ngx.var.uri;
local originalFile = ngx.var.file;
local index = string.find(ngx.var.uri, "([0-9]+)x([0-9]+)");  
if index then 
    originalUri = string.sub(ngx.var.uri, 0, index-2);  
    area = string.sub(ngx.var.uri, index);  
    index = string.find(area, "([.])");  
    area = string.sub(area, 0, index-1);  

    local index = string.find(originalFile, "([0-9]+)x([0-9]+)");  
    originalFile = string.sub(originalFile, 0, index-2)
end

-- check original file
if not file_exists(originalFile) then
    local fileid = string.sub(originalUri, 2);
    -- main
    local fastdfs = require('restyfastdfs')
    local fdfs = fastdfs:new()
    fdfs:set_tracker("192.168.117.100", 22122)
    fdfs:set_timeout(1000)
    fdfs:set_tracker_keepalive(0, 100)
    fdfs:set_storage_keepalive(0, 100)
    local data = fdfs:do_download(fileid)
    if data then
       -- check image dir
        if not is_dir(ngx.var.image_dir) then
            os.execute("mkdir -p " .. ngx.var.image_dir)
        end
        writefile(originalFile, data)
    end
end

-- 建立縮略圖
local image_sizes = {"80x80", "800x600", "40x40", "60x60"};  
function table.contains(table, element)  
    for _, value in pairs(table) do  
        if value == element then
            return true  
        end  
    end  
    return false  
end 

if table.contains(image_sizes, area) then  
    local command = "convert " .. originalFile  .. " -thumbnail " .. area .. " -background gray -gravity center -extent " .. area .. " " .. ngx.var.file;  
    os.execute(command);  
end;

if file_exists(ngx.var.file) then
    --ngx.req.set_uri(ngx.var.uri, true);  
    ngx.exec(ngx.var.uri)
else
    ngx.exit(404)
end

參考資料:

https://github.com/openresty/lua-nginx-module
http://www.ttlsa.com/nginx/nginx-modules-ngx_lua/
http://www.2cto.com/os/201504/387948.html

http://houxiyang.com/archives/112/

https://github.com/hpxl/nginx-lua-fastdfs-GraphicsMagick

https://github.com/azurewang/lua-resty-fastdfs

相關文章
相關標籤/搜索