暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Java序列化和反序列化超强工具类(包含tif图片与其他格式互转)

开发者的花花世界 2017-06-26
817
  1. /** 

  2.  * @author  

  3.  * 

  4.  */  

  5. public class IdepUtil {  

  6.     private static Logger logger = Logger.getLogger(IdepUtil.class);  

  7.     static final int BUFFER = 2048;  

  8.     public IdepUtil(){}  

  9.     public static String serializer(Object ob) throws Exception{//图片序列化  

  10.         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  

  11.         ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);  

  12.         objectOutputStream.writeObject(ob);    

  13.         String serStr = byteArrayOutputStream.toString("ISO-8859-1");  

  14.         serStr = java.net.URLEncoder.encode(serStr, "UTF-8");  

  15.           

  16.         objectOutputStream.close();  

  17.         byteArrayOutputStream.close();  

  18.         return serStr;  

  19.     }  

  20.       

  21.   

  22.     public static Object unSerializer(String xml) throws Exception{//反序列化  

  23.         String redStr = java.net.URLDecoder.decode(xml, "UTF-8");  

  24.         ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(redStr.getBytes("ISO-8859-1"));  

  25.         ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);   

  26.         Object ob = objectInputStream.readObject();   

  27.         objectInputStream.close();  

  28.         byteArrayInputStream.close();  

  29.         return ob;  

  30.     }  

  31.       

  32.     @SuppressWarnings("unchecked")  

  33.     public static Map<String,String> zipSerializer(String zipPath) throws Exception{//压缩文件序列化  

  34.         File file = new File(zipPath);  

  35.         ZipFile zip = new ZipFile(file);   

  36.         Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>)zip.entries();   

  37.         Map<String,String> map = new HashMap<String,String>();  

  38.         while(entries.hasMoreElements()){  

  39.             ZipEntry entry = entries.nextElement();    

  40.             String entryName = entry.getName();  

  41.             //将名称统一化  

  42.             String newStr = entryName.replaceAll("^(0+)""");  

  43.             String regEx="[^0-9]";     

  44.             Pattern p = Pattern.compile(regEx);     

  45.             Matcher m = p.matcher(newStr);  

  46.             String finName = m.replaceAll("").trim()+".tif";  

  47.               

  48.             InputStream inputStream = zip.getInputStream(entry);  

  49.               

  50.             ByteArrayOutputStream out=new ByteArrayOutputStream();  

  51.             byte[] buffer=new byte[1024*4];  

  52.             int n=0;  

  53.             while ( (n=inputStream.read(buffer)) !=-1) {  

  54.                 out.write(buffer,0,n);  

  55.             }  

  56. //          byte[] b = out.toByteArray();  

  57.             byte[] b = tifToJpg(out.toByteArray());//可以换tiffToPng这个方法  

  58.               

  59. //          String s = IdepUtil.serializer(b);  

  60.             String s = byte2hex(b);  

  61.               

  62.             map.put(finName, s);  

  63.             out.close();  

  64.             inputStream.close();  

  65. //          System.out.println(s);  

  66.         }  

  67.         return map;  

  68.     }  

  69.       

  70.     /** tif格式压缩转换为jpg格式压缩 

  71.      * @param zipPath 

  72.      * @return 

  73.      * @throws Exception 

  74.      */  

  75.     public static byte[] zipTifToJpg(String zipPath) throws Exception{  

  76.         File file = new File(zipPath);  

  77.         ZipFile zip = new ZipFile(file);   

  78.         Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>)zip.entries();   

  79.         List<byte[]> list = new ArrayList<byte[]>();  

  80.         while(entries.hasMoreElements()){  

  81.             ZipEntry entry = entries.nextElement();    

  82.             String entryName = entry.getName();  

  83.             System.out.println("entryName===="+entryName);//本地测试时添加,记得删除  

  84.             InputStream inputStream = zip.getInputStream(entry);  

  85.               

  86.             ByteArrayOutputStream out=new ByteArrayOutputStream();  

  87.             byte[] buffer=new byte[1024*4];  

  88.             int n=0;  

  89.             while ( (n=inputStream.read(buffer)) !=-1) {  

  90.                 out.write(buffer,0,n);  

  91.             }  

  92. //          byte[] b = out.toByteArray();  

  93.             out.flush();  

  94.             byte[] b = tiffToPng(out.toByteArray());  

  95.             list.add(b);  

  96.             out.close();  

  97.             inputStream.close();  

  98. //          System.out.println(s);  

  99.         }  

  100.           

  101.         return toZip(list);  

  102.     }  

  103.      /** 

  104.       * 打zip包 

  105.      * @param fileName 

  106.      * @param FilePath 

  107.      * @return 

  108.      * @throws IOException  

  109.      */  

  110.     public static byte[] toZip(List<byte[]> list) throws IOException {  

  111.         logger.info("开始将tif压缩成zip");  

  112.             ByteArrayOutputStream out=new ByteArrayOutputStream();  

  113.             ZipOutputStream zo = new ZipOutputStream(out);  

  114.             byte[] b = null;  

  115.             if(list!=null&&list.size()>0){  

  116.                 for(int i=0; i<list.size(); i++){  

  117.                     zo.putNextEntry(new ZipEntry(i+""));  

  118.                     zo.write(list.get(i));  

  119.                     zo.flush();  

  120.                 }  

  121.                 zo.close();  

  122.                 b = out.toByteArray();  

  123.             }  

  124.             out.close();  

  125.         logger.info("结束将tif压缩成zip");  

  126.         return b;  

  127.     }  

  128.     /** 

  129.      * tiff2png 

  130.      * @param b 

  131.      * @return 

  132.      * @throws IOException 

  133.      */  

  134.     public static byte[] tiffToPng(byte[] imgData) throws Exception {  

  135.         byte[] rev = null;  

  136.           

  137.         int TAG_COMPRESSION = 259;  

  138.         int TAG_JPEG_INTERCHANGE_FORMAT = 513;  

  139.         int COMP_JPEG_OLD = 6;  

  140.   

  141.         SeekableStream stream = new ByteArraySeekableStream(imgData);  

  142.         TIFFDirectory tdir = new TIFFDirectory(stream, 0);  

  143.         int compression = tdir.getField(TAG_COMPRESSION).getAsInt(0);  

  144.   

  145.         // Decoder name  

  146.         String decoder2use = "tiff";  

  147.         boolean needResize = false;  

  148.         if (COMP_JPEG_OLD == compression) {  

  149.             stream.seek(tdir.getField(TAG_JPEG_INTERCHANGE_FORMAT).getAsLong(0));  

  150.             decoder2use = "jpeg";  

  151.             needResize = true;  

  152.         }  

  153.   

  154.         // Decode image  

  155.         ImageDecoder dec = ImageCodec.createImageDecoder(decoder2use, stream, null);  

  156.         RenderedImage img = dec.decodeAsRenderedImage();  

  157.   

  158.         if (needResize) {  

  159.             ParameterBlock params = new ParameterBlock();  

  160.             params.addSource(img);  

  161.             params.add(0.35F); // x scale factor  

  162.             params.add(0.35F); // y scale factor  

  163.             params.add(0.0F); // x translate  

  164.             params.add(0.0F); // y translate  

  165.             params.add(new InterpolationNearest());  

  166.             img = JAI.create("scale", params, null);  

  167.         }  

  168.           

  169.         ByteArrayOutputStream fileOut=new ByteArrayOutputStream();  

  170.         ImageEncoder pngEncoder = ImageCodec.createImageEncoder("png", fileOut, null);  

  171.         pngEncoder.encode(img);  

  172.         stream.close();  

  173.         rev = fileOut.toByteArray();  

  174.         fileOut.close();  

  175.         return rev;  

  176.     }  

  177.       

  178.     public static byte[] tifToJpg(byte[] b) throws IOException{  

  179.         SeekableStream stream = new ByteArraySeekableStream(b);              

  180.            PlanarImage in = JAI.create("stream", stream);            

  181. //         OutputStream os = null;    

  182. //         os = new FileOutputStream(output);    

  183.            ByteArrayOutputStream os = new ByteArrayOutputStream();  

  184.            JPEGEncodeParam param = new JPEGEncodeParam();     

  185.            byte[] ret = null;  

  186.            ImageEncoder enc = ImageCodec.createImageEncoder("JPEG", os, param);    

  187.            try {    

  188.                enc.encode(in);                    

  189.                os.flush();    

  190.                ret = os.toByteArray();  

  191.                os.close();     

  192.                stream.close();    

  193.            } catch (IOException e) {      

  194.                e.printStackTrace();  

  195.            }   

  196.            return ret;  

  197.     }  

  198.       

  199.     private static String byte2hex(byte[] b){  // 二进制转字符串  

  200.        StringBuffer sb = new StringBuffer();    

  201.        String stmp = "";    

  202.        for (int n = 0; n < b.length; n++) {    

  203.             stmp = Integer.toHexString(b[n] & 0XFF);    

  204.             if (stmp.length() == 1){    

  205.                 sb.append("0" + stmp);    

  206.             }else{    

  207.                 sb.append(stmp);    

  208.             }    

  209.        }    

  210.        return sb.toString();    

  211.     }    




文章转载自开发者的花花世界,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论