資源簡介
實現圖片的壓縮
1.按照固定的比例縮放圖片
2.以寬度為基準等比例放縮圖片
3.以高度為基準,等比例縮放圖片
4.按照最大高度限制,生成最大的等比例縮略圖
代碼片段和文件信息
package?com.wufe.project.web.fyb.background.util;
import?java.awt.Image;
import?java.awt.image.BufferedImage;
import?java.io.File;
import?java.io.FileOutputStream;
import?java.io.IOException;
import?com.sun.image.codec.jpeg.JPEGCodec;
import?com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
?*?title:?
?*?Description:?
?*?Copyright:?Copyright?(c)2007-6-13
?*?Company:?fuen
?*?用于圖片的壓縮
?*?@author?范銀波
?*?@version?1.0
?*/
public?class?ImageCompression?{
???private?String?srcFile;
???private?String?destFile;
???private?int?width;
???private?int?height;
???private?Image?img;??
???
???
//???public?ImageCompression()
//???{
// ???
//???}
//???
//???public?ImageCompression(String?fileName)?throws?IOException
//???{
// ???
// ???compression(fileName);
//???}
//???
????
???/**
????*?構造函數
????*?@param?fileName?String
????*?@throws?IOException
????*/
????public?ImageCompression(String?fileName)?throws?IOException?{
?????File?_file?=?new?File(fileName);?//讀入文件
?????this.setSrcFile(_file.getName());
?????int?idx?=?fileName.lastIndexOf(“\\“);
?????fileName?=?fileName.substring(0?idx);
?????System.out.println(fileName);
?????System.out.println(this.srcFile);
?????this.destFile?=?fileName+“/s“+this.srcFile;//this.srcFile.substring(0?this.srcFile.lastIndexOf(“.“))?+“_s.jpg“;
?????img?=?javax.imageio.ImageIO.read(_file);?//構造Image對象
?????width?=?img.getWidth(null);?//得到源圖寬
?????height?=?img.getHeight(null);?//得到源圖長
???}??
???
???/**
????*?強制壓縮/放大圖片到固定的大小
????*?@param?w?int?新寬度
????*?@param?h?int?新高度
????*?@throws?IOException
????*/
???public?void?resize(int?w?int?h)?throws?IOException?{
?????BufferedImage?_image?=?new?BufferedImage(w?hBufferedImage.TYPE_INT_RGB);
?????_image.getGraphics().drawImage(img?0?0?w?h?null);?//繪制縮小后的圖
?????FileOutputStream?newimageout?=?new?FileOutputStream(destFile);?//輸出到文件流
?????/*
??????*?JPEGImageEncoder?將圖像緩沖數據編碼為?JPEG?數據流。該接口的用戶應在?Raster
??????*?或?BufferedImage?中提供圖像數據,在?JPEGEncodeParams?對象中設置必要的參數,
??????*?并成功地打開?OutputStream(編碼?JPEG?流的目的流)。JPEGImageEncoder?接口可
??????*?將圖像數據編碼為互換的縮略?JPEG?數據流,該數據流將寫入提供給編碼器的?OutputStream?中。
??????注意:com.sun.image.codec.jpeg?包中的類并不屬于核心?Java?API。它們屬于?Sun?發布的
??????JDK?和?JR
評論
共有 條評論