搜尋
首頁運維NginxNginx代理輸出縮放圖片怎麼實現

nginx 設定檔:

# document ppt convert configuration.
upstream document.polyv.net {
 server 127.0.0.1:8080;
}

server {
 listen 80;
 server_name document.polyv.net;
 index index.html index.htm;
 charset utf-8;
 client_max_body_size 1000m;

 # ignore favicon.ico not exist.
 location = /favicon.ico {
  log_not_found off;
  access_log off;
 }

 # not allow to visit hidden files.
 location ~ /\. {
  deny all;
  access_log off;
  log_not_found off;
 }

 location / {
  if ($request_filename ~* ^.*?\.(txt|doc|pdf|rar|gz|zip|docx|exe|xlsx|ppt|pptx)$) {
   add_header content-disposition: 'attachment;';
   add_header content-type: 'application/octet-stream';
  }

  proxy_pass http://document.polyv.net;
  proxy_set_header x-real-ip $remote_addr;
  proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for;
  proxy_set_header request_host $host;

  # include proxy.conf;
  charset utf-8;
 }

 # user upload files
 location /images/ {
   #expires 7d;
  alias /data03/ovp/blobs/;
   proxy_store on;
   proxy_store_access user:rw group:rw all:rw;
   proxy_set_header accept-encoding "";
   if ( !-f $request_filename ) {
    proxy_pass http://document.polyv.net;
   }
 }

 location /blobs/ {
   #expires 7d;
  alias /data03/ovp/blobs/;
 }

  location /preview/images/ {
   #expires 7d;
   alias /data03/ovp/blobs/;
   proxy_store on;
   proxy_store_access user:rw group:rw all:rw;
   proxy_set_header accept-encoding "";
   if ( !-f $request_filename ) {
    proxy_pass http://document.polyv.net;
   }
  }

}

代理程式輸出縮放圖片

r​​rreee

圖片縮放的業務

package com.document.handle.controller;

import java.io.bufferedinputstream;
import java.io.file;
import java.io.ioexception;
import java.io.outputstream;
import java.net.httpurlconnection;
import java.net.url;

import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

import org.apache.commons.lang3.stringutils;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.servletrequestutils;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.requestmapping;

import com.document.tool.imagemagickutils;
import com.document.tool.systemconfig;

@controller
public class imageagentcontroller {

 private static final logger log = loggerfactory.getlogger(imageagentcontroller.class);

 /**
  * ppt预览图片代理输出
  * @throws ioexception
  */
 @requestmapping("/preview/images/{year}/{month}/{md5id}/{preview}/{filename}.{ext}")
 public void cropimage(@pathvariable string year, @pathvariable string month, @pathvariable string md5id,
   @pathvariable string preview, @pathvariable string filename, @pathvariable string ext,
   httpservletrequest request, httpservletresponse response) throws ioexception {
  // string rootdir = "/data03/ovp/blobs/";
  string rootdir = systemconfig.getblobdirectory();
  string oname = filename.substring(1, filename.length());// 原图文件名
  string dirstring = rootdir + year + "/" + month + "/" + md5id + "/" + oname + "." + ext;
  string targetfilestring = rootdir + year + "/" + month + "/" + md5id + "/preview/" + filename + "." + ext;

  //如果原图存在
  file originimage = new file(oname);
  if(originimage.exists()){
   log.info("corpimage..." + dirstring + " -> " + targetfilestring);
   file newfile = new file(targetfilestring);
   string pathstring = newfile.getparent();
   log.info("pathstring...{} {}", pathstring);
   file pathfile = new file(pathstring);
   if (!pathfile.exists()) {
    log.info("---create file---");
    pathfile.mkdirs();
   }
   boolean status = imagemagickutils.scale(dirstring, targetfilestring, 240, 180);
   if (status) {
    response.reset();
    response.setcontenttype("image/" + ext);

    java.io.inputstream in = new java.io.fileinputstream(targetfilestring);
    // filenameurlutils.getimagefilename(targetfilestring);

    if (in != null) {
     byte[] b = new byte[1024];
     int len;
     while ((len = in.read(b)) != -1) {
      response.getoutputstream().write(b);
     }

     in.close();
    }
   }
  }else{
   log.info("原图目录不存在-preview:{}",dirstring); 
  }
 }


