Java 压缩图片
来源:互联网 发布:cf软件制作 编辑:程序博客网 时间:2024/05/29 02:58
/** * 压缩图片方法 * * @param oldFile * 将要压缩的图片 * @param width * 压缩宽 * @param height * 压缩高 * @param quality * 压缩清晰度 <b>建议为1.0</b> * @param smallIcon * 压缩图片后,添加的扩展名(在图片后缀名前添加) * @param percentage * 是否等比压缩 若true宽高比率将将自动调整 * @author slzs * @return 如果处理正确返回压缩后的文件名 null则参数可能有误 */public static String doCompress(String oldFile, int width, int height, float quality, String smallIcon, boolean percentage) {if (oldFile != null && width > 0 && height > 0) {Image srcFile = null;String newImage = null;try {File file = new File(oldFile);// 文件不存在if (!file.exists()) {return null;}/* 读取图片信息 */srcFile = ImageIO.read(file);if(srcFile == null){return null;}int new_w = width;int new_h = height;if (percentage) {// 为等比缩放计算输出的图片宽度及高度double rate1 = ((double) srcFile.getWidth(null)) / (double) width + 0.1;double rate2 = ((double) srcFile.getHeight(null)) / (double) height + 0.1;double rate = rate1 > rate2 ? rate1 : rate2;new_w = (int) (((double) srcFile.getWidth(null)) / rate);new_h = (int) (((double) srcFile.getHeight(null)) / rate);}/* 宽高设定 */BufferedImage tag = new BufferedImage(new_w, new_h, BufferedImage.TYPE_INT_RGB);tag.getColorModel();tag.getGraphics().drawImage(srcFile, 0, 0, new_w, new_h,Color.white,null);/* 压缩后的文件名 */String filePrex = oldFile.substring(0, oldFile.lastIndexOf('.'));newImage = filePrex + smallIcon + oldFile.substring(filePrex.length());/* 压缩之后临时存放位置 */FileOutputStream out = new FileOutputStream(newImage);JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);/* 压缩质量 */jep.setQuality(quality, true);encoder.encode(tag, jep);out.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if(srcFile != null){srcFile.flush();}}return newImage;} else {return null;}}
ImageUtils.doCompress("h:/_test/123.jpg", 500, 500, 2, "_small", false);
- java 压缩图片 实例
- Java 图片压缩
- java图片压缩
- java图片压缩
- java图片压缩、解压缩
- JAVA 图片压缩
- java 图片压缩
- java 剪切 压缩 图片
- Java图片压缩处理
- java--图片水印、压缩
- Java 压缩图片
- java 图片压缩 缩放
- Java 压缩图片
- java图片压缩
- java处理压缩图片
- java图片压缩
- Java压缩图片
- java 压缩图片实例
- 【ios开发】文件管理总结
- 全局变量、extern/static/const区别与联系
- C#编程入门,C#中控件(textBox、checkBox、listBox、listView等等)的应用
- 我们的管理:部门管理
- Android 新API 之 MediaCodec使用笔记 <一>
- Java 压缩图片
- QDateTime类参考
- Android屏幕适配原理
- Sent mail -Shell:Mark 一下。
- 点分十进制IP和长整型转换
- gcc中的环境变量
- Unity3d webplayer连接Sokcet服务器
- 黑马程序员_字符串
- Struts2+Spring3+Mybatis3开发环境搭建