diff --git a/src/sc545/pay/utils/FileUtils.java b/src/sc545/pay/utils/FileUtils.java new file mode 100644 index 0000000..d3a9366 --- /dev/null +++ b/src/sc545/pay/utils/FileUtils.java @@ -0,0 +1,1106 @@ +package sc545.pay.utils; + +import java.awt.Color; +import java.awt.Font; +import java.awt.image.BufferedImage; +import java.io.BufferedWriter; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.PrintWriter; +import java.net.URL; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.UUID; + +import javax.imageio.ImageIO; +import javax.servlet.ServletContext; + +import net.coobird.thumbnailator.Thumbnails; +import net.coobird.thumbnailator.geometry.Positions; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.io.IOUtils; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.commons.CommonsMultipartFile; + +import sun.misc.BASE64Encoder; + +import com.freeway.image.combiner.ImageCombiner; +import com.freeway.image.combiner.enums.OutputFormat; +import com.freeway.image.combiner.enums.ZoomMode; +import com.google.zxing.*; +import com.google.zxing.common.BitMatrix; + +public class FileUtils { + + public static void main(String[] args) throws Exception { + System.out.println("/a/b".substring(0, "/a/b".length()-1)); + } + + + + + +public static final int BLACK = 0xFF000000; +public static final int WHITE = 0xFFFFFFFF; +public static BufferedImage toBufferedImage(BitMatrix matrix) { + int width = matrix.getWidth(); + int height = matrix.getHeight(); + BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE); + } + } + return image; +} + +private static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { + BufferedImage image = toBufferedImage(matrix); + if (!ImageIO.write(image, format, file)) { + throw new IOException("Could not write an image of format " + format + " to " + file); + } +} + +/** + * 删除二维码白边 + * @param matrix + * @return + */ +public static BitMatrix deleteQRWhite(BitMatrix matrix) { + int[] rec = matrix.getEnclosingRectangle(); + int resWidth = rec[2] + 1; + int resHeight = rec[3] + 1; + + BitMatrix resMatrix = new BitMatrix(resWidth, resHeight); + resMatrix.clear(); + for (int i = 0; i < resWidth; i++) { + for (int j = 0; j < resHeight; j++) { + if (matrix.get(i + rec[0], j + rec[1])) + resMatrix.set(i, j); + } + } + return resMatrix; +} + + + +/** + * 生成一张二维码图片文件 + * @param content 二维码内容 + * @param widthHeight 宽高度 + * @param path 图片存储路径(不带文件名) + * @return + */ +public static String QrImgFile(String content,int widthHeight,String path) { + try { + String codeName = UUID.randomUUID().toString();// 二维码的图片名 + String imageType = "jpg";// 图片类型 + MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); + Map hints = new HashMap(); + hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); + BitMatrix bitMatrix= multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, widthHeight, widthHeight, hints); + bitMatrix= deleteQRWhite(bitMatrix); + // BufferedImage imgbuf = toBufferedImage(bitMatrix); + File file1 = new File(path, codeName + "." + imageType); + writeToFile(bitMatrix, imageType, file1); + return path+codeName + "." + imageType; + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return null; +} + + +/** + * 生成一张二维码图片(BufferedImage) + * @param content 二维码内容 + * @param widthHeight 宽高度 + * @return + */ +public static BufferedImage QrImgBuf(String content,int widthHeight) { + try { + MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); + Map hints = new HashMap(); + hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); + BitMatrix bitMatrix= multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, widthHeight, widthHeight, hints); + bitMatrix= deleteQRWhite(bitMatrix); + BufferedImage imgbuf = toBufferedImage(bitMatrix); + return imgbuf; + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return null; +} + + +/** + * 生成一张二维码图片(base64)
+ * data:image/jpg;base64,base64_code + * @param content 二维码内容 + * @param widthHeight 宽高度 + * @return + */ +public static String QrImgB64(String content,int widthHeight) { + try { + MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); + Map hints = new HashMap(); + hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); + BitMatrix bitMatrix= multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, widthHeight, widthHeight, hints); + bitMatrix= deleteQRWhite(bitMatrix); + BufferedImage imgbuf = toBufferedImage(bitMatrix); + ByteArrayOutputStream os = new ByteArrayOutputStream();//新建流。 + ImageIO.write(imgbuf, "jpg", os);//利用ImageIO类提供的write方法,将bi以png图片的数据模式写入流。 + byte b[] = os.toByteArray();//从流中获取数据数组。 + String str = new BASE64Encoder().encode(b); + return str; + + } catch (Exception e) { + e.printStackTrace(); + } + + return null; +} + + +/** + * 图片质量压缩 + * @param img 文件流 + * @param quality 压缩质量 0~1/1为最高质量 + * @return + */ +public static BufferedImage rarImgBuf(InputStream img, double quality) { + BufferedImage buf =null; + try { + buf = Thumbnails.of(img).scale(1f).outputQuality(quality).asBufferedImage(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return buf; +} + +/** + * 图片质量压缩 + * @param img 文件地址 + * @param quality 压缩质量 0~1/1为最高质量 + * @return + */ +public static File rarImgFile(File img, double quality) { + File arg0 = img; + try { + Thumbnails.of(img).scale(1f).outputQuality(quality).toFile(arg0); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return arg0; +} + +/** + * 裁剪图片
+ * 从左上角开始裁切
+ * 另存图片保持等比缩放,若填写的高度不符合自动调整为等比例 + * + * @param img 图片文件 + * @param p 裁切位置 Positions.TOP/BOTTOM_LEFT/RIGHT、CENTER + * @param x 裁切x轴范围 + * @param y 裁切y轴范围 + * @param width 另存图片的宽度 + * @param height 另存图片的高度 + * @return + */ +public static File cutImgFile(File img,Positions p,int x,int y,int width,int height) { + File arg0 = img; + try { + Thumbnails.of(img).sourceRegion(p, x, y).size(width, height).keepAspectRatio(true).toFile(arg0); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return arg0; +} + + +/** + * 裁剪图片
+ * 从左上角开始裁切
+ * 另存图片保持等比缩放,若填写的高度不符合自动调整为等比例 + * + * @param img 图片流 + * @param p 裁切位置 Positions.TOP/BOTTOM_LEFT/RIGHT、CENTER + * @param x 裁切x轴范围 + * @param y 裁切y轴范围 + * @param width 另存图片的宽度 + * @param height 另存图片的高度 + * @return + */ +public static BufferedImage cutImgBuf(InputStream img,Positions p,int x,int y,int width,int height) { + BufferedImage buf =null; + try { + buf=Thumbnails.of(img).sourceRegion(p, x, y).size(width, height).keepAspectRatio(true).asBufferedImage(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return buf; +} + + + +/** + * 将图片存放在项目根路径下 + * @param servletContext + * @param file MultipartFile文件 + * @param path 在项目根目录下的存放路径 + * @param towhere 数据库入库格式,格式:表#id#字段 + * @return 图片路径(相对) + */ +public static String putImg(ServletContext servletContext,MultipartFile file,String path,String towhere) { + int maxSize = 1024*1024*2; //上传最大为2MB + if (file==null||file.getSize()>maxSize) { + return "图片最大上传2MB"; + } + + + File targetFile=null; + String realurl="";//返回存储路径 + String rid=""; + String fileName=file.getOriginalFilename();//获取文件名加后缀 + if(fileName.trim().length()<1) return "图片不能为空"; + if(fileName!=null&&fileName!=""){ + String lpath=path; + + if(servletContext==null) + path = "D:/"+(lpath.replaceAll("D:/", "").replaceAll("D://", "").replaceAll("D:", "").replaceAll("c:", ""));//图片存储在C盘下的路径 + else{ + //修改:原本存储在项目根路径下的,为了防止删除项目文件丢失 + //path = servletContext.getRealPath(lpath);//图片存储在项目根目录下的路径 + //现修改为:存储到固定文件夹(子路径保留),读取的时候通过url获取base64格式图片 + String basePath = ReadTxt.getSetting(null, "setting.ini", "FilePath", "D://scbox_settings/webFile"); + if("/".equals(basePath.substring(basePath.length()-1, basePath.length()))) basePath=basePath.substring(0, basePath.length()-1); + String np=lpath; + if(lpath.indexOf(":")>0){ + np = lpath.substring(lpath.indexOf(":")+2,lpath.length()); + if(!"/".equals(np.substring(0, 1))) np="/"+np; + }else{ + if(!"/".equals(np.substring(0, 1))) np="/"+np; + } + path = basePath+np; + } + String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀 + if (!(fileF.equals(".jpg") || fileF.equals(".jpeg") || fileF.equals(".png") || fileF.equals(".gif"))) { + return "只能上传jpg,jpeg,png,gif格式图片"; + } + //新的文件名 + fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF; + //获取文件夹路径 + File file1=new File(path); + //如果文件夹不存在则创建 + if(!file1.exists() && !file1.isDirectory()){ + file1.mkdirs(); + } + //将图片存入文件夹 + targetFile = new File(file1, fileName); + + try { + //将上传的文件写到服务器上指定的文件。 + file.transferTo(targetFile); + rarImgFile(targetFile, 0.8f); + //赋予权限 + /*String command = "chmod 775 -R " + targetFile; + Runtime runtime = Runtime.getRuntime(); + Process proc = runtime.exec(command);*/ + //生成文件地址 + + if(servletContext==null) realurl=path+"/"+fileName; + else realurl=ReadTxt.getSetting(null, "setting.ini", "resweb", "")+path+"/"+fileName; + //System.out.println("图片上传成功 \nUrl:"+realurl); + } catch (Exception e) { + e.printStackTrace(); + return "系统异常,图片上传失败"; + } + + /** + * 存储完成之后把信息存到数据库,后续用数据库ID来取用文件 + * + * **/ + DBUtil db = new DBUtil(); + int i = db.execUpdate("insert savefile(realurl) values('"+realurl+"')", null); + if(i>0){ + List> rs = db.execQuery("select * from savefile where realurl='"+realurl+"'", null); + if(rs!=null&&rs.size()>0) rid=rs.get(0).get("id")+""; + } + + //成功/添加图片用处 + if(towhere != null && !"".equals(towhere)) + saveSql(realurl, towhere,fileName); + } + + if(servletContext != null) return "/getImg/"+rid; + else return realurl; +} + +/** + * 将图片存放在项目根路径下(带名称,不含文件格式后缀) + * @param servletContext + * @param file MultipartFile文件 + * @param path 在项目根目录下的存放路径 + * @param towhere 数据库入库格式,格式:表#id#字段 + * @return 图片路径(相对) + */ +public static String putImgAsName(ServletContext servletContext,MultipartFile file,String path,String filename,String towhere) { + int maxSize = 1024*1024*2; //上传最大为2MB + if (file==null||file.getSize()>maxSize) { + return "图片最大上传2MB"; + } + File targetFile=null; + String rid=""; + String realurl="";//返回存储路径 + String fileName=file.getOriginalFilename();//获取文件名加后缀 + if(fileName.trim().length()<1) return "图片不能为空"; + if(fileName!=null&&fileName!=""){ + String lpath=path; + if(servletContext==null) + path = "D:/"+(lpath.replaceAll("D:/", "").replaceAll("D://", "").replaceAll("D:", "").replaceAll("c:", ""));//图片存储在C盘下的路径 + else{ + //修改:原本存储在项目根路径下的,为了防止删除项目文件丢失 + //path = servletContext.getRealPath(lpath);//图片存储在项目根目录下的路径 + //现修改为:存储到固定文件夹(子路径保留),读取的时候通过url获取base64格式图片 + String basePath = ReadTxt.getSetting(null, "setting.ini", "FilePath", "D://scbox_settings/webFile"); + if("/".equals(basePath.substring(basePath.length()-1, basePath.length()))) basePath=basePath.substring(0, basePath.length()-1); + String np=lpath; + if(lpath.indexOf(":")>0){ + np = lpath.substring(lpath.indexOf(":")+2,lpath.length()); + if(!"/".equals(np.substring(0, 1))) np="/"+np; + }else{ + if(!"/".equals(np.substring(0, 1))) np="/"+np; + } + path = basePath+np; + } + + String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀 + if (!(fileF.equals(".jpg") || fileF.equals(".jpeg") || fileF.equals(".png") || fileF.equals(".gif"))) { + return "只能上传jpg,jpeg,png,gif格式图片"; + } + //新的文件名 + if(filename!=null&&filename.length()>0) + fileName=filename+fileF; + else + fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF; + //获取文件夹路径 + File file1=new File(path); + //如果文件夹不存在则创建 + if(!file1.exists() && !file1.isDirectory()){ + file1.mkdirs(); + } + //将图片存入文件夹 + targetFile = new File(file1, fileName); + + try { + //将上传的文件写到服务器上指定的文件。 + file.transferTo(targetFile); + rarImgFile(targetFile, 0.8f); + //赋予权限 + /*String command = "chmod 775 -R " + targetFile; + Runtime runtime = Runtime.getRuntime(); + Process proc = runtime.exec(command);*/ + //生成文件地址 + if(servletContext==null) realurl=path+"/"+fileName; + else realurl=ReadTxt.getSetting(null, "setting.ini", "resweb", "")+path+"/"+fileName; + //System.out.println("图片上传成功 \nUrl:"+realurl); + } catch (Exception e) { + e.printStackTrace(); + return "系统异常,图片上传失败"; + } + + /** + * 存储完成之后把信息存到数据库,后续用数据库ID来取用文件 + * + * **/ + DBUtil db = new DBUtil(); + int i = db.execUpdate("insert savefile(realurl) values('"+realurl+"')", null); + if(i>0){ + List> rs = db.execQuery("select * from savefile where realurl='"+realurl+"'", null); + if(rs!=null&&rs.size()>0) rid=rs.get(0).get("id")+""; + } + + //成功/添加图片用处 + if(towhere != null && !"".equals(towhere)) + saveSql(realurl, towhere,fileName); + } + + if(servletContext != null) return "/getImg/"+rid; + else return realurl; +} + + +/** + * 将视频存放在项目根路径下 + * @param servletContext + * @param file MultipartFile文件 + * @param path 在项目根目录下的存放路径 + * @param towhere 数据库入库格式,格式:表#id#字段 + * @return 图片路径(相对) + */ +public static String putVideo(ServletContext servletContext,MultipartFile file,String path,String towhere) { + int maxSize = 1024*1024*10; //上传最大为2MB + if (file==null) { + return ""; + } + if (file.getSize()>maxSize) { + return "视频最大上传10MB"; + } + File targetFile=null; + String rid=""; + String realurl="";//返回存储路径 + String fileName=file.getOriginalFilename();//获取文件名加后缀 + if(fileName.trim().length()<1) return ""; + if(fileName!=null&&fileName!=""){ + String lpath=path; + if(servletContext==null) + path = "D:/"+(lpath.replaceAll("D:/", "").replaceAll("D://", "").replaceAll("D:", "").replaceAll("c:", ""));//图片存储在C盘下的路径 + else{ + + //修改:原本存储在项目根路径下的,为了防止删除项目文件丢失 + //path = servletContext.getRealPath(lpath);//图片存储在项目根目录下的路径 + //现修改为:存储到固定文件夹(子路径保留),读取的时候通过url获取base64格式图片 + String basePath = ReadTxt.getSetting(null, "setting.ini", "FilePath", "D://scbox_settings/webFile"); + if("/".equals(basePath.substring(basePath.length()-1, basePath.length()))) basePath=basePath.substring(0, basePath.length()-1); + String np=lpath; + if(lpath.indexOf(":")>0){ + np = lpath.substring(lpath.indexOf(":")+2,lpath.length()); + if(!"/".equals(np.substring(0, 1))) np="/"+np; + }else{ + if(!"/".equals(np.substring(0, 1))) np="/"+np; + } + path = basePath+np; + + } + + String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀 + if (!(fileF.equals(".mp4"))) { + return "只能上传mp4格式视频"; + } + //新的文件名 + fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF; + //获取文件夹路径 + File file1=new File(path); + //如果文件夹不存在则创建 + if(!file1.exists() && !file1.isDirectory()){ + file1.mkdirs(); + } + //将图片存入文件夹 + targetFile = new File(file1, fileName); + + try { + //将上传的文件写到服务器上指定的文件。 + file.transferTo(targetFile); + rarImgFile(targetFile, 0.8f); + //赋予权限 + /*String command = "chmod 775 -R " + targetFile; + Runtime runtime = Runtime.getRuntime(); + Process proc = runtime.exec(command);*/ + //生成文件地址 + if(servletContext==null) realurl=path+"/"+fileName; + else realurl=ReadTxt.getSetting(null, "setting.ini", "resweb", "")+path+"/"+fileName; + //System.out.println("图片上传成功 \nUrl:"+realurl); + } catch (Exception e) { + e.printStackTrace(); + return "系统异常,视频上传失败"; + } + + /** + * 存储完成之后把信息存到数据库,后续用数据库ID来取用文件 + * + * **/ + DBUtil db = new DBUtil(); + int i = db.execUpdate("insert savefile(realurl) values('"+realurl+"')", null); + if(i>0){ + List> rs = db.execQuery("select * from savefile where realurl='"+realurl+"'", null); + if(rs!=null&&rs.size()>0) rid=rs.get(0).get("id")+""; + } + + //成功/添加图片用处 + if(towhere != null && !"".equals(towhere)) + saveSql(realurl, towhere,fileName); + } + + if(servletContext != null) return "/getImg/"+rid; + else return realurl; +} + + + + +/** + * 将文件存放在项目根路径下 + * @param servletContext + * @param file MultipartFile文件 + * @param filename 文件名 不含后缀格式,为空自动生成 + * @param path 在项目根目录下的存放路径 + * @param towhere 数据库入库格式,格式:表#id#字段 + * @return 图片路径(相对) + */ +public static String putFile(ServletContext servletContext,MultipartFile file,String filename,String path,String towhere) { + int maxSize = 1024*1024*10; //上传最大为2MB + if (file==null) { + return ""; + } + if (file.getSize()>maxSize) { + return "文件最大上传20MB"; + } + File targetFile=null; + String rid=""; + String realurl="";//返回存储路径 + String fileName=file.getOriginalFilename();//获取文件名加后缀 + if(fileName.trim().length()<1) return ""; + if(fileName!=null&&fileName!=""){ + String lpath=path; + if(servletContext==null) + path = "D:/"+(lpath.replaceAll("D:/", "").replaceAll("D://", "").replaceAll("D:", "").replaceAll("c:", ""));//图片存储在C盘下的路径 + else{ + //修改:原本存储在项目根路径下的,为了防止删除项目文件丢失 + //path = servletContext.getRealPath(lpath);//图片存储在项目根目录下的路径 + //现修改为:存储到固定文件夹(子路径保留),读取的时候通过url获取base64格式图片 + String basePath = ReadTxt.getSetting(null, "setting.ini", "FilePath", "D://scbox_settings/webFile"); + if("/".equals(basePath.substring(basePath.length()-1, basePath.length()))) basePath=basePath.substring(0, basePath.length()-1); + String np=lpath; + if(lpath.indexOf(":")>0){ + np = lpath.substring(lpath.indexOf(":")+2,lpath.length()); + if(!"/".equals(np.substring(0, 1))) np="/"+np; + }else{ + if(!"/".equals(np.substring(0, 1))) np="/"+np; + } + path = basePath+np; + } + + String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀 + + //新的文件名 + if(filename!=null&&filename.length()>0) + fileName=filename+fileF; + else + fileName=new Date().getTime()+"_"+new Random().nextInt(1000)+fileF; + //获取文件夹路径 + File file1=new File(path); + //如果文件夹不存在则创建 + if(!file1.exists() && !file1.isDirectory()){ + file1.mkdirs(); + } + //将图片存入文件夹 + targetFile = new File(file1, fileName); + + try { + //将上传的文件写到服务器上指定的文件。 + file.transferTo(targetFile); + //赋予权限 + /*String command = "chmod 775 -R " + targetFile; + Runtime runtime = Runtime.getRuntime(); + Process proc = runtime.exec(command);*/ + //生成文件地址 + if(servletContext==null) realurl=path+"/"+fileName; + else realurl=ReadTxt.getSetting(null, "setting.ini", "resweb", "")+path+"/"+fileName; + //System.out.println("图片上传成功 \nUrl:"+realurl); + } catch (Exception e) { + e.printStackTrace(); + return "系统异常,视频上传失败"; + } + + /** + * 存储完成之后把信息存到数据库,后续用数据库ID来取用文件 + * + * **/ + DBUtil db = new DBUtil(); + int i = db.execUpdate("insert savefile(realurl) values('"+realurl+"')", null); + if(i>0){ + List> rs = db.execQuery("select * from savefile where realurl='"+realurl+"'", null); + if(rs!=null&&rs.size()>0) rid=rs.get(0).get("id")+""; + } + + //成功/添加图片用处 + if(towhere != null && !"".equals(towhere)) + saveSql(realurl, towhere,fileName); + } + + if(servletContext != null) return "/getFile/"+rid; + else return realurl; +} + + +/** + * 把上传的文件信息存入数据库 + * @param realurl 文件路径 + * @param towhere 数据库入库格式,格式:表#id#字段 + * @param saveName 显示文件名称 + */ +public static void saveSql(String realurl, String towhere, String saveName) { + + if(realurl.indexOf("http")>=0 || realurl.indexOf("upload")<0) return; + + //标记文件被使用的地方,方便后续清理无用文件 + // 标记位置格式:表#id#字段,比如哪个表里哪条数据的哪个字段使用该文件,byx_class#16#clist + DBUtil db = new DBUtil(); + + if(towhere.split("#").length>2&&realurl.trim().length()>0){ + String mstab = towhere.split("#")[0]; + String msid = towhere.split("#")[1]; + String mstag = towhere.split("#")[2]; + + if(realurl.indexOf("/getImg/")==0) { + realurl=realurl.replace("/getImg/", ""); + if(db.execSql("select * from savefile where id = '"+realurl+"'", null)>0){//已存在 + db.execUpdate("update savefile set mstab=?,msid=?,mstag=?,savename=? where id=?", new String[]{mstab.trim(),msid.trim(),mstag.trim(),realurl.trim(),saveName==null?"":saveName.trim()}); + }else{//不存在 + //db.execUpdate("insert into savefile(realurl,mstab,msid,mstag,savename) values(?,?,?,?,?)", new String[]{realurl.trim(),mstab.trim(),msid.trim(),mstag.trim(),saveName==null?"":saveName.trim()}); + } + }else{ + if(db.execSql("select * from savefile where realurl = '"+realurl+"'", null)>0){//已存在 + db.execUpdate("update savefile set mstab=?,msid=?,mstag=?,savename=? where realurl=?", new String[]{mstab.trim(),msid.trim(),mstag.trim(),realurl.trim(),saveName==null?"":saveName.trim()}); + }else{//不存在 + db.execUpdate("insert into savefile(realurl,mstab,msid,mstag,savename) values(?,?,?,?,?)", new String[]{realurl.trim(),mstab.trim(),msid.trim(),mstag.trim(),saveName==null?"":saveName.trim()}); + } + } + + + } + +} + + +/** + * 创建一个文件并写入内容 + * @param servletContext + * @param path 路径(不含文件名) + * @param content 内容 + * @param suffix 后缀名(不含点) + * @param oldfile 自己设定文件名(含后缀) 可带路径,若为空则根据时间戳生成随机文件名 + * @return + */ +public static String writeFile(ServletContext servletContext, String path, + String content, String suffix, String oldfile) { + + if(".".equals(suffix.substring(0, 1))) suffix=suffix.substring(1, suffix.length()); + + //兼容文件名含路径 + if(oldfile!=null&&!"".equals(oldfile.trim())){ + int i = oldfile.replace("\\","/").lastIndexOf("/"); + if(i>0) + path=oldfile.substring(0, i); + oldfile=oldfile.substring(i+1, oldfile.length()); + } + + String path1 = path; + if(path.indexOf("./")==0) + path =path.substring(1, path.length()); + + if (servletContext == null) { + if(path.indexOf(":") <= 0&&path.indexOf("/") <0) + path1 = "D:\\" + path; + else path1 = path; + } else { + //修改:原本存储在项目根路径下的,为了防止删除项目文件丢失 + //path = servletContext.getRealPath(lpath);//图片存储在项目根目录下的路径 + //现修改为:存储到固定文件夹(子路径保留),读取的时候通过url获取base64格式图片 + String basePath = ReadTxt.getSetting(null, "setting.ini", "FilePath", "D://scbox_settings/webFile"); + if("/".equals(basePath.substring(basePath.length()-1, basePath.length()))) basePath=basePath.substring(0, basePath.length()-1); + String np=path; + if(path.indexOf(":")>0){ + np = path.substring(path.indexOf(":")+2,path.length()); + if(!"/".equals(np.substring(0, 1))) np="/"+np; + }else{ + if(!"/".equals(np.substring(0, 1))) np="/"+np; + } + path1 = basePath+np; + } + + if(!"/".equals(path1.replace("\\", "/").substring(path1.replace("\\", "/").length()-1))) path1+="/"; + File file1 = new File(path1); + if (!file1.exists() && !file1.isDirectory()) { + file1.mkdirs(); + } + + String fileName = new Date().getTime() + "_" + + new Random().nextInt(1000) + "." + suffix; + if(oldfile!=null&&!"".equals(oldfile.trim())) fileName = oldfile; + path1 += fileName; + file1 = new File(path1); + + try { + if (!file1.exists()) { + file1.createNewFile(); + } + PrintWriter out = new PrintWriter( + new BufferedWriter(new OutputStreamWriter( + new FileOutputStream(path1), "UTF-8"))); + out.write(content); + out.flush(); + out.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + return fileName; +} + +/** + * 删除上传的文件,联通表数据一块删除 + *
servletContext为空默认C盘 + */ +public static void delfile(ServletContext servletContext, String path) { + path=path.replace(ReadTxt.getSetting(null, "setting.ini", "resweb", ""),""); + if(path.indexOf("http")==0 || path.indexOf("//")==0) return ; + if(path.indexOf("./")==0) + path =path.substring(1, path.length()); + + String path1 = path; + if (servletContext == null) { + if(path.indexOf(":") <= 0) + path1 = "D:\\" + path; + } else { + if(path.indexOf("/getImg/")==0){ + String rid = path.replace("/getImg/", ""); + DBUtil db = new DBUtil(); + List> rs = db.execQuery("select * from savefile where id ="+rid, null); + if(rs!=null&&rs.size()>0){ + path=rs.get(0).get("realurl")+""; + path1=rs.get(0).get("realurl")+""; + } + } else path1 = servletContext.getRealPath(path); + } + + File file1 = new File(path1); + if(file1.exists()) { + file1.delete(); + //兼容 + new DBUtil().execUpdate("delete from savefile where realurl=?", new String[]{path}); + + } + + +} + + +/** + * 删除字符串中提取的图片文件 + * + * @param path + * 项目根目录下的文件路径(servletContext若null为c盘下的) + */ +public static void delFileForStr(ServletContext servletContext, String str) { + + ArrayList imgs = Utils.getImgStr(str, true); + DBUtil db = new DBUtil(); + + for (String path : imgs) { + path=path.replace(ReadTxt.getSetting(null, "setting.ini", "resweb", ""),""); + if(path.indexOf("http")==0 || path.indexOf("//")==0) continue; + String oldpath = path; + if(path.indexOf("./")==0) + path =path.substring(1, path.length()); + + path=path.replace(ReadTxt.getSetting(null, "setting.ini", "resweb", ""),""); + + String path1 = path; + if (servletContext == null) { + if(path.indexOf(":") <= 0) + path1 = "D:\\" + path; + } else { + if(path.indexOf("/getImg/")==0){ + String rid = path.replace("/getImg/", ""); + List> rs = db.execQuery("select * from savefile where id ="+rid, null); + if(rs!=null&&rs.size()>0){ + oldpath=rs.get(0).get("realurl")+""; + path1=rs.get(0).get("realurl")+""; + } + } else path1 = servletContext.getRealPath(path); + } + + File file1 = new File(path1); + if(file1.exists()) { + file1.delete(); + + //兼容img_tag + db.execUpdate("delete from savefile where realurl='"+oldpath+"'", null); + + } + } + + +} + +/** + * 提取字符串中的图片地址存入数据库 + * @param str + * @param towhere + * @param saveName + */ +public static void intoSqlForStr(String str,String towhere,String saveName) { + ArrayList imgs = Utils.getImgStr(str, true); + DBUtil db = new DBUtil(); + String mstab = towhere.split("#")[0]; + String msid = towhere.split("#")[1]; + String mstag=""; + if(towhere.split("#").length>2) + mstag = towhere.split("#")[2]; + + for (String path : imgs) { + if(path.indexOf("/getImg/")==0){ + String rid = path.replace("/getImg/", ""); + List> rs = db.execQuery("select * from savefile where id ="+rid, null); + if(rs!=null&&rs.size()>0){ + path=rs.get(0).get("realurl")+""; + + } + } + + if(path.indexOf("http")>=0 || path.indexOf("upload")<0) continue; + + if(db.execSql("select * from savefile where realurl = '"+path+"'", null)>0){//已存在 + db.execUpdate("update savefile set mstab=?,msid=?,mstag=?,savename=? where realurl=?", new String[]{mstab.trim(),msid.trim(),mstag.trim(),saveName==null?"":saveName.trim(),path.trim()}); + }else{//不存在 + db.execUpdate("insert into savefile(realurl,mstab,msid,mstag,savename) values(?,?,?,?,?)", new String[]{path.trim(),mstab.trim(),msid.trim(),mstag.trim(),saveName==null?"":saveName.trim()}); + } + } + +} + + + +/** + * 下载url图片 + * @param url + * @return + */ +public static File downloadImage(String url) { + File file = null; + + URL urlfile; + InputStream inputStream = null; + OutputStream outputStream= null; + try { + file = File.createTempFile(new Date().getTime()+"_"+new Random().nextInt(1000), url.substring(url.lastIndexOf("."))); + //下载 + urlfile = new URL(url); + inputStream = urlfile.openStream(); + outputStream= new FileOutputStream(file); + + int bytesRead = 0; + byte[] buffer = new byte[8192]; + while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + if (null != outputStream) { + outputStream.close(); + } + if (null != inputStream) { + inputStream.close(); + } + + } catch (Exception e) { + e.printStackTrace(); + } + } + return file; +} + +public static MultipartFile getMultipartFile(File file) { + FileItem item = new DiskFileItemFactory().createItem("file" + , MediaType.MULTIPART_FORM_DATA_VALUE + , true + , file.getName()); + try (InputStream input = new FileInputStream(file); + OutputStream os = item.getOutputStream()) { + // 流转移 + IOUtils.copy(input, os); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid file: " + e, e); + } + + return new CommonsMultipartFile(item); +} + +/** + * 返回文件类型 + * @param file + * @return + */ +public static ResponseEntity returnFile(File file) { + if (file == null) { + return null; + } + HttpHeaders headers = new HttpHeaders(); + headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); + headers.add("Content-Disposition", "attachment; filename=" + file.getName()); + headers.add("Pragma", "no-cache"); + headers.add("Expires", "0"); + headers.add("Last-Modified", new Date().toString()); + headers.add("ETag", String.valueOf(System.currentTimeMillis())); + return ResponseEntity + .ok() + .headers(headers) + .contentLength(file.length()) + .contentType(MediaType.parseMediaType("application/octet-stream")) + .body(new FileSystemResource(file)); +} + + + +/** + * 制作合成图片 +* @param title 课程名称 15字内 + * @param des 课程简介 48字内 + * @param teacher 老师名称 + * @param teacherImgUrl 老师透明照片180*318 + * @param localUrl 二维码地址 + * @return + */ +public static String imgPS(String title,String des,String teacher,String teacherImgUrl,String localUrl) { + String r=null; + try { + String bjUrl = "file:///C://webimg/bj.jpg"; + String imgUrl = teacherImgUrl; + + //标题x,y轴,字体大小,最大行数,行高 + int title_x=27; + int title_y=30; + int title_f=100; + int title_h=2; + int title_l=120; + if(title.length()<=6){//6字以内 + title_x=40; + title_y=30; + title_f=100; + title_h=2; + title_l=120; + }else if(title.length()>6&&title.length()<9){ //7-8字 + title_x=22; + title_y=67; + title_f=85; + title_h=2; + title_l=88; + }else if(title.length()>8&&title.length()<13){ //9-12字 + title_x=33; + title_y=32; + title_f=80; + title_h=3; + title_l=85; + }else{ + title_x=27; + title_y=30; + title_f=65; + title_h=3; + title_l=75; + } + + //简介x,y轴,字体大小 + int des_x=27; + int des_y=30; + int des_f=20; + int des_h=2; + int des_l=25; + if(des.length()<=16){//16字以内 + des_y=310; + des_h=1; + }else if(title.length()>16&&title.length()<33){ //16-32字 + des_y=303; + des_h=2; + }else{ //32++ + des_y=290; + des_h=3; + } + + teacher = "主讲人:"+teacher; + //讲师x轴 + int tx = (178-(teacher.length()*24))/2; + + + Color c1=new Color(26, 121, 134); + //合成器(指定背景图和输出格式,整个图片的宽高和相关计算依赖于背景图,所以背景图的大小是个基准) + ImageCombiner combiner = new ImageCombiner( bjUrl, 385, 666, ZoomMode.Height, OutputFormat.JPG); + + //标题 + combiner.addTextElement(title, new Font("微软雅黑",Font.BOLD, title_f), title_x, title_y) //内容,默认字体为阿里普惠,字体大小,x,y + .setCenter(false) //居中绘制(会忽略x坐标,改为自动计算) + .setAlpha(1.0f) //透明度(0.0~1.0) + .setRotate(0) //旋转(0~360) + .setAutoBreakLine(340, title_h, title_l) //自动换行 + .setColor(c1); //颜色 + + //简介 + combiner.addTextElement(des, new Font("微软雅黑",Font.BOLD, des_f), des_x,des_y) //内容,默认字体为阿里普惠,字体大小,x,y + .setCenter(false) //居中绘制(会忽略x坐标,改为自动计算) + .setAutoBreakLine(335, des_h, des_l) //自动换行 /最大宽度,最大行数,行高 + .setColor(c1); //颜色 + + //讲师 + combiner.addTextElement(teacher, new Font("微软雅黑",Font.BOLD, 24), tx+22, 390) //内容,默认字体为阿里普惠,字体大小,x,y + .setCenter(false) //居中绘制(会忽略x坐标,改为自动计算) + .setAlpha(1.0f) //透明度(0.0~1.0) + .setRotate(0) //旋转(0~360) + .setAutoBreakLine(178, 1, 24) //自动换行 /最大宽度,最大行数,行高 + .setColor(Color.WHITE); //颜色 + + //图片 + combiner.addImageElement(imgUrl, 205, 349, 180, 318, ZoomMode.Width) //imgUrl, x, y, width, height, zoomMode + .setCenter(false) //居中绘制(会忽略x坐标,改为自动计算) + .setRoundCorner(0); //设置圆角 + + + //生成二维码Buffer + BufferedImage imgbuf = QrImgBuf(localUrl, 200); + combiner.addImageElement(imgbuf, 29, 441, 165, 165, ZoomMode.WidthHeight) + .setRoundCorner(0);//圆角 + + //执行图片合并 + combiner.combine(); + + //可以获取流(并上传oss等) + //InputStream is = combiner.getCombinedImageStream(); + + //也可以保存到本地 + //combiner.save("D://image.jpg"); + + //压缩图片 + //BufferedImage img = rarImgBuf(combiner.getCombinedImageStream(),0.5f); + + //输出为base64 + byte[] arr = IOUtils.toByteArray(combiner.getCombinedImageStream()); + r = Base64.encodeBase64String(arr);//转换为base64格式 + + } catch (Exception e) { + System.out.println(e); + } + + return r; +} + + + +}