 /**
  * ppt固定尺寸图片代理输出
  * @throws ioexception
  * https://cache.yisu.com/upload/ask_collection/20210726/113/19154.png
  *
  * http://document.polyv.net/images/2016/03/de37d2ceb11ac068c18c5e4428541075/jpg-3.png
  */
 @requestmapping("/images/{year}/{month}/{md5id}/{filename}/{width}x{height}.{ext}")
 public void cropfixedimage(@pathvariable string year, @pathvariable string month, @pathvariable string md5id,
   @pathvariable string filename, @pathvariable integer width, @pathvariable integer height, @pathvariable string ext,
   httpservletrequest request, httpservletresponse response) throws ioexception {
  // string rootdir = "/data03/ovp/blobs/";
  string rootdir = systemconfig.getblobdirectory();
  //string oname = filename.substring(1, filename.length());// 原图文件名
  string dirstring = rootdir + year + "/" + month + "/" + md5id + "/" + ( filename + "." + ext);
  string targetfilestring = rootdir + year + "/" + month + "/" + md5id + "/" + filename + "/" + (width + "x" + height + "." + ext);

  //如果原图存在
  file originimage = new file(dirstring);
  if(originimage.exists()){
   file targetfilestringfile = new file(targetfilestring);
   if(!targetfilestringfile.exists()){
    log.info("corpimage..." + dirstring + " -> " + targetfilestring);
    file newfile = new file(targetfilestring);
    string pathstring = newfile.getparent();
    log.info("pathstring...{} {}", pathstring);
    file pathfile = new file(pathstring);
    if (!pathfile.exists()) {
     log.info("---create file---");
     pathfile.mkdirs();
    }
    imagemagickutils.resizewh(dirstring, targetfilestring,width,height);
   }
   response.setcontenttype("image/" + ext);
   java.io.inputstream in = null;
   try{
    in = new java.io.fileinputstream(targetfilestring);
    response.setcontentlength(in.available());
    byte[] buffer = new byte[1024];
    int count = 0;
    while ((count = in.read(buffer)) > 0) {
     response.getoutputstream().write(buffer, 0, count);
    }
    response.flushbuffer();
   }catch(exception e){
    e.printstacktrace();
   }finally {
    try {
     in.close();
    } catch (exception e) {

    }
   }
  }else{
   log.info("原图目录不存在:{}",dirstring);
  }




 }


 /**
  * 图片下载
  */
 @requestmapping("get/image/data")
 public void downloadimage(httpservletrequest request, httpservletresponse response) throws ioexception { 
  string filepath = servletrequestutils.getstringparameter(request, "filepath", ""); //图片访问路劲
  string filename = servletrequestutils.getstringparameter(request, "filename", ""); //名称

  if(stringutils.isnotblank(filepath) || stringutils.isnotblank(filename)){
   string desturl = filepath;
   //log.info("--------------"+filepath); 
   string fileformat=filepath.substring(filepath.lastindexof("."));
   //string name=filename.trim()+fileformat;
   string name=filepath.substring(filepath.lastindexof("/")+1, filepath.length()); 
   //file f = new file(filepath);
   //response.setheader("content-disposition", "attachment; filename="+java.net.urlencoder.encode(f.getname(),"utf-8")); 
   //log.info("--------------"+f.getname());

   // 建立链接 
   url url = new url(desturl); 
   httpurlconnection httpurl = (httpurlconnection) url.openconnection(); 
   // 连接指定的资源 
   httpurl.connect(); 
   // 获取网络输入流 
   bufferedinputstream bis = new bufferedinputstream(httpurl.getinputstream()); 

   integer lenf=httpurl.getcontentlength();
   //string lenf=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"));
   outputstream out = response.getoutputstream();
   byte[] buf = new byte[1024]; 
   if (desturl != null) { 
    bufferedinputstream br = bis; 
    int len = 0; 
    while ((len = br.read(buf)) > 0){ 
     out.write(buf, 0, len); 
    }     
    br.close(); 
   } 
   out.flush(); 
   out.close(); 
  }

 } 

}

