赞
踩
需要jai_core.jar和jai_codec.jar包
实现格式转换,但此方法中的RenderedOp资源不能释放,生成之后原图不能删除;
- public class ImgCast {
- public static void main(String[] args) {
- /* tif转换到jpg格式 */
- try {
- String input2 = "F:/T20150120002001001.jpg";
- String output2 = "F:/T20150120002001001_01.jpg";
- RenderedOp src2 = JAI.create("fileload", input2);
- OutputStream os2 = new FileOutputStream(output2);
- JPEGEncodeParam param2 = new JPEGEncodeParam();
- //指定格式类型,jpg 属于 JPEG 类型
- ImageEncoder enc2 = ImageCodec.createImageEncoder("JPEG", os2, param2);
- enc2.encode(src2);
- os2.close();
-
- /*tif转换到bmp格式*/
- String inputFile = "F:/T20150120002001001.jpg";
- String outputFile = "F:/T20150120002001001_01.bmp";
- RenderedOp src = JAI.create("fileload", inputFile);
- OutputStream os = new FileOutputStream(outputFile);
- BMPEncodeParam param = new BMPEncodeParam();
- ImageEncoder enc = ImageCodec.createImageEncoder("BMP", os,param);
- enc.encode(src);
- os.close();//关闭流
-
- //其他的一样的方式转换 ...
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
下面第一种情况是用上面的方法,但不能删除,第二种情况是另一种方法,没有资源不能释放被占用情况
第一种情况:(不能释放,删除)
- // 强制将图片转成JPEG
- String input = sourcePath + File.separator + fileName;
- String output = sourcePath + File.separator + fileName.replace(".", "_01.");
- File inputFile = new File(input);
- File outputFile = new File(output);
- //使用RenderedOp后src资源一直存在,input的文件始终删不掉
- RenderedOp src = JAI.create("fileload", input);
- OutputStream os = new FileOutputStream(output);
- JPEGEncodeParam param = new JPEGEncodeParam();
- ImageEncoder enc = ImageCodec.createImageEncoder("JPEG", os, param);
- src.dispose();
- src.removeSources();
- enc.encode(src);
- os.flush();
- os.close();
- src.removeSinks();
- // 强制将图片转成JPEG
- String input = sourcePath + File.separator + fileName;
- String output = sourcePath + File.separator + fileName.replace(".", "_01.");
- FileSeekableStream stream = new FileSeekableStream(input);
- PlanarImage in = JAI.create("stream", stream);
- OutputStream os = null;
- os = new FileOutputStream(output);
- JPEGEncodeParam param = new JPEGEncodeParam();
- ImageEncoder enc = ImageCodec.createImageEncoder("JPEG", os, param);
- try {
- enc.encode(in);
- os.flush();
- os.close();
- stream.close();
- } catch (IOException e) {
- Constant.bLog.error("JPEG error"+e.toString());
- }
- //删除源文件
- FileUtils.forceDelete(new File(input));
- //将新生成的文件名字改为原始文件名
- File sFile = new File(input);
- if(!sFile.exists()){
- File fDest = new File(output);
- fDest.renameTo(new File(input));
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。