1import java.awt.image.RenderedImage; 2import java.awt.image.renderable.ParameterBlock; 3import java.io.BufferedInputStream; 4import java.io.BufferedOutputStream; 5import java.io.ByteArrayInputStream; 6import java.io.ByteArrayOutputStream; 7import java.io.File; 8import java.io.FileOutputStream; 9import java.io.IOException; 10import java.io.InputStream; 11import java.io.ObjectInputStream; 12import java.io.ObjectOutputStream; 13import java.sql.Timestamp; 14import java.text.ParseException; 15import java.text.SimpleDateFormat; 16import java.util.ArrayList; 17import java.util.Date; 18import java.util.Enumeration; 19import java.util.HashMap; 20import java.util.List; 21import java.util.Map; 22import java.util.regex.Matcher; 23import java.util.regex.Pattern; 24import java.util.zip.ZipEntry; 25import java.util.zip.ZipFile; 26import java.util.zip.ZipInputStream; 27import java.util.zip.ZipOutputStream; 28 29import javax.media.jai.InterpolationNearest; 30import javax.media.jai.JAI; 31import javax.media.jai.PlanarImage; 32 33import org.apache.log4j.Logger; 34 35import com.sun.media.jai.codec.ByteArraySeekableStream; 36import com.sun.media.jai.codec.ImageCodec; 37import com.sun.media.jai.codec.ImageDecoder; 38import com.sun.media.jai.codec.ImageEncoder; 39import com.sun.media.jai.codec.JPEGEncodeParam; 40import com.sun.media.jai.codec.SeekableStream; 41import com.sun.media.jai.codec.TIFFDirectory; 42 43/** 44 * @author 45 * 46 */ 47public class IdepUtil { 48 private static Logger logger = Logger.getLogger(IdepUtil.class); 49 static final int BUFFER = 2048; 50 public IdepUtil(){} 51 public static String serializer(Object ob) throws Exception{//图片序列化 52 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 53 ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); 54 objectOutputStream.writeObject(ob); 55 String serStr = byteArrayOutputStream.toString("ISO-8859-1"); 56 serStr = java.net.URLEncoder.encode(serStr, "UTF-8"); 57 58 objectOutputStream.close(); 59 byteArrayOutputStream.close(); 60 return serStr; 61 } 62 63 64 public static Object unSerializer(String xml) throws Exception{//反序列化 65 String redStr = java.net.URLDecoder.decode(xml, "UTF-8"); 66 ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(redStr.getBytes("ISO-8859-1")); 67 ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); 68 Object ob = objectInputStream.readObject(); 69 objectInputStream.close(); 70 byteArrayInputStream.close(); 71 return ob; 72 } 73 74 @SuppressWarnings("unchecked") 75 public static Map<String,String> zipSerializer(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 Map<String,String> map = new HashMap<String,String>(); 80 while(entries.hasMoreElements()){ 81 ZipEntry entry = entries.nextElement(); 82 String entryName = entry.getName(); 83 //将名称统一化 84 String newStr = entryName.replaceAll("^(0+)", ""); 85 String regEx="[^0-9]"; 86 Pattern p = Pattern.compile(regEx); 87 Matcher m = p.matcher(newStr); 88 String finName = m.replaceAll("").trim()+".tif"; 89 90 InputStream inputStream = zip.getInputStream(entry); 91 92 ByteArrayOutputStream out=new ByteArrayOutputStream(); 93 byte[] buffer=new byte[1024*4]; 94 int n=0; 95 while ( (n=inputStream.read(buffer)) !=-1) { 96 out.write(buffer,0,n); 97 } 98// byte[] b = out.toByteArray(); 99 byte[] b = tifToJpg(out.toByteArray());//可以换tiffToPng这个方法 100 101// String s = IdepUtil.serializer(b); 102 String s = byte2hex(b); 103 104 map.put(finName, s); 105 out.close(); 106 inputStream.close(); 107// System.out.println(s); 108 } 109 return map; 110 } 111 112 /** tif格式压缩转换为jpg格式压缩 113 * @param zipPath 114 * @return 115 * @throws Exception 116 */ 117 public static byte[] zipTifToJpg(String zipPath) throws Exception{ 118 File file = new File(zipPath); 119 ZipFile zip = new ZipFile(file); 120 Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>)zip.entries(); 121 List<byte[]> list = new ArrayList<byte[]>(); 122 while(entries.hasMoreElements()){ 123 ZipEntry entry = entries.nextElement(); 124 String entryName = entry.getName(); 125 System.out.println("entryName===="+entryName);//本地测试时添加,记得删除 126 InputStream inputStream = zip.getInputStream(entry); 127 128 ByteArrayOutputStream out=new ByteArrayOutputStream(); 129 byte[] buffer=new byte[1024*4]; 130 int n=0; 131 while ( (n=inputStream.read(buffer)) !=-1) { 132 out.write(buffer,0,n); 133 } 134// byte[] b = out.toByteArray(); 135 out.flush(); 136 byte[] b = tiffToPng(out.toByteArray()); 137 list.add(b); 138 out.close(); 139 inputStream.close(); 140// System.out.println(s); 141 } 142 143 return toZip(list); 144 } 145 /** 146 * 打zip包 147 * @param fileName 148 * @param FilePath 149 * @return 150 * @throws IOException 151 */ 152 public static byte[] toZip(List<byte[]> list) throws IOException { 153 logger.info("开始将tif压缩成zip"); 154 ByteArrayOutputStream out=new ByteArrayOutputStream(); 155 ZipOutputStream zo = new ZipOutputStream(out); 156 byte[] b = null; 157 if(list!=null&&list.size()>0){ 158 for(int i=0; i<list.size(); i++){ 159 zo.putNextEntry(new ZipEntry(i+"")); 160 zo.write(list.get(i)); 161 zo.flush(); 162 } 163 zo.close(); 164 b = out.toByteArray(); 165 } 166 out.close(); 167 logger.info("结束将tif压缩成zip"); 168 return b; 169 } 170 /** 171 * tiff2png 172 * @param b 173 * @return 174 * @throws IOException 175 */ 176 public static byte[] tiffToPng(byte[] imgData) throws Exception { 177 byte[] rev = null; 178 179 int TAG_COMPRESSION = 259; 180 int TAG_JPEG_INTERCHANGE_FORMAT = 513; 181 int COMP_JPEG_OLD = 6; 182 183 SeekableStream stream = new ByteArraySeekableStream(imgData); 184 TIFFDirectory tdir = new TIFFDirectory(stream, 0); 185 int compression = tdir.getField(TAG_COMPRESSION).getAsInt(0); 186 187 // Decoder name 188 String decoder2use = "tiff"; 189 boolean needResize = false; 190 if (COMP_JPEG_OLD == compression) { 191 stream.seek(tdir.getField(TAG_JPEG_INTERCHANGE_FORMAT).getAsLong(0)); 192 decoder2use = "jpeg"; 193 needResize = true; 194 } 195 196 // Decode image 197 ImageDecoder dec = ImageCodec.createImageDecoder(decoder2use, stream, null); 198 RenderedImage img = dec.decodeAsRenderedImage(); 199 200 if (needResize) { 201 ParameterBlock params = new ParameterBlock(); 202 params.addSource(img); 203 params.add(0.35F); // x scale factor 204 params.add(0.35F); // y scale factor 205 params.add(0.0F); // x translate 206 params.add(0.0F); // y translate 207 params.add(new InterpolationNearest()); 208 img = JAI.create("scale", params, null); 209 } 210 211 ByteArrayOutputStream fileOut=new ByteArrayOutputStream(); 212 ImageEncoder pngEncoder = ImageCodec.createImageEncoder("png", fileOut, null); 213 pngEncoder.encode(img); 214 stream.close(); 215 rev = fileOut.toByteArray(); 216 fileOut.close(); 217 return rev; 218 } 219 220 public static byte[] tifToJpg(byte[] b) throws IOException{ 221 SeekableStream stream = new ByteArraySeekableStream(b); 222 PlanarImage in = JAI.create("stream", stream); 223// OutputStream os = null; 224// os = new FileOutputStream(output); 225 ByteArrayOutputStream os = new ByteArrayOutputStream(); 226 JPEGEncodeParam param = new JPEGEncodeParam(); 227 byte[] ret = null; 228 ImageEncoder enc = ImageCodec.createImageEncoder("JPEG", os, param); 229 try { 230 enc.encode(in); 231 os.flush(); 232 ret = os.toByteArray(); 233 os.close(); 234 stream.close(); 235 } catch (IOException e) { 236 e.printStackTrace(); 237 } 238 return ret; 239 } 240 241 private static String byte2hex(byte[] b){ // 二进制转字符串 242 StringBuffer sb = new StringBuffer(); 243 String stmp = ""; 244 for (int n = 0; n < b.length; n++) { 245 stmp = Integer.toHexString(b[n] & 0XFF); 246 if (stmp.length() == 1){ 247 sb.append("0" + stmp); 248 }else{ 249 sb.append(stmp); 250 } 251 } 252 return sb.toString(); 253 } 254 255 /** 256 * 257 * @param bzip 258 * @param outputDirectory 259 * @return 260 * @throws Exception 261 */ 262 private static int unzip(byte[] bzip, String outputDirectory) throws Exception { 263 ByteArrayInputStream s = new ByteArrayInputStream(bzip); 264 ZipInputStream inputStream = new ZipInputStream(s); 265 BufferedInputStream Bin=new BufferedInputStream(inputStream);//新加 266 int i=0; 267 ZipEntry zipEntry = null; 268 FileOutputStream outputStream = null; 269 try { 270 while ((zipEntry = inputStream.getNextEntry()) != null) { 271 if (zipEntry.isDirectory()) { 272 String name = zipEntry.getName(); 273 name = name.substring(0, name.length() - 1); 274 File file = new File(outputDirectory + File.separator 275 + name); 276 file.mkdir(); 277 } else { 278 File file = new File(outputDirectory + File.separator 279 + i+".jpg"); 280 file.createNewFile(); 281 outputStream = new FileOutputStream(file); 282 BufferedOutputStream Bout=new BufferedOutputStream(outputStream); 283 int b; 284 while ((b = Bin.read()) != -1) { 285 Bout.write(b); 286 } 287 outputStream.flush(); 288 Bout.flush(); 289 Bout.close(); 290 outputStream.close(); 291 } 292 i++; 293 } 294 } catch (IOException ex) { 295 } finally { 296 //outputStream.flush(); 297 Bin.close(); 298 inputStream.close(); 299 s.close(); 300 } 301 return i; 302 } 303 /** 304 * 字符串转二进制 305 */ 306 private byte[] hex2byte(String str) { // 字符串转二进制 307 if (str == null) return null; 308 str = str.trim(); 309 int len = str.length(); 310 if (len == 0 || len % 2 == 1) 311 return null; 312 byte[] b = new byte[len / 2]; 313 try { 314 for (int i = 0; i < str.length(); i += 2) { 315 b[i / 2] = (byte) Integer.decode("0X" + str.substring(i, i + 2)).intValue(); 316 } 317 return b; 318 } catch (Exception e) { 319 return null; 320 } 321 } 322 /** 323 * 格式化时间 324 * @param strDate 325 * @return 326 * @throws ParseException 327 */ 328 public static java.lang.String format2Date(Date date) throws ParseException { 329 java.lang.String d = null; 330 try { 331 d =new SimpleDateFormat("yyyyMMdd").format(date); 332 } catch (Exception e) { 333 try { 334 d = new SimpleDateFormat("yyyyMM").format(date); 335 } catch (Exception e1) { 336 d = new SimpleDateFormat("yyyy").format(date); 337 } 338 } 339 return d; 340 } 341 342 } 343 344}
Java序列化和反序列化超强工具类(包含tif图片与其他格式互转)
Wesley13
2021-10-11
1078 0 0
点赞
收藏
评论区
加载中...