图片类

各种图片操作

取压缩包图片

  /** 
	 * 解压,处理下载的zip工具包文件 
	 *  
	 * @param directory 
	 *            要解压到的目录 
	 * @param zip 
	 *            工具包文件 
	 *  
	 * @throws Exception 
	 *             操作失败时抛出异常 
	 *             unzipFile("d://work", new File("D://work/ftp/2.zip"),"2.JPG");
	 */  
	public static boolean unzipFile(String directory, String zip,String fname,int size)   {  
		boolean falg=false;
	    try  {  
	    	log.info("文件名字:"+fname);
	        ZipInputStream zis = new ZipInputStream(new FileInputStream(new File(zip)));  
	       
//	        ZipFile zFile=new ZipFile(zip);
//	        int size = zFile.size();
//	        log.info("文件数量"+size);
	        ZipEntry ze = zis.getNextEntry(); 
	       
	        log.info("ze--->"+ze);
	        File parent = new File(directory);  
//	        if (!parent.exists() && !parent.mkdirs())  
//	        {  
//	            throw new Exception("创建解压目录 \"" + parent.getAbsolutePath() + "\" 失败");  
//	        }  
	        
	        int i=1;
	        while(ze == null){
		    	   ze=zis.getNextEntry();
		    	 
		    	   i++;
		    	   if(i>=size){
		    		  
		    		   break;
		    	   }
		       }
	        
	      
	        while (ze != null){  
	            String name = ze.getName(); 
	           log.info("name---》"+name);
	            if(name.equals(fname)){
	            //	log.info("开始下载"+fname);
	            	File child = new File(parent, name);  
	                FileOutputStream output = new FileOutputStream(child);  
	            byte[] buffer = new byte[10240];  
	            int bytesRead = 0;  
	            while ((bytesRead = zis.read(buffer)) > 0)  
	            {  
	                output.write(buffer, 0, bytesRead);  
	             //   log.info("下载中");
	                 falg=true;
	            }  
	            output.flush();  
	            output.close();  
	                ze = zis.getNextEntry(); 
	                zis.close();  
	                break;
	            }  else {
					ze=zis.getNextEntry();
				}
	            }
	            
	           
	    }  
	    catch (IOException e)  {  
	    	 
	    	log.info(e.getMessage());
	    }  
	    return falg;
	}  

生成图片方寸压缩包

 /**
	     * String zipUrl="D://work/ftp/3.zip";
	       String fromUrl="D://work/yh.pdf";
	       String toUrl="/yh.pdf";
	       boolean result = add(zipUrl,fromUrl ,toUrl);
	     * @param zipUrl
	     * @param fromUrl
	     * @param toUrl
	     * @return
	     */
	    public static boolean add(String zipUrl,String fromUrl,String toUrl)   {
	    	Map <String,String> env = new HashMap <>(); 
	        env.put("create","true");
	        //使用语法定位文件系统 
	        //在java.net.JarURLConnection中定义
	        Path path = Paths.get(zipUrl);
	        
	       
	        URI uri = URI.create("jar:"+path.toUri());
	       try(FileSystem zipfs = FileSystems.newFileSystem(uri,env)){
	            Path externalTxtFile = Paths.get(fromUrl);
	            Path pathInZipfile = zipfs.getPath(toUrl);
	            //将文件复制到zip文件中
	    		Files.copy(externalTxtFile,pathInZipfile,StandardCopyOption.REPLACE_EXISTING);
	    		return true;
	        }catch (Exception e) {
	        	return false;
	    	}
         }

工具类

package com.kanq.jining.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.apache.logging.log4j.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.itextpdf.text.pdf.PdfStructTreeController.returnType;

public class QTUtils {
	
	public static Logger log = LoggerFactory.getLogger(QTUtils.class);
  
