java對圖片進行壓縮和resize縮放的方法
更新時間:2017年07月31日 10:49:16 作者:xixicat
本篇文章主要介紹了java對圖片進行壓縮和resize調整的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
序
這里展示一下如何對圖片進行壓縮和resize。分享給大家,具體如下:
壓縮
public static boolean compress(String src,String to, float quality) {
boolean rs = true;
// Build param
JPEGEncodeParam param = null;
// Build encoder
File destination = new File(to);
FileOutputStream os = null;
try {
BufferedImage image = ImageIO.read(new File(src));
param = JPEGCodec.getDefaultJPEGEncodeParam(image);
param.setQuality(quality, false);
os = FileUtils.openOutputStream(destination);
JPEGImageEncoder encoder;
if (param != null) {
encoder = JPEGCodec.createJPEGEncoder(os, param);
} else {
return false;
}
encoder.encode(image);
} catch(Exception e){
e.printStackTrace();
rs = false;
}finally {
IOUtils.closeQuietly(os);
}
return rs;
}
resize
public static boolean resize(String src,String to,int newWidth,int newHeight) {
try {
File srcFile = new File(src);
File toFile = new File(to);
BufferedImage img = ImageIO.read(srcFile);
int w = img.getWidth();
int h = img.getHeight();
BufferedImage dimg = new BufferedImage(newWidth, newHeight, img.getType());
Graphics2D g = dimg.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(img, 0, 0, newWidth, newHeight, 0, 0, w, h, null);
g.dispose();
ImageIO.write(dimg, "jpg", toFile);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
java中 String和StringBuffer的區(qū)別實例詳解
這篇文章主要介紹了java中 String和StringBuffer的區(qū)別實例詳解的相關資料,一個小的例子,來測試String和StringBuffer在時間和空間使用上的差別,需要的朋友可以參考下2017-04-04
springboot?vue接口測試定義編輯功能的實現(xiàn)
這篇文章主要為大家介紹了springboot?vue接口測試定義編輯功能的實現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05
詳解Java中ByteArray字節(jié)數(shù)組的輸入輸出流的用法
ByteArrayInputStream和ByteArrayOutputStream分別集成自InputStream和OutputStream這兩個輸入和輸出流,這里我們就來詳解Java中ByteArray字節(jié)數(shù)組的輸入輸出流的用法,需要的朋友可以參考下2016-06-06
使用Java Servlet生成動態(tài)二維碼的實現(xiàn)步驟
在現(xiàn)代互聯(lián)網時代,二維碼廣泛應用于各個領域,包括支付、認證、信息傳遞等,在Web開發(fā)中,通過Java Servlet生成動態(tài)二維碼是一個常見的需求,本文將介紹如何使用Java Servlet結合Google的ZXing庫生成動態(tài)二維碼,需要的朋友可以參考下2023-11-11
Spring Boot 2 Thymeleaf服務器端表單驗證實現(xiàn)詳解
這篇文章主要介紹了Spring Boot 2 Thymeleaf服務器端表單驗證實現(xiàn)詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-11-11
關于Spring自定義XML schema 擴展的問題(Spring面試高頻題)
今天給大家分享一道spring高頻率面試題關于Spring自定義XML schema 擴展的問題,今天以spring整合dubbo的實例給大家詳細講解下,感興趣的朋友跟隨小編一起看看吧2021-05-05
mybatis注解動態(tài)sql注入map和list方式(防sql注入攻擊)
這篇文章主要介紹了mybatis注解動態(tài)sql注入map和list方式(防sql注入攻擊),具有很好的參考價值,希望對大家有所幫助。2021-11-11