伺服器上要安裝imagemagick。

以上是Nginx代理輸出縮放圖片怎麼實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:亿速云。如有侵權,請聯絡admin@php.cn刪除
NGINX單元與其他應用程序服務器NGINX單元與其他應用程序服務器Apr 24, 2025 am 12:14 AM

NGINXUnit優於ApacheTomcat、Gunicorn和Node.js內置HTTP服務器,適用於多語言項目和動態配置需求。 1)支持多種編程語言,2)提供動態配置重載,3)內置負載均衡功能,適合需要高擴展性和可靠性的項目。

NGINX單元:架構及其工作原理NGINX單元:架構及其工作原理Apr 23, 2025 am 12:18 AM

NGINXUnit通過其模塊化架構和動態重配置功能提高了應用的性能和可管理性。 1)模塊化設計包括主控進程、路由器和應用進程,支持高效管理和擴展。 2)動態重配置允許在運行時無縫更新配置,適用於CI/CD環境。 3)多語言支持通過動態加載語言運行時實現,提升了開發靈活性。 4)高性能通過事件驅動模型和異步I/O實現,即使在高並發下也保持高效。 5)安全性通過隔離應用進程提高,減少應用間相互影響。

使用NGINX單元:部署和管理應用程序使用NGINX單元:部署和管理應用程序Apr 22, 2025 am 12:06 AM

NGINXUnit可用於部署和管理多種語言的應用。 1)安裝NGINXUnit。 2)配置它以運行不同類型的應用,如Python和PHP。 3)利用其動態配置功能進行應用管理。通過這些步驟,你可以高效地部署和管理應用,提升項目效率。

NGINX與Apache:Web服務器的比較分析NGINX與Apache:Web服務器的比較分析Apr 21, 2025 am 12:08 AM

NGINX更适合处理高并发连接,而Apache更适合需要复杂配置和模块扩展的场景。1.NGINX以高性能和低资源消耗著称,适合高并发。2.Apache以稳定性和丰富的模块扩展闻名,适合复杂配置需求。

NGINX單元的優勢:靈活性和性能NGINX單元的優勢:靈活性和性能Apr 20, 2025 am 12:07 AM

NGINXUnit通過其動態配置和高性能架構提升應用的靈活性和性能。 1.動態配置允許在不重啟服務器的情況下調整應用配置。 2.高性能體現在事件驅動和非阻塞架構以及多進程模型上,能夠高效處理並發連接和利用多核CPU。

NGINX與Apache:性能,可伸縮性和效率NGINX與Apache:性能,可伸縮性和效率Apr 19, 2025 am 12:05 AM

NGINX和Apache都是強大的Web服務器,各自在性能、可擴展性和效率上有獨特的優勢和不足。 1)NGINX在處理靜態內容和反向代理時表現出色,適合高並發場景。 2)Apache在處理動態內容時表現更好,適合需要豐富模塊支持的項目。選擇服務器應根據項目需求和場景來決定。

終極攤牌:nginx vs. apache終極攤牌:nginx vs. apacheApr 18, 2025 am 12:02 AM

NGINX適合處理高並發請求,Apache適合需要復雜配置和功能擴展的場景。 1.NGINX採用事件驅動、非阻塞架構,適用於高並發環境。 2.Apache採用進程或線程模型,提供豐富的模塊生態系統,適合複雜配置需求。

nginx行動:示例和現實應用程序nginx行動:示例和現實應用程序Apr 17, 2025 am 12:18 AM

NGINX可用於提升網站性能、安全性和可擴展性。 1)作為反向代理和負載均衡器,NGINX可優化後端服務和分擔流量。 2)通過事件驅動和異步架構,NGINX高效處理高並發連接。 3)配置文件允許靈活定義規則,如靜態文件服務和負載均衡。 4)優化建議包括啟用Gzip壓縮、使用緩存和調整worker進程。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)