centos7 openresty lua 自适应webp和缩放图片

news2024/10/6 2:22:03

目录

    • 背景
    • 效果图
    • 准备
      • 安装`cwebp`等命令,转换文件格式
      • 安装`ImageMagick`,压缩文件
      • 下载Lua API 操控ImageMagick的依赖包
    • 代码
    • 参考

背景

  • 缩小图片体积,提升加载速度,节省流量。

效果图

  • 参数格式 : ?image_process=format,webp/resize,p_20
    在这里插入图片描述

在这里插入图片描述

准备

安装cwebp等命令,转换文件格式

yum install  libwebp-devel libwebp-tools

安装ImageMagick,压缩文件

yum install  ImageMagick

下载Lua API 操控ImageMagick的依赖包

  • 网址:https://github.com/leafo/magick,到Releases下载,解压后得到如下:
    在这里插入图片描述
  • 复制magick包到lualib里,如下所示。
    在这里插入图片描述

代码

  • 修改conf文件,添加如下内容。
      location ~ \.(jpe?g|png|gif)$ {
  		     add_header Access-Control-Allow-Origin *;
              add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
               add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
               content_by_lua_file /usr/local/openresty/nginx/conf/lua/image-convert.lua;
        }
  • 创建/usr/local/openresty/nginx/conf/lua/image-convert.lua 文件。添加一下内容。



local originalFile = ngx.var.request_filename
 

local image_process = ngx.var.arg_image_process
-- local image_process = ngx.req.get_uri_args()["image_process"]

function fileExists(name)
  local f=io.open(name,"r")
  if f~=nil then io.close(f) return true else return false end
end

function tryServeFile(name, contentType)
    if fileExists(name) then
        local f = io.open(name, "rb")
        local content = f:read("*all")
        f:close()
        if contentType ~= "" then
            ngx.header["Content-Type"] = contentType
        end
        ngx.print(content)
        return true
    end
    return false
end

function serveFileOr404(name, contentType)
    if not tryServeFile(name, contentType) then
        ngx.exit(404)
    end
end


function ratioZip(originalFile,ratioFile) 
	if not fileExists(ratioFile) then
		local ratio_num = string.match(image_process, "%d+")
		local magick = require("magick")
		local img = assert(magick.load_image(originalFile))
		local r_num = tonumber(ratio_num) / 100
		local w = img:get_width() * r_num
		local h = img:get_height() * r_num
		img:destroy()
		
		local size_str = tostring(math.floor(w)) .. "x" .. tostring(math.floor(h))
		magick.thumb(originalFile, size_str , ratioFile)
	end
		

end

function outputWebp(originalFile,commandExe)
	 
	local newFile = originalFile .. ".converted.webp"
	local headers = ngx.req.get_headers()
	if headers ~= nil and headers["accept"] ~= nil and string.find(headers["accept"], "image/webp") ~= nil then
		if not tryServeFile(newFile, "image/webp") then
			 os.execute(commandExe .. " -q 80 " .. originalFile .. " -o " .. newFile);
			 serveFileOr404(originalFile, "image/webp")
		end
	elseif image_process ~= nil and string.find(image_process, "webp") ~= nil then
		if not tryServeFile(newFile, "image/webp") then
			 os.execute(commandExe .. " -q 80 " .. originalFile .. " -o " .. newFile);
			 serveFileOr404(originalFile, "image/webp")
		end
	else
		serveFileOr404(originalFile, "")
	end

end

function zipAndWebp(originalFile,commandExe)

	
	
	--ngx.header["Content-Type"] = "text/html; charset=UTF-8"
    --ngx.say("imgp ",image_process,string.find(image_process, "resize")," 比例 ",number)
    local ratio_num = nil
    if image_process ~= nil and string.find(image_process, "resize") ~= nil then
		ratio_num = string.match(image_process, "%d+")
    end
   
	-- ngx.say("imgp ",ratio_num)
	 
	-- 是否要压缩
	if  ratio_num ~= nil and tonumber(ratio_num) > 0 then
		local ratioFile = originalFile .. ratio_num
		ratioZip(originalFile,ratioFile) 
		outputWebp(ratioFile,commandExe)
	else
		outputWebp(originalFile,commandExe)
	end
	
	
	
	
