服务器端图片多中尺寸的生成,服务器端尺寸,1、你上传图片之后,服务
分享于 点击 32131 次 点评:231
服务器端图片多中尺寸的生成,服务器端尺寸,1、你上传图片之后,服务
1、你上传图片之后,服务器不做任何处理。比如路径: http://1.asset.m3958.com/gasset/1.png
2、当有人通过 http://1.asset.m3958.com/gasset/1.48x48.png 请求这个图片时,如果这个图片存在,就发送了,如果不存在,服务器也不处理,马上返回原图,但是做了一件很便宜的,额外的事情,记录一个文件,说明有人做了这样的请求。
3、服务器一侧的apache camel将这个文件捡起来,按照需要的尺寸处理它。
这是文件的内容:
94,48x48,jpg
分别是资产id,尺寸,后缀
但这样设计还必须防范一个攻击,比如有人用程序不停的生成不同尺寸的url来请求,服务器磁盘可能很快被生成的图片占满了。
所以camel处理的时候,仅允许6个不同尺寸的图片,如果超出,最老生成的图片将会被替换。
下面是camel代码:
public class SizeProcessor { private static Joiner pathJoiner = Joiner.on(File.separatorChar); private static Pattern SIZED_FILE_NAME = Pattern.compile("^\\\\d+\\\\.\\\\d+x\\\\d+\\\\.(.*)$"); public void p1(Exchange exchange) throws SQLException, IOException{ Message in = exchange.getIn(); String inBody = in.getBody(String.class).trim(); String[] resizelog = inBody.split(",");//55,320x240,png String id = resizelog[0].trim(); String size = resizelog[1].trim(); String[] wh = size.split("x"); if(Integer.parseInt(wh[0]) > 2000 || Integer.parseInt(wh[1])>2000){ return; } String ext = resizelog[2].trim(); File srcd; if(Osdetecter.isWindows()){ srcd = new File("x:/path/to/debug",pathJoiner.join(id.split("", 5))); }else{ srcd = new File("/path/to/production",pathJoiner.join(id.split("", 5))); } List<File> sizedFiles = Lists.newArrayList(srcd.listFiles()); if(sizedFiles.size() > 6){//max 7 size Collections.sort(sizedFiles, new Comparator<File>() { @Override public int compare(File f1, File f2) { long f1l = f1.lastModified(); long f2l = f2.lastModified(); System.out.println(f1.getName() + ":" + f1l); if(f1l > f2l){ return 1; }else if(f1l < f2l){ return -1; }else{ return 0; } } }); for(int i = sizedFiles.size() - 1;i > 5;i--){ File f = sizedFiles.get(i); System.out.println(f.getName()); Matcher m = SIZED_FILE_NAME.matcher(f.getName()); if(m.matches()){ System.out.println(f.getName() + "--- deleted!"); f.delete(); } } }; String srcf = id + "." + ext; String dstf = id + "." + size + "." + ext; List<String> args = new ArrayList<String>(); args.add(srcf); args.add("-resize"); args.add(size); args.add(dstf); Message out = exchange.getOut();out.setHeader(ExecBinding.EXEC_COMMAND_EXECUTABLE,"/path/to/convert"); out.setHeader(ExecBinding.EXEC_COMMAND_ARGS, args); out.setHeader(ExecBinding.EXEC_COMMAND_TIMEOUT,30000); out.setHeader(ExecBinding.EXEC_COMMAND_WORKING_DIR,srcd.getAbsolutePath()); }}//该片段来自于http://byrx.net
用户点评