Nginx代理输出缩放图片的方法
本文实例为大家分享了Nginx代理输出缩放图片的具体代码,供大家参考,具体内容如下
nginx配置文件:
#documentpptconvertConfiguration.
upstreamdocument.polyv.net{
server127.0.0.1:8080;
}
server{
listen80;
server_namedocument.polyv.net;
indexindex.htmlindex.htm;
charsetutf-8;
client_max_body_size1000m;
#ignorefavicon.iconotexist.
location=/favicon.ico{
log_not_foundoff;
access_logoff;
}
#notallowtovisithiddenfiles.
location~/\.{
denyall;
access_logoff;
log_not_foundoff;
}
location/{
if($request_filename~*^.*?\.(txt|doc|pdf|rar|gz|zip|docx|exe|xlsx|ppt|pptx)$){
add_headerContent-Disposition:'attachment;';
add_headerContent-Type:'APPLICATION/OCTET-STREAM';
}
proxy_passhttp://document.polyv.net;
proxy_set_headerX-Real-IP$remote_addr;
proxy_set_headerX-Forwarded-For$proxy_add_x_forwarded_for;
proxy_set_headerREQUEST_HOST$host;
#includeproxy.conf;
charsetUTF-8;
}
#useruploadfiles
location/images/{
#expires7d;
alias/data03/ovp/blobs/;
proxy_storeon;
proxy_store_accessuser:rwgroup:rwall:rw;
proxy_set_headerAccept-Encoding"";
if(!-f$request_filename){
proxy_passhttp://document.polyv.net;
}
}
location/blobs/{
#expires7d;
alias/data03/ovp/blobs/;
}
location/preview/images/{
#expires7d;
alias/data03/ovp/blobs/;
proxy_storeon;
proxy_store_accessuser:rwgroup:rwall:rw;
proxy_set_headerAccept-Encoding"";
if(!-f$request_filename){
proxy_passhttp://document.polyv.net;
}
}
}
代理输出缩放图片
packagecom.document.handle.controller;
importjava.io.BufferedInputStream;
importjava.io.File;
importjava.io.IOException;
importjava.io.OutputStream;
importjava.net.HttpURLConnection;
importjava.net.URL;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.commons.lang3.StringUtils;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.ServletRequestUtils;
importorg.springframework.web.bind.annotation.PathVariable;
importorg.springframework.web.bind.annotation.RequestMapping;
importcom.document.tool.ImageMagickUtils;
importcom.document.tool.SystemConfig;
@Controller
publicclassImageAgentController{
privatestaticfinalLoggerLOG=LoggerFactory.getLogger(ImageAgentController.class);
/**
*ppt预览图片代理输出
*@throwsIOException
*/
@RequestMapping("/preview/images/{year}/{month}/{md5id}/{preview}/{filename}.{ext}")
publicvoidcropImage(@PathVariableStringyear,@PathVariableStringmonth,@PathVariableStringmd5id,
@PathVariableStringpreview,@PathVariableStringfilename,@PathVariableStringext,
HttpServletRequestrequest,HttpServletResponseresponse)throwsIOException{
//StringrootDir="/data03/ovp/blobs/";
StringrootDir=SystemConfig.getBlobDirectory();
Stringoname=filename.substring(1,filename.length());//原图文件名
StringdirString=rootDir+year+"/"+month+"/"+md5id+"/"+oname+"."+ext;
StringtargetFileString=rootDir+year+"/"+month+"/"+md5id+"/preview/"+filename+"."+ext;
//如果原图存在
FileoriginImage=newFile(oname);
if(originImage.exists()){
LOG.info("corpImage..."+dirString+"->"+targetFileString);
Filenewfile=newFile(targetFileString);
StringpathString=newfile.getParent();
LOG.info("pathString...{}{}",pathString);
FilepathFile=newFile(pathString);
if(!pathFile.exists()){
LOG.info("---createfile---");
pathFile.mkdirs();
}
booleanstatus=ImageMagickUtils.scale(dirString,targetFileString,240,180);
if(status){
response.reset();
response.setContentType("image/"+ext);
java.io.InputStreamin=newjava.io.FileInputStream(targetFileString);
//FilenameUrlUtils.getImageFilename(targetFileString);
if(in!=null){
byte[]b=newbyte[1024];
intlen;
while((len=in.read(b))!=-1){
response.getOutputStream().write(b);
}
in.close();
}
}
}else{
LOG.info("原图目录不存在-preview:{}",dirString);
}
}
/**
*ppt固定尺寸图片代理输出
*@throwsIOException
*http://document.polyv.net/images/2016/03/de37d2ceb11ac068c18c5e4428541075/jpg-3/1000x540.png
*
*http://document.polyv.net/images/2016/03/de37d2ceb11ac068c18c5e4428541075/jpg-3.png
*/
@RequestMapping("/images/{year}/{month}/{md5id}/{filename}/{width}x{height}.{ext}")
publicvoidcropfixedImage(@PathVariableStringyear,@PathVariableStringmonth,@PathVariableStringmd5id,
@PathVariableStringfilename,@PathVariableIntegerwidth,@PathVariableIntegerheight,@PathVariableStringext,
HttpServletRequestrequest,HttpServletResponseresponse)throwsIOException{
//StringrootDir="/data03/ovp/blobs/";
StringrootDir=SystemConfig.getBlobDirectory();
//Stringoname=filename.substring(1,filename.length());//原图文件名
StringdirString=rootDir+year+"/"+month+"/"+md5id+"/"+(filename+"."+ext);
StringtargetFileString=rootDir+year+"/"+month+"/"+md5id+"/"+filename+"/"+(width+"x"+height+"."+ext);
//如果原图存在
FileoriginImage=newFile(dirString);
if(originImage.exists()){
FiletargetFileStringFile=newFile(targetFileString);
if(!targetFileStringFile.exists()){
LOG.info("corpImage..."+dirString+"->"+targetFileString);
Filenewfile=newFile(targetFileString);
StringpathString=newfile.getParent();
LOG.info("pathString...{}{}",pathString);
FilepathFile=newFile(pathString);
if(!pathFile.exists()){
LOG.info("---createfile---");
pathFile.mkdirs();
}
ImageMagickUtils.resizeWH(dirString,targetFileString,width,height);
}
response.setContentType("image/"+ext);
java.io.InputStreamin=null;
try{
in=newjava.io.FileInputStream(targetFileString);
response.setContentLength(in.available());
byte[]buffer=newbyte[1024];
intcount=0;
while((count=in.read(buffer))>0){
response.getOutputStream().write(buffer,0,count);
}
response.flushBuffer();
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
in.close();
}catch(Exceptione){
}
}
}else{
LOG.info("原图目录不存在:{}",dirString);
}
}
/**
*图片下载
*/
@RequestMapping("get/image/data")
publicvoiddownloadImage(HttpServletRequestrequest,HttpServletResponseresponse)throwsIOException{
StringfilePath=ServletRequestUtils.getStringParameter(request,"filePath","");//图片访问路劲
StringfileName=ServletRequestUtils.getStringParameter(request,"fileName","");//名称
if(StringUtils.isNotBlank(filePath)||StringUtils.isNotBlank(fileName)){
StringdestUrl=filePath;
//LOG.info("--------------"+filePath);
StringfileFormat=filePath.substring(filePath.lastIndexOf("."));
//Stringname=fileName.trim()+fileFormat;
Stringname=filePath.substring(filePath.lastIndexOf("/")+1,filePath.length());
//Filef=newFile(filePath);
//response.setHeader("Content-Disposition","attachment;filename="+java.net.URLEncoder.encode(f.getName(),"UTF-8"));
//LOG.info("--------------"+f.getName());
//建立链接
URLurl=newURL(destUrl);
HttpURLConnectionhttpUrl=(HttpURLConnection)url.openConnection();
//连接指定的资源
httpUrl.connect();
//获取网络输入流
BufferedInputStreambis=newBufferedInputStream(httpUrl.getInputStream());
Integerlenf=httpUrl.getContentLength();
//Stringlenf=this.getFileLength(4189053,7189053);
response.setContentType("application/x-msdownload");
response.setHeader("Content-Length",lenf.toString());//文件大小值5几M
response.setHeader("Content-Disposition","attachment;filename="+java.net.URLEncoder.encode(name,"UTF-8"));
OutputStreamout=response.getOutputStream();
byte[]buf=newbyte[1024];
if(destUrl!=null){
BufferedInputStreambr=bis;
intlen=0;
while((len=br.read(buf))>0){
out.write(buf,0,len);
}
br.close();
}
out.flush();
out.close();
}
}
}
图片缩放的业务
packagecom.document.tool;
importjava.io.IOException;
importjavax.swing.ImageIcon;
importorg.apache.commons.exec.CommandLine;
importorg.apache.commons.exec.DefaultExecuteResultHandler;
importorg.apache.commons.exec.DefaultExecutor;
importorg.apache.commons.exec.ExecuteException;
importorg.apache.commons.exec.ExecuteWatchdog;
importorg.apache.commons.exec.Executor;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
/**
*使用ImageMagick对图片文件进行处理的工具类。
*@authorXingNingOU
*/
publicabstractclassImageMagickUtils{
privatestaticfinalStringEXECUTABLE_CONVERT="/usr/bin/convert";//convert命令
privatestaticfinalStringEXECUTABLE_COMPOSITE="/usr/bin/composite";//composite命令
privatestaticfinallongEXECUTE_TIMEOUT=30*60*1000L;//30minutes
privatestaticfinalLoggerLOG=LoggerFactory.getLogger(ImageMagickUtils.class);
/**
*执行图片处理的命令。
*@paramcmdLine待执行的命令
*@returnexitValue,一般等于0时表示正常运行结束
*@throwsExecuteException命令执行失败时抛出此异常
*@throwsIOException当发生IO错误时抛出此异常
*@throwsInterruptedException当等待异步返回结果被中断时抛出此异常
*/
publicstaticintexecuteCommandLine(CommandLinecmdLine)throwsExecuteException,IOException,
InterruptedException{
Executorexecutor=newDefaultExecutor();
executor.setExitValue(0);
//Killarun-awayprocessafterEXECUTE_TIMEmilliseconds.
ExecuteWatchdogwatchdog=newExecuteWatchdog(EXECUTE_TIMEOUT);
executor.setWatchdog(watchdog);
//Executetheprintjobasynchronously.
DefaultExecuteResultHandlerresultHandler=newDefaultExecuteResultHandler();
executor.execute(cmdLine,resultHandler);
//Sometimelatertheresulthandlercallbackwasinvoked.
resultHandler.waitFor();
//Sowecansafelyrequesttheexitvalue.
returnresultHandler.getExitValue();
}
/**
*按照高宽比例缩小图片。
*@paramsrc源图片
*@paramdst目标图片
*@paramwidth图片图片的宽度
*@paramheight目标图片的高度
*@return是否处理成功
*/
publicstaticbooleanscale(Stringsrc,Stringdst,intwidth,intheight){
//构建命令
CommandLinecmdLine=newCommandLine(EXECUTABLE_CONVERT);
cmdLine.addArgument(src);
cmdLine.addArgument("-scale");
cmdLine.addArgument(width+"x"+height);
cmdLine.addArgument(dst);
try{
executeCommandLine(cmdLine);
returntrue;
}catch(Exceptione){
LOG.error("缩略图片时发生异常,Cause:",e);
returnfalse;
}
}
/**
*按照高宽比例缩小图片。
*@paramsrc源图片
*@paramdst目标图片
*@paramwidth图片图片的宽度
*@paramheight目标图片的高度
*@return是否处理成功
*/
publicstaticbooleanthumbnail(Stringsrc,Stringdst,intwidth,intheight){
//构建命令
CommandLinecmdLine=newCommandLine(EXECUTABLE_CONVERT);
cmdLine.addArgument(src);
cmdLine.addArgument("-thumbnail");
cmdLine.addArgument(width+"x"+height);
cmdLine.addArgument(dst);
try{
executeCommandLine(cmdLine);
returntrue;
}catch(Exceptione){
LOG.error("缩略图片时发生异常,Cause:",e);
returnfalse;
}
}
/**
*添加图片水印。
*@paramsrc源图片
*@paramdst目标图片
*@paramlogofile水印图片
*@paramdissolve和水印的融合度,0-100的数字
*@paramgravity叠放方向,East,West,North,South,NorthEast,NorthWest,SouthEast,SouthWest
*@return是否处理成功
*/
publicstaticbooleandrawLogo(Stringsrc,Stringdst,Stringlogofile,intdissolve,Stringgravity){
//构建命令
CommandLinecmdLine=newCommandLine(EXECUTABLE_COMPOSITE);
cmdLine.addArgument("-dissolve");
cmdLine.addArgument(dissolve+"%");
cmdLine.addArgument("-gravity");
cmdLine.addArgument(gravity);
cmdLine.addArgument(logofile);
cmdLine.addArgument(src);
cmdLine.addArgument(dst);
try{
executeCommandLine(cmdLine);
returntrue;
}catch(Exceptione){
LOG.error("添加图片水印时发生异常,Cause:",e);
returnfalse;
}
}
/**
*添加图片水印。
*@paramsrc源图片
*@paramdst目标图片
*@paramlogofile水印图片
*@paramdissolve和水印的融合度,0-100的数字
*@paramx水印距离左下角的距离
*@paramy水印距离右下角的距离
*@return是否处理成功
*/
publicstaticbooleandrawLogo(Stringsrc,Stringdst,Stringlogofile,intdissolve,intx,inty){
ImageIconicon=newImageIcon(src);
intwidth=icon.getIconWidth();//源图的宽
intheight=icon.getIconHeight();//源图的高
String_x=String.valueOf(width-x);//在x轴上水印图片的左上顶点距离图片左上角的距离
String_y=String.valueOf(height-y);//在y轴上水印图片的左上顶点距离图片左上角的距离
//构建命令
CommandLinecmdLine=newCommandLine(EXECUTABLE_COMPOSITE);
cmdLine.addArgument("-dissolve");
cmdLine.addArgument(dissolve+"%");
cmdLine.addArgument("-geometry");
cmdLine.addArgument(_x+"+"+_y);
cmdLine.addArgument(logofile);
cmdLine.addArgument(src);
cmdLine.addArgument(dst);
try{
executeCommandLine(cmdLine);
returntrue;
}catch(Exceptione){
LOG.error("添加图片水印时发生异常,Cause:",e);
returnfalse;
}
}
/**
*裁剪图片。
*@paramsrc源图片
*@paramdst目标图片
*@paramwidth目标宽度
*@paramheight目标高度
*@paramleft裁剪位置:距离左边的像素
*@paramtop裁剪位置:距离上边的像素
*@return是否处理成功
*/
publicstaticbooleancrop(Stringsrc,Stringdst,intwidth,intheight,intleft,inttop){
//构建命令
CommandLinecmdLine=newCommandLine(EXECUTABLE_CONVERT);
cmdLine.addArgument(src);
cmdLine.addArgument("-crop");
cmdLine.addArgument(width+"x"+height+"+"+left+"+"+top);
cmdLine.addArgument(dst);
try{
executeCommandLine(cmdLine);
returntrue;
}catch(Exceptione){
LOG.error("裁剪图片时发生异常,Cause:",e);
returnfalse;
}
}
/**
*获取矩形的小图。
*@paramsrc源图片
*@paramdst目标图片
*@paramwidth目标宽度
*@paramheight目标高度
*@paramleft裁剪位置:距离左边的像素
*@paramtop裁剪位置:距离上边的像素
*@return是否处理成功
*/
publicstaticbooleancropRect(Stringsrc,Stringdst,intwidth,intheight,intleft,inttop){
ImageIconicon=newImageIcon(src);
intorigWidth=icon.getIconWidth();
intorigHeight=icon.getIconHeight();
int[]s=newint[2];
if(origWidthscale){
width=height*scale;
}elseif((width/height)
服务器上要安装imagemagick。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。