end

 
if string.find(originalFile, ".png") ~= nil then
   
   zipAndWebp(originalFile,"cwebp")
elseif string.find(originalFile, ".jpg") ~= nil then
	 zipAndWebp(originalFile,"cwebp")
elseif string.find(originalFile, ".jpeg") ~= nil then
	 zipAndWebp(originalFile,"cwebp")
elseif string.find(originalFile, ".gif") ~= nil then
	 outputWebp(originalFile,"gif2webp")
else 
	serveFileOr404(originalFile, "")
end

  • 参数格式
?image_process=format,webp/resize,p_20

参考

  • https://blog.rexskz.info/use-openresty-to-optimize-image-size-with-avif-and-webp.html
  • https://blog.csdn.net/F_angT/article/details/90073211
  • https://www.jianshu.com/p/b14c89b57493

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1630752.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

C语言之详细讲解文件操作

什么是文件 与普通文件载体不同,文件是以硬盘为载体存储在计算机上的信息集合,文件可以是文本文档、图片、程序等等。文件通常具有点三个字母的文件扩展名,用于指示文件类型(例如,图片文件常常以KPEG格式保存并且文件…

idea创建完项目如何隐藏不重要的文件

如果您不打算直接使用这些脚本,而是更倾向于通过IDEA的内置工具来运行Maven命令,那么您可以选择隐藏这些文件。但是,隐藏这些文件并不会影响它们的功能,只是在项目视图中不再显示它们。 1.转到 File > Settings(Wi…

信息系统项目管理师——第7章项目立项管理

本章考选择题2-3分,案例和论文均有可能作为领域考试。 项目建议与立项申请♥♥♥♥♥ 立项申请的概念 立项申请又称为项目建议书,是项目建设单位向上级主管部门提交项目申请时所必须的文 件,是该项目建设筹建单位根据国民经济的发展、国家…

Spark高可用模式和Spark分布式Yarn环境安装

Spark分布式HA环境安装 图-12 高可用模式原理 因为在目前情况下,集群中只有一个Master,如果master挂掉,便无法对外提供新的服务,显然有单点故障问题,解决方法就是master的ha。 有两种方式解决单点故障,一…

无脑入单向无头链表的实现| ArrayList和LinkedList的区别

1. ArrayList的缺陷 上节课已经熟悉了ArrayList的使用,并且进行了简单模拟实现。通过源码知道,ArrayList底层使用数组来存储元素。 由于其底层是一段连续空间,当 在 ArrayList 任意位置插入或者删除元素时,就需要将后序元素整体往…

如何使用docker部署前端项目

账号:root 密码:*** 主机:ip地址 登录后: 初级名词: sudo 是Linux和类Unix操作系统中的一个命令,全称为“super user do”,用于允许普通用户以超级用户(root)的身份执行某些或全部命令 需要下…

【python】简单实现遍历文件夹和子文件夹重命名

个人简介 👨🏻‍💻个人主页:九黎aj 🏃🏻‍♂️幸福源自奋斗,平凡造就不凡 🌟如果文章对你有用,麻烦关注点赞收藏走一波,感谢支持! 🌱欢迎订阅我的…

sql注入漏洞及其sqlmap工具的使用

一、sql注入的原理 sql注入概念: sql注入主要是将sql语句,插入到web表单提交或者输入域名或者页面请求的查询字符串,最 终 达到一个欺骗服务器执行sql语句的效果。 sql注入的原理:主要分为平台层注入和代码层注入两种原因 …

TechTool Pro for mac中文激活版:硬件监测和系统维护工具

TechTool Pro mac帮助用户实现系统硬件监测(CPU、内存、硬盘、网络、USB等)、内存测试、S.M.A.R.T检测、磁盘宗卷扫描、宗卷重建和优化、数据恢复和粉碎等等,定期使用,可以确保您的Mac保持优化和无故障。 TechTool Pro for mac v1…

(学习日记)2024.04.19:UCOSIII第四十七节:各文件夹功能介绍

之前的章节都是针对某个或某些知识点进行的专项讲解,重点在功能和代码解释。 回到最初开始学μC/OS-III系统时,当时就定下了一个目标,不仅要读懂,还要读透,改造成更适合中国宝宝体质的使用方式。在学完野火的教程后&a…

JavaScript操作DOM实现页面元素更改

DOM是什么 DOM(文档对象模型)是一种用于表示和操作HTML、XML文档的标准编程接口。它将文档中的每个元素、属性、文本和事件都表示为对象,从而可以使用JavaScript等脚本语言来操作和修改文档的结构、样式和内容。 DOM 将文档表示为一个树状结…

AI绘画的算法原理:从生成模型到Diffusion

近年来,AI绘画技术引起了广泛关注,让我们深入探讨其背后的技术原理和发展历程。本文将以通俗易懂的方式,介绍AI绘画的核心算法,从生成模型到Diffusion。 1. 计算机如何生成图画? AI绘画的核心在于生成模型&#xff08…

【平台开发】MTK6833 实现lk下CQE接口移植 - cmdq request

1.函数调用图 对应协议上结构为: 2.函数拆解 cmdq_request: 1)配置task_desc和tran_desc参数 2)EN_CQHCI_IRQ 3)write CQTDBR cmdq_prep_task_desc: 设置task_desc参数 cmdq_set_tran_desc: 设置tran_desc参数

