国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java實現圖片壓縮的思路與代碼

2019-11-26 14:29:14
字體:
來源:轉載
供稿:網友

本文實例為大家分享了java實現圖片壓縮的相關代碼,供大家參考,具體內容如下

import java.awt.Image;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream; import javax.imageio.ImageIO; public class ImageProcess { /**  * 圖片  */ private Image img;  /**  * 寬度  */ private int width;  /**  * 高度  */ private int height;  /**  * 文件格式  */ private String imageFormat; /**   * 構造函數   * @throws Exception   */  public ImageProcess(InputStream in,String fileName) throws Exception{    //構造Image對象    img = ImageIO.read(in);    //得到源圖寬    width = img.getWidth(null);   //得到源圖長    height = img.getHeight(null);   //文件格式   imageFormat = fileName.substring(fileName.lastIndexOf(".")+1); }  /**   * 按照寬度還是高度進行壓縮   * @param w int 最大寬度   * @param h int 最大高度   */  public byte[] resizeFix(int w, int h) throws IOException {    if (width / height > w / h) {      return resizeByWidth(w);    } else {      return resizeByHeight(h);    }  }  /**   * 以寬度為基準,等比例放縮圖片   * @param w int 新寬度   */  public byte[] resizeByWidth(int w) throws IOException {    int h = (int) (height * w / width);    return resize(w, h);  }  /**   * 以高度為基準,等比例縮放圖片   * @param h int 新高度   */  public byte[] resizeByHeight(int h) throws IOException {    int w = (int) (width * h / height);    return resize(w, h);  }  /**   * 強制壓縮/放大圖片到固定的大小   * @param w int 新寬度   * @param h int 新高度   */  public byte[] resize(int w, int h) throws IOException {    // SCALE_SMOOTH 的縮略算法 生成縮略圖片的平滑度的 優先級比速度高 生成的圖片質量比較好 但速度慢    BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB );     image.getGraphics().drawImage(img, 0, 0, w, h, null); // 繪制縮小后的圖    ByteArrayOutputStream baos = new ByteArrayOutputStream();   ImageIO.write(image, imageFormat, baos);   return baos.toByteArray(); } }

以上就是本文的全部內容,希望對大家的學習有所幫助,輕松實現圖片壓縮操作。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 贵定县| 德格县| 松阳县| 石林| 监利县| 阿瓦提县| 钟山县| 龙门县| 东辽县| 长垣县| 三亚市| 元阳县| 临澧县| 都江堰市| 永和县| 松原市| 凭祥市| 吴川市| 新昌县| 安图县| 保德县| 克拉玛依市| 南澳县| 晋中市| 韶关市| 宜春市| 龙胜| 海宁市| 沧源| 平乐县| 巴彦淖尔市| 太白县| 蓬溪县| 河北省| 东海县| 平潭县| 邓州市| 贡觉县| 新绛县| 涟水县| 徐州市|