The Nginx agent outputs the method to scale the image
- 2020-05-17 07:41:01
- OfStack
The example of this article for you to share the Nginx agent output zoom image specific code, for your reference, the specific content is as follows
nginx profile:
# 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;
}
}
}
The agent outputs the zoom image
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 Preview image proxy output
* @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());// Original file name
String dirString = rootDir + year + "/" + month + "/" + md5id + "/" + oname + "." + ext;
String targetFileString = rootDir + year + "/" + month + "/" + md5id + "/preview/" + filename + "." + ext;
// If the original exists
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(" The original image directory does not exist -preview : {}",dirString);
}
}
/**
* ppt Fixed size picture agent output
* @throws IOException
* 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}")
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());// Original file name
String dirString = rootDir + year + "/" + month + "/" + md5id + "/" + ( filename + "." + ext);
String targetFileString = rootDir + year + "/" + month + "/" + md5id + "/" + filename + "/" + (width + "x" + height + "." + ext);
// If the original exists
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(" The original directory does not exist: {}",dirString);
}
}
/**
* Images are downloaded
*/
@RequestMapping("get/image/data")
public void downloadImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
String filePath = ServletRequestUtils.getStringParameter(request, "filePath", ""); // Picture visit lu jin
String fileName = ServletRequestUtils.getStringParameter(request, "fileName", ""); // The name of the
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());
// Link building
URL url = new URL(destUrl);
HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
// Connect to the specified resource
httpUrl.connect();
// Gets the network input stream
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());// File size value 5 A few 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();
}
}
}
Image zooming business
package com.document.tool;
import java.io.IOException;
import javax.swing.ImageIcon;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* use ImageMagick A utility class that handles image files.
* @author XingNing OU
*/
public abstract class ImageMagickUtils {
private static final String EXECUTABLE_CONVERT = "/usr/bin/convert"; // convert The command
private static final String EXECUTABLE_COMPOSITE = "/usr/bin/composite"; // composite The command
private static final long EXECUTE_TIMEOUT = 30 * 60 * 1000L; // 30 minutes
private static final Logger LOG = LoggerFactory.getLogger(ImageMagickUtils.class);
/**
* Execute the image processing command.
* @param cmdLine Commands to be executed
* @return exitValue . 1 A is equal to the 0 Is the end of normal operation
* @throws ExecuteException This exception is thrown when the command execution fails
* @throws IOException When a IO An error throws this exception
* @throws InterruptedException This exception is thrown when waiting for the asynchronous return result to be interrupted
*/
public static int executeCommandLine(CommandLine cmdLine) throws ExecuteException, IOException,
InterruptedException {
Executor executor = new DefaultExecutor();
executor.setExitValue(0);
// Kill a run-away process after EXECUTE_TIME milliseconds.
ExecuteWatchdog watchdog = new ExecuteWatchdog(EXECUTE_TIMEOUT);
executor.setWatchdog(watchdog);
// Execute the print job asynchronously.
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
executor.execute(cmdLine, resultHandler);
// Some time later the result handler callback was invoked.
resultHandler.waitFor();
// So we can safely request the exit value.
return resultHandler.getExitValue();
}
/**
* Scale the image in proportion to height and width.
* @param src The source image
* @param dst The target image
* @param width Picture the width of the picture
* @param height The height of the target image
* @return Whether the processing is successful or not
*/
public static boolean scale(String src, String dst, int width, int height) {
// Build commands
CommandLine cmdLine = new CommandLine(EXECUTABLE_CONVERT);
cmdLine.addArgument(src);
cmdLine.addArgument("-scale");
cmdLine.addArgument(width + "x" + height);
cmdLine.addArgument(dst);
try {
executeCommandLine(cmdLine);
return true;
} catch (Exception e) {
LOG.error(" Something is wrong with the thumbnail, Cause: ", e);
return false;
}
}
/**
* Scale the image in proportion to height and width.
* @param src The source image
* @param dst The target image
* @param width Picture the width of the picture
* @param height The height of the target image
* @return Whether the processing is successful or not
*/
public static boolean thumbnail(String src, String dst, int width, int height) {
// Build commands
CommandLine cmdLine = new CommandLine(EXECUTABLE_CONVERT);
cmdLine.addArgument(src);
cmdLine.addArgument("-thumbnail");
cmdLine.addArgument(width + "x" + height);
cmdLine.addArgument(dst);
try {
executeCommandLine(cmdLine);
return true;
} catch (Exception e) {
LOG.error(" Something is wrong with the thumbnail, Cause: ", e);
return false;
}
}
/**
* Add image watermarking.
* @param src The source image
* @param dst The target image
* @param logofile The watermark image
* @param dissolve The degree of fusion with the watermark ,0-100 The number of
* @param gravity Stacked direction ,East,West,North,South,NorthEast,NorthWest,SouthEast,SouthWest
* @return Whether the processing is successful or not
*/
public static boolean drawLogo(String src, String dst, String logofile, int dissolve, String gravity) {
// Build commands
CommandLine cmdLine = new CommandLine(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);
return true;
} catch (Exception e) {
LOG.error(" There is an exception when adding image watermark, Cause: ", e);
return false;
}
}
/**
* Add image watermarking.
* @param src The source image
* @param dst The target image
* @param logofile The watermark image
* @param dissolve The degree of fusion with the watermark ,0-100 The number of
* @param x The distance between the watermark and the lower left corner
* @param y The distance between the watermark and the lower right corner
* @return Whether the processing is successful or not
*/
public static boolean drawLogo(String src, String dst, String logofile, int dissolve, int x, int y) {
ImageIcon icon = new ImageIcon(src);
int width = icon.getIconWidth(); // Figure of wide source
int height = icon.getIconHeight(); // High source map
String _x = String.valueOf(width - x); // in x The distance between the top left vertex of the watermark image on the axis and the top left corner of the image
String _y = String.valueOf(height - y); // in y The distance between the top left vertex of the watermark image on the axis and the top left corner of the image
// Build commands
CommandLine cmdLine = new CommandLine(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);
return true;
} catch (Exception e) {
LOG.error(" There is an exception when adding image watermark, Cause: ", e);
return false;
}
}
/**
* Crop the picture.
* @param src The source image
* @param dst The target image
* @param width The target width
* @param height Target height
* @param left Clipping position: the distance to the left of the pixel
* @param top Clipping position: the distance from the top pixel
* @return Whether the processing is successful or not
*/
public static boolean crop(String src, String dst, int width, int height, int left, int top) {
// Build commands
CommandLine cmdLine = new CommandLine(EXECUTABLE_CONVERT);
cmdLine.addArgument(src);
cmdLine.addArgument("-crop");
cmdLine.addArgument(width + "x" + height + "+" + left + "+" + top);
cmdLine.addArgument(dst);
try {
executeCommandLine(cmdLine);
return true;
} catch (Exception e) {
LOG.error(" Something unusual happened when the picture was cropped. Cause: ", e);
return false;
}
}
/**
* Gets a small picture of the rectangle.
* @param src The source image
* @param dst The target image
* @param width The target width
* @param height Target height
* @param left Clipping position: the distance to the left of the pixel
* @param top Clipping position: the distance from the top pixel
* @return Whether the processing is successful or not
*/
public static boolean cropRect(String src, String dst, int width, int height, int left, int top) {
ImageIcon icon = new ImageIcon(src);
int origWidth = icon.getIconWidth();
int origHeight = icon.getIconHeight();
int[] s = new int[2];
if (origWidth < origHeight) { // Take width as the standard
s = getSize(origWidth, origHeight, width, height, 1);
} else {// High is the standard
s = getSize(origWidth, origHeight, width, height, 2);
}
if (thumbnail(src, dst, s[0], s[1])) {
return crop(src, dst, width, height, left, top);
}
return false;
}
/**
* Add borders.
* @param src The source image
* @param dst The target image
* @param borderWidth Width of border
* @param borderHeight Height of border
* @param borderColor Color of border
* @return Whether the processing is successful or not
*/
public static boolean border(String src, String dst, int borderWidth, int borderHeight, String borderColor) {
// Build commands
CommandLine cmdLine = new CommandLine(EXECUTABLE_CONVERT);
cmdLine.addArgument("-bordercolor");
cmdLine.addArgument(borderColor);
cmdLine.addArgument("-border");
cmdLine.addArgument(borderWidth + "x" + borderHeight);
cmdLine.addArgument(src);
cmdLine.addArgument(dst);
try {
executeCommandLine(cmdLine);
return true;
} catch (Exception e) {
LOG.error(" An exception occurred when the picture border was added, Cause: ", e);
return false;
}
}
/**
* Convert image format.
* @param src The source image
* @param dst The target image
* @param format Conversion format
* @return Whether the processing is successful or not
*/
public static boolean format(String src, String dst, String format) {
// Build commands
CommandLine cmdLine = new CommandLine(EXECUTABLE_CONVERT);
cmdLine.addArgument(src);
cmdLine.addArgument("-format");
cmdLine.addArgument("'" + format + "'");
cmdLine.addArgument(dst);
try {
executeCommandLine(cmdLine);
return true;
} catch (Exception e) {
LOG.error(" An exception occurred when converting the image format, Cause: ", e);
return false;
}
}
/**
* Convert to infinity TIFF The image.
*/
public static boolean convertTiff(String src, String dst) {
// Build commands
CommandLine cmdLine = new CommandLine(EXECUTABLE_CONVERT);
cmdLine.addArgument(src);
cmdLine.addArgument("-colorspace");
cmdLine.addArgument("RGB");
cmdLine.addArgument(dst);
try {
executeCommandLine(cmdLine);
return true;
} catch (Exception e) {
LOG.error(" An exception occurred when converting the image format, Cause: ", e);
return false;
}
}
/**
* Gets the size of the image to compress.
* @param w The original width of the image
* @param h The original height of the picture
* @param width The standard width
* @param height High standard
* @param type type 1- Compression in terms of width 2- Compression by height 3- Compressed to scale
* @return size[0]- The width to compress, size[1]- The height to compress
*/
public static int[] getSize(double w, double h, double width, double height, int type) {
if (w < width) {// If the original width is smaller than the standard width
width = w;
}
if (h < height) {// If the original height is less than the standard height
height = h;
}
double scale = w / h;
switch (type) {
case 1:
height = width / scale;
break;
case 2:
width = height * scale;
break;
case 3:
if (width / height > scale) {
width = height * scale;
} else if ((width / height) < scale) {
height = width / scale;
}
break;
}
int[] size = new int[2];
size[0] = (int) width;
size[1] = (int) height;
return size;
}
/**
* Specify the width.
* @param src
* @param width
* @param dst
*/
public static boolean resize(String src, int width, String dst) {
// Build commands
CommandLine cmdLine = new CommandLine(EXECUTABLE_CONVERT);
cmdLine.addArgument(src);
cmdLine.addArgument("-resize");
cmdLine.addArgument(width + "");
cmdLine.addArgument(dst);
try {
executeCommandLine(cmdLine);
return true;
} catch (Exception e) {
LOG.error(" Something is wrong with the thumbnail, Cause: ", e);
return false;
}
}
/**
* Specify width and height.
* @param src
* @param width
* @param dst
*/
public static boolean resizeWH(String src,String dst, int width, int height ) {
// Build commands
CommandLine cmdLine = new CommandLine(EXECUTABLE_CONVERT);
cmdLine.addArgument(src);
cmdLine.addArgument("-resize");
cmdLine.addArgument(width + "x" + height +"!");
cmdLine.addArgument(dst);
try {
executeCommandLine(cmdLine);
return true;
} catch (Exception e) {
LOG.error(" Something is wrong with the thumbnail, Cause: ", e);
return false;
}
}
}
imagemagick will be installed on the server.