Elasticsearch下载

1 最新版下载地址 Download Elasticsearch | Elastic https://www.elastic.co/cn/downloads/elasticsearch 2 其他版本下载地址 https://www.elastic.co/cn/downloads/past-releases#elasticsearch 7.9.2:https://artifacts.elastic.co/downloads/elasticsearch/elasticsear…

github two-factor authentication是个啥?

最近在逛github时,总是时不时会弹出一下界面,很烦 看到红框里的文字,这明显是强制要求做这个认证,如果不认证4天后账号将不可访问,所以今天花点时间看看怎么做这个认证,点“Enable 2FA now”进入这个界面&a…

LVGL移植

Lvgl介绍 LVGL是一个开源的图形库,专为嵌入式系统设计。它提供了丰富的图形元素和功能,可以帮助开发者快速构建现代化的用户界面。LVGL具有跨平台的特性,支持多种操作系统和硬件平台,包括ARM Cortex-M,ESP32&#xff…

【Protobuf】protobuf详细介绍

protobuf详细介绍 一、前言二、Protobuf简介2.1、核心思想2.2、Protobuf是如何工作的?2.3、如何使用 Protoc 生成代码?2.4 入门命令 一、前言 在以往的项目中进行网络通信和数据交换的应用场景中,最经常使用的技术便是json或xml。随着JSON的…

flac转wav怎么转?4种简单又快速的方法~

FLAC(Free Lossless Audio Codec)是一种无损音频编解码器,它可以将音频压缩成较小的文件大小而不损失任何音频质量。因此,将FLAC文件转换为WAV(Waveform Audio File Format)格式不会损失音频质量&#xff0…

Coursera: An Introduction to American Law 学习笔记 Week 02: Contract Law

An Introduction to American Law 本文是 https://www.coursera.org/programs/career-training-for-nevadans-k7yhc/learn/american-law 这门课的学习笔记。 文章目录 An Introduction to American LawInstructors Week 02: Contract LawKey Contract Law TermsSupplemental Re…

谷歌个人号秒过审,他都做了什么?“20+14”封测怎么解决?

近日,有开发者分享称自己在使用谷歌个人号提交正式版应用时秒过审。在目前谷歌上架市场如此严峻的形势下,“秒过审”,这是多么小众的词汇! 相信大家都清楚,谷歌的审核系统正变得越来越智能和严格,这无疑加大…