  public static String getValue(String name) {
    Properties properties = new Properties();
    String value = "";
    try
    {
      properties = PropertiesLoaderUtils.loadAllProperties("application.properties");
      
      value = new String(properties.getProperty(name).getBytes("iso-8859-1"), "utf-8");
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    return value;
  }
  
  /** 
	 * 解压,处理下载的zip工具包文件 
	 *  
	 * @param directory 
	 *            要解压到的目录 
	 * @param zip 
	 *            工具包文件 
	 *  
	 * @throws Exception 
	 *             操作失败时抛出异常 
	 *             unzipFile("d://work", new File("D://work/ftp/2.zip"),"2.JPG");
	 */  
	public static boolean unzipFile(String directory, String zip,String fname,int size)   {  
		boolean falg=false;
	    try  {  
	    	log.info("文件名字:"+fname);
	        ZipInputStream zis = new ZipInputStream(new FileInputStream(new File(zip)));  
	       
//	        ZipFile zFile=new ZipFile(zip);
//	        int size = zFile.size();
//	        log.info("文件数量"+size);
	        ZipEntry ze = zis.getNextEntry(); 
	       
	        log.info("ze--->"+ze);
	        File parent = new File(directory);  
//	        if (!parent.exists() && !parent.mkdirs())  
//	        {  
//	            throw new Exception("创建解压目录 \"" + parent.getAbsolutePath() + "\" 失败");  
//	        }  
	        
	        int i=1;
	        while(ze == null){
		    	   ze=zis.getNextEntry();
		    	 
		    	   i++;
		    	   if(i>=size){
		    		  
		    		   break;
		    	   }
		       }
	        
	      
	        while (ze != null){  
	            String name = ze.getName(); 
	           log.info("name---》"+name);
	            if(name.equals(fname)){
	            //	log.info("开始下载"+fname);
	            	File child = new File(parent, name);  
	                FileOutputStream output = new FileOutputStream(child);  
	            byte[] buffer = new byte[10240];  
	            int bytesRead = 0;  
	            while ((bytesRead = zis.read(buffer)) > 0)  
	            {  
	                output.write(buffer, 0, bytesRead);  
	             //   log.info("下载中");
	                 falg=true;
	            }  
	            output.flush();  
	            output.close();  
	                ze = zis.getNextEntry(); 
	                zis.close();  
	                break;
	            }  else {
					ze=zis.getNextEntry();
				}
	            }
	            
	           
	    }  
	    catch (IOException e)  {  
	    	 
	    	log.info(e.getMessage());
	    }  
	    return falg;
	}  
	 public static String creatml(String slid, String ml)
	  {
	    Calendar cal = Calendar.getInstance();
	    int d = cal.get(5);
	    int m = cal.get(2) + 1;
	    String month = "";
	    String day = "";
	    if (m < 10) {
	      month = "0" + m;
	    } else {
	      month = "" + m;
	    }
	    if (d < 10) {
	      day = "0" + d;
	    } else {
	      day = "" + d;
	    }
	    int year = cal.get(1);
	    
	    String dizhi = ml + "/" + year + "/" + month + "/" + day + "/" + slid + "/";
	    
	    File dir = new File(dizhi);
	    if (!dir.exists())
	    {
	      dir.mkdirs();
	      System.out.println("创建目录成功");
	    }
	    String DZ = year + "/" + month + "/" + day + "/"+ slid + "/";
	    return DZ;
	  }
	 public static String creatWJ(String slid, String ml){
	    
	 String tzwjdz = QTUtils.getValue("tzwjdz");
	 
	    String mldz = tzwjdz + "/"  + slid ;
	    String dizhi = tzwjdz + "/" +  slid +"/"+slid+".zip";
	    
	    File dir = new File(mldz);
	   
	    if (!dir.exists()){
	      try {
			 dir.mkdirs();
			log.info("创建文件夹成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	      
	    }
	    String generateFile=null;
	    try {
	    	generateFile = generateFile( mldz, "zip");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	   // String DZ = year + "/" + month + "/" + day + "/"+ slid + "/";
	    return generateFile;
	  }
	  
	  
	 public static net.sf.json.JSONObject jsonobject(Map<String, Object> datalist) {
	        String str = com.alibaba.fastjson.JSONArray.toJSONString(datalist, filter, SerializerFeature.WriteNullBooleanAsFalse);
	        // 给数据都加上  “”
	       // str = str.replaceAll("\":\\s*([^\\[{\"])(.*?)(?=[[,\"]|[},]}])", "\":\"$1$2\"");
	        final net.sf.json.JSONObject fromObject = net.sf.json.JSONObject.fromObject(str);
	        return fromObject;
	    }
	 
	 private static ValueFilter filter = new ValueFilter() {

	        public Object process(Object obj, String s, Object v) {
	            if (v == null) {
	                return "";
	            }
	            return v;
	        }
	    };
	    
	    public static String jsonString(Map<String, Object> datalist) {
	        String str = com.alibaba.fastjson.JSONArray.toJSONString(datalist, filter, SerializerFeature.WriteNullBooleanAsFalse);
	        // 给数据都加上  “”
	         str = str.replaceAll("\":\\s*([^\\[{\"])(.*?)(?=[[,\"]|[},]}])", "\":\"$1$2\"");
	        //final net.sf.json.JSONObject fromObject = net.sf.json.JSONObject.fromObject(str);
	        return str;
	    }
	    public static void main (String[] args){
	    	
			//boolean unzipFile = unzipFile("d://work", "D:/work/ftp/2.zip","11.PNG");
	    	//boolean unzipFile = QTUtils.unzipFile("d://work", "D:/work/ftp/2.zip", "111.PNG",1);
	  // System.err.println(unzipFile);
	   String creatml = creatWJ("124", "d://work/ftp");
	   System.err.println(creatml);
	    }
	    
	    
	    public static Object getDIC(Object key) {
	        final Properties pros = new Properties();
	        String value = "";
	        try {

	            pros.load(new InputStreamReader(PropertiesUtil.class.getResourceAsStream("/dic.properties"), "UTF-8"));
	            value = pros.getProperty(key.toString());
	        } catch (Exception e) {
	            return e.getMessage();
	        }
	        return value;
	    }
	    
	    
	    /**
	     * String zipUrl="D://work/ftp/3.zip";
	       String fromUrl="D://work/yh.pdf";
	       String toUrl="/yh.pdf";
	       boolean result = add(zipUrl,fromUrl ,toUrl);
	     * @param zipUrl
	     * @param fromUrl
	     * @param toUrl
	     * @return
	     */
	    public static boolean add(String zipUrl,String fromUrl,String toUrl)   {
	    	Map <String,String> env = new HashMap <>(); 
	        env.put("create","true");
	        //使用语法定位文件系统 
	        //在java.net.JarURLConnection中定义
	        Path path = Paths.get(zipUrl);
	        
	       
	        URI uri = URI.create("jar:"+path.toUri());
	       try(FileSystem zipfs = FileSystems.newFileSystem(uri,env)){
	            Path externalTxtFile = Paths.get(fromUrl);
	            Path pathInZipfile = zipfs.getPath(toUrl);
	            //将文件复制到zip文件中
	    		Files.copy(externalTxtFile,pathInZipfile,StandardCopyOption.REPLACE_EXISTING);
	    		return true;
	        }catch (Exception e) {
	        	return false;
	    	}
         }
	    
	    public static boolean deleteFile(String pathname){
	      boolean result = false;
	      File file = new File(pathname);
	      if (file.exists())
	      {
	        file.delete();
	        result = true;
	        log.info("文件已经被成功删除");
	      }
	      return result;
	    }
	    
	    /**
	     * @param path   要压缩的文件路径
	     * @param format 生成的格式(zip、rar)d
	     */
	    public static String generateFile(String path, String format) throws Exception {

	        File file = new File(path);
	        // 压缩文件的路径不存在
	        if (!file.exists()) {
	            throw new Exception("路径 " + path + " 不存在文件,无法进行压缩...");
	        }
	        // 用于存放压缩文件的文件夹
	        //String generateFile = file.getParent() + File.separator +"CompressFile";
	        String generateFile = file.getParent() + File.separator ;
	        File compress = new File(generateFile);
	        // 如果文件夹不存在,进行创建
	        if( !compress.exists() ){
	            compress.mkdirs();
	        }

	        // 目的压缩文件
	       // String generateFileName = compress.getAbsolutePath() + File.separator + "AAA" + file.getName() + "." + format;
	        String generateFileName = compress.getAbsolutePath() + File.separator +  file.getName() + "." + format;

	        // 输入流 表示从一个源读取数据
	        // 输出流 表示向一个目标写入数据

	        // 输出流
	        FileOutputStream outputStream = new FileOutputStream(generateFileName);

	        // 压缩输出流
	        ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream));

	        generateFile(zipOutputStream,file,"");

	      //  System.out.println("源文件位置:" + file.getAbsolutePath() + ",目的压缩文件生成位置:" + generateFileName);
	       
	        log.info("源文件位置:" + file.getAbsolutePath() + ",目的压缩文件生成位置:" + generateFileName);// 关闭 输出流
	        zipOutputStream.close();
	        return  generateFileName;
	    }
	    
	    
	    /**
	     * @param out  输出流
	     * @param file 目标文件
	     * @param dir  文件夹
	     * @throws Exception
	     */
	    private static void generateFile(ZipOutputStream out, File file, String dir) throws Exception {

	        // 当前的是文件夹,则进行一步处理
	        if (file.isDirectory()) {
	            //得到文件列表信息
	            File[] files = file.listFiles();

	            //将文件夹添加到下一级打包目录
	            out.putNextEntry(new ZipEntry(dir + "/"));

	            dir = dir.length() == 0 ? "" : dir + "/";

	            //循环将文件夹中的文件打包
	            for (int i = 0; i < files.length; i++) {
	                generateFile(out, files[i], dir + files[i].getName());
	            }

	        } else { // 当前是文件

	            // 输入流
	            FileInputStream inputStream = new FileInputStream(file);
	            // 标记要打包的条目
	            out.putNextEntry(new ZipEntry(dir));
	            // 进行写操作
	            int len = 0;
	            byte[] bytes = new byte[1024];
	            while ((len = inputStream.read(bytes)) > 0) {
	                out.write(bytes, 0, len);
	            }
	            // 关闭输入流
	            inputStream.close();
	        }

	    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值