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

import java.awt.image.RenderedImage;
import java.awt.image.renderable.ParameterBlock;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import javax.media.jai.InterpolationNearest;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;

import org.apache.log4j.Logger;

import com.sun.media.jai.codec.ByteArraySeekableStream;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageEncoder;
import com.sun.media.jai.codec.JPEGEncodeParam;
import com.sun.media.jai.codec.SeekableStream;
import com.sun.media.jai.codec.TIFFDirectory;

/**
 * @author 
 *
 */
public class IdepUtil {
    private static Logger logger = Logger.getLogger(IdepUtil.class);
    static final int BUFFER = 2048;
    public IdepUtil(){}
    public static String serializer(Object ob) throws Exception{//图片序列化
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(ob);  
        String serStr = byteArrayOutputStream.toString("ISO-8859-1");
        serStr = java.net.URLEncoder.encode(serStr, "UTF-8");
        
        objectOutputStream.close();
        byteArrayOutputStream.close();
        return serStr;
    }
    

    public static Object unSerializer(String xml) throws Exception{//反序列化
        String redStr = java.net.URLDecoder.decode(xml, "UTF-8");
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(redStr.getBytes("ISO-8859-1"));
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); 
        Object ob = objectInputStream.readObject(); 
        objectInputStream.close();
        byteArrayInputStream.close();
        return ob;
    }
    
    @SuppressWarnings("unchecked")
    public static Map<String,String> zipSerializer(String zipPath) throws Exception{//压缩文件序列化
        File file = new File(zipPath);
        ZipFile zip = new ZipFile(file); 
        Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>)zip.entries(); 
        Map<String,String> map = new HashMap<String,String>();
        while(entries.hasMoreElements()){
            ZipEntry entry = entries.nextElement();  
            String entryName = entry.getName();
            //将名称统一化
            String newStr = entryName.replaceAll("^(0+)", "");
            String regEx="[^0-9]";   
            Pattern p = Pattern.compile(regEx);   
            Matcher m = p.matcher(newStr);
            String finName = m.replaceAll("").trim()+".tif";
            
            InputStream inputStream = zip.getInputStream(entry);
            
            ByteArrayOutputStream out=new ByteArrayOutputStream();
            byte[] buffer=new byte[1024*4];
            int n=0;
            while ( (n=inputStream.read(buffer)) !=-1) {
                out.write(buffer,0,n);
            }
//            byte[] b = out.toByteArray();
            byte[] b = tifToJpg(out.toByteArray());//可以换tiffToPng这个方法
            
//            String s = IdepUtil.serializer(b);
            String s = byte2hex(b);
            
            map.put(finName, s);
            out.close();
            inputStream.close();
//            System.out.println(s);
        }
        return map;
    }
    
    /** tif格式压缩转换为jpg格式压缩
     * @param zipPath
     * @return
     * @throws Exception
     */
    public static byte[] zipTifToJpg(String zipPath) throws Exception{
        File file = new File(zipPath);
        ZipFile zip = new ZipFile(file); 
        Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>)zip.entries(); 
        List<byte[]> list = new ArrayList<byte[]>();
        while(entries.hasMoreElements()){
            ZipEntry entry = entries.nextElement();  
            String entryName = entry.getName();
            System.out.println("entryName===="+entryName);//本地测试时添加,记得删除
            InputStream inputStream = zip.getInputStream(entry);
            
            ByteArrayOutputStream out=new ByteArrayOutputStream();
            byte[] buffer=new byte[1024*4];
            int n=0;
            while ( (n=inputStream.read(buffer)) !=-1) {
                out.write(buffer,0,n);
            }
//            byte[] b = out.toByteArray();
            out.flush();
            byte[] b = tiffToPng(out.toByteArray());
            list.add(b);
            out.close();
            inputStream.close();
//            System.out.println(s);
        }
        
        return toZip(list);
    }
     /**
      * 打zip包
     * @param fileName
     * @param FilePath
     * @return
     * @throws IOException 
     */
    public static byte[] toZip(List<byte[]> list) throws IOException {
        logger.info("开始将tif压缩成zip");
            ByteArrayOutputStream out=new ByteArrayOutputStream();
            ZipOutputStream zo = new ZipOutputStream(out);
            byte[] b = null;
            if(list!=null&&list.size()>0){
                for(int i=0; i<list.size(); i++){
                    zo.putNextEntry(new ZipEntry(i+""));
                    zo.write(list.get(i));
                    zo.flush();
                }
                zo.close();
                b = out.toByteArray();
            }
            out.close();
        logger.info("结束将tif压缩成zip");
        return b;
    }
    /**
     * tiff2png
     * @param b
     * @return
     * @throws IOException
     */
    public static byte[] tiffToPng(byte[] imgData) throws Exception {
        byte[] rev = null;
        
        int TAG_COMPRESSION = 259;
        int TAG_JPEG_INTERCHANGE_FORMAT = 513;
        int COMP_JPEG_OLD = 6;

        SeekableStream stream = new ByteArraySeekableStream(imgData);
        TIFFDirectory tdir = new TIFFDirectory(stream, 0);
        int compression = tdir.getField(TAG_COMPRESSION).getAsInt(0);

        // Decoder name
        String decoder2use = "tiff";
        boolean needResize = false;
        if (COMP_JPEG_OLD == compression) {
            stream.seek(tdir.getField(TAG_JPEG_INTERCHANGE_FORMAT).getAsLong(0));
            decoder2use = "jpeg";
            needResize = true;
        }

        // Decode image
        ImageDecoder dec = ImageCodec.createImageDecoder(decoder2use, stream, null);
        RenderedImage img = dec.decodeAsRenderedImage();

        if (needResize) {
            ParameterBlock params = new ParameterBlock();
            params.addSource(img);
            params.add(0.35F); // x scale factor
            params.add(0.35F); // y scale factor
            params.add(0.0F); // x translate
            params.add(0.0F); // y translate
            params.add(new InterpolationNearest());
            img = JAI.create("scale", params, null);
        }
        
        ByteArrayOutputStream fileOut=new ByteArrayOutputStream();
        ImageEncoder pngEncoder = ImageCodec.createImageEncoder("png", fileOut, null);
        pngEncoder.encode(img);
        stream.close();
        rev = fileOut.toByteArray();
        fileOut.close();
        return rev;
    }
    
    public static byte[] tifToJpg(byte[] b) throws IOException{
        SeekableStream stream = new ByteArraySeekableStream(b);            
           PlanarImage in = JAI.create("stream", stream);          
//           OutputStream os = null;  
//           os = new FileOutputStream(output);  
           ByteArrayOutputStream os = new ByteArrayOutputStream();
           JPEGEncodeParam param = new JPEGEncodeParam();   
           byte[] ret = null;
           ImageEncoder enc = ImageCodec.createImageEncoder("JPEG", os, param);  
           try {  
               enc.encode(in);                  
               os.flush();  
               ret = os.toByteArray();
               os.close();   
               stream.close();  
           } catch (IOException e) {    
               e.printStackTrace();
           } 
           return ret;
    }
    
    private static String byte2hex(byte[] b){  // 二进制转字符串
       StringBuffer sb = new StringBuffer();  
       String stmp = "";  
       for (int n = 0; n < b.length; n++) {  
            stmp = Integer.toHexString(b[n] & 0XFF);  
            if (stmp.length() == 1){  
                sb.append("0" + stmp);  
            }else{  
                sb.append(stmp);  
            }  
       }  
       return sb.toString();  
    }  
    
    /**
     * 
     * @param bzip
     * @param outputDirectory
     * @return
     * @throws Exception
     */
    private static int unzip(byte[] bzip, String outputDirectory) throws Exception {
        ByteArrayInputStream s = new ByteArrayInputStream(bzip);
        ZipInputStream inputStream = new ZipInputStream(s); 
        BufferedInputStream Bin=new BufferedInputStream(inputStream);//新加
        int i=0;
        ZipEntry zipEntry = null;
        FileOutputStream outputStream = null;
        try {
            while ((zipEntry = inputStream.getNextEntry()) != null) {
                if (zipEntry.isDirectory()) {
                    String name = zipEntry.getName();
                    name = name.substring(0, name.length() - 1);
                    File file = new File(outputDirectory + File.separator
                            + name);
                    file.mkdir();
                } else {
                    File file = new File(outputDirectory + File.separator
                            + i+".jpg");
                    file.createNewFile();
                    outputStream = new FileOutputStream(file);
                    BufferedOutputStream Bout=new BufferedOutputStream(outputStream); 
                    int b;
                    while ((b = Bin.read()) != -1) {
                        Bout.write(b);
                    }
                    outputStream.flush();
                    Bout.flush();
                    Bout.close();
                    outputStream.close();
                }
                i++;
            }
        } catch (IOException ex) {
        } finally {
            //outputStream.flush();
            Bin.close();
            inputStream.close();
            s.close();
        }
        return i;
    }
    /**
     * 字符串转二进制
     */
    private  byte[] hex2byte(String str) { // 字符串转二进制  
        if (str == null)  return null;  
        str = str.trim();  
        int len = str.length();  
        if (len == 0 || len % 2 == 1)  
         return null;  
        byte[] b = new byte[len / 2];  
        try {  
         for (int i = 0; i < str.length(); i += 2) {  
          b[i / 2] = (byte) Integer.decode("0X" + str.substring(i, i + 2)).intValue();  
         }  
         return b;  
        } catch (Exception e) {  
         return null;
        }  
    }
    /**
     * 格式化时间
     * @param strDate
     * @return
     * @throws ParseException
     */
    public static java.lang.String format2Date(Date date) throws ParseException {
        java.lang.String d = null;
        try {
            d =new SimpleDateFormat("yyyyMMdd").format(date);
        } catch (Exception e) {
            try {
                d = new SimpleDateFormat("yyyyMM").format(date);
            } catch (Exception e1) {
                d = new SimpleDateFormat("yyyy").format(date);
            }
        }
        return d;
    }
        
    }

}

评论

暂无评论