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

Wesley13
• 阅读 557
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;
    }
        
    }

}
点赞
收藏
评论区
推荐文章
待兔 待兔
2个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Wesley13 Wesley13
2年前
java8 时间类与Date类的相互转化
java8时间类与Date类的相互转化在转换中,我们需要注意,因为java8之前Date是包含日期和时间的,而LocalDate只包含日期,LocalTime只包含时间,所以与Date在互转中,势必会丢失日期或者时间,或者会使用起始时间。如果转LocalDateTime,那么就不存在信息误差。//Date与Instant的相互转化
Wesley13 Wesley13
2年前
java中的序列化方式及dubbo使用kryo序列化
java中的序列化方式:1\.自带序列化 ObjectInputSteam、ObjectOutStream等2\.hession23\.json,xml等格式4.kryo5.FST\dubbo直接多种序列化方式,默认是hession2.比较成熟,但是效率略低。可以配置使用kryo  <dubbo:
Java开发面试高频考点学习笔记(每日更新)
Java开发面试高频考点学习笔记(每日更新)1.深拷贝和浅拷贝2.接口和抽象类的区别3.java的内存是怎么分配的4.java中的泛型是什么?类型擦除是什么?5.Java中的反射是什么6.序列化与反序列化7.Object有哪些方法?8.JVM内存模型9.类加载机制10.对象的创建和对象的布局11.Java的四种引用
Wesley13 Wesley13
2年前
Java处理.tif或.tiff图片
前言Java将图片读取到内存用的是ImageIO,默认可以处理的图片格式如下:ImageIO.getWriterFileSuffixes()//此方法返回可以处理的图片格式数组jpgbmpgifpngwbmpjpeg当要处理其他图片格式时,如tif或tiff则要加入第
红烧土豆泥 红烧土豆泥
2年前
解决Redis序列化Java8的LocalDateTime问题
在从Redis获取带有LocalDateTime类型属性的对象时,产生序列化和反序列化问题解决办法方式一:实体类上指定LocalDateTime的序列化器和反序列化器java@JsonDeserialize(usingLocalDateTimeDeserializer.class)//反序列化@JsonSerialize(usingLo
Stella981 Stella981
2年前
Gson
Java对象和Json之间的互转,一般用的比较多的两个类库是Jackson和Gson,下面记录一下Gson的学习使用。基础概念: Serialization:序列化,使Java对象到Json字符串的过程。 Deserialization:反序列化,字符串转换成Java对象使用Maven管理Gson,pom.xml导入gson的依赖
Stella981 Stella981
2年前
Gson 数据解析
gson和其他现有javajson类库最大的不同时gson需要序列化的实体类不需要使用annotation来标识需要序列化的字段,同时gson又可以通过使用annotation来灵活配置需要序列化的字段。下面是一个简单的例子:1.public class Person {3.private String name;
Wesley13 Wesley13
2年前
Java序列化——transient关键字和Externalizable接口
  提到Java序列化,相信大家都不陌生。我们在序列化的时候,需要将被序列化的类实现Serializable接口,这样的类在序列化时,会默认将所有的字段都序列化。那么当我们在序列化Java对象时,如果不希望对象中某些字段被序列化(如密码字段),怎么实现呢?看一个例子:import java.io.Serializable;imp
Wesley13 Wesley13
2年前
Java并发编程:Java 序列化的工作机制
JDK内置同步器的实现类经常会看到java.io.Serializable接口,这个接口即是Java序列化操作,这样看来序列化也是同步器的一种机制。 关于序列化本文主要分析Java中的序列化机制,并看看AQS同步器的序列化,掌握序列化机制才能完整理解JDK内置的同步工具的实现。在程序中为了能直接以Java对象的形式进行保存,然后再