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

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

具体内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
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;
}

}

}

本作品采用知识共享署名 4.0 中国大陆许可协议进行许可,欢迎转载,但转载请注明来自御前提笔小书童,并保持转载后文章内容的完整。本人保留所有版权相关权利。

本文链接:https://royalscholar.cn/2017/04/24/Java序列化和反序列化超强工具类(包含tif图片与其他格式互转)/

# JAVA

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×