把圖片按照規定的比例壓縮,然後保存至FTP,列表讀取縮略圖,單擊顯示原圖。
/** *?壓縮圖片方法壹(高質量) *?@param?oldFile?將要壓縮的圖片 *?@param?width?壓縮寬 *?@param?height?壓縮高 *?@param?smallIcon?壓縮圖片後,添加的擴展名(在圖片後綴名前添加) *?@param?quality?壓縮質量?範圍:<i>0.0-1.0</i>?高質量:<i>0.75</i>?中等質量:<i>0.5</i>?低質量:<i>0.25</i> *?@param?percentage?是否等比壓縮?若true寬高比率將將自動調整 */public?static?void?compressImage(String?oldFile,?int?width,?int?height,?String?smallIcon,
float?quality,?boolean?percentage)?{
try?{
File?file?=?new?File(oldFile);
//?驗證文件是否存在
if(!file.exists())
throw?new?FileNotFoundException("找不到原圖片!");
//?獲取圖片信息
BufferedImage?image?=?ImageIO.read(file);
int?orginalWidth?=?image.getWidth();
int?orginalHeight?=?image.getHeight();
//?驗證壓縮圖片信息
if?(width?<=?0?||?height?<=?0?||?!Pattern.matches("^[1-9]\\d*$",?String.valueOf(width))
||?!Pattern.matches("^[1-9]\\d*$",?String.valueOf(height)))
throw?new?Exception("圖片壓縮後的高寬有誤!");
//?等比壓縮
if?(percentage)?{
double?rate1?=?((double)?orginalWidth)?/?(double)?width?+?0.1;
double?rate2?=?((double)?orginalHeight)?/?(double)?height?+?0.1;
double?rate?=?rate1?>?rate2rate1?:?rate2;
width?=?(int)?(((double)?orginalWidth)?/?rate);
height?=?(int)?(((double)?orginalHeight)?/?rate);
}
//?壓縮後的文件名
String?filePrex?=?oldFile.substring(0,?oldFile.lastIndexOf('.'));
String?newImage?=?filePrex?+?smallIcon?+?oldFile.substring(filePrex.length());
//?壓縮文件存放位置
File?savedFile?=?new?File(newImage);
//?創建壹個新的文件
savedFile.createNewFile();
//?創建原圖像的縮放版本
Image?image2?=?image.getScaledInstance(width,?height,?Image.SCALE_AREA_AVERAGING);
//?創建數據緩沖區圖像
BufferedImage?bufImage?=?new?BufferedImage(width,?height,?BufferedImage.TYPE_INT_RGB);
//?創建壹個Graphics2D
Graphics2D?g2?=?bufImage.createGraphics();
//?重繪圖像
g2.drawImage(image2,?0,?0,?width,?height,?null);
g2.dispose();
//?過濾像素矩陣
float[]?kernelData?=?{?
-0.125f,?-0.125f,?-0.125f,?
-0.125f,?2,?-0.125f,?-0.125f,?
-0.125f,?-0.125f?};
Kernel?kernel?=?new?Kernel(3,?3,?kernelData);
//?按核數學源圖像邊緣的像素復制為目標中相應的像素輸出像素
ConvolveOp?cOp?=?new?ConvolveOp(kernel,?ConvolveOp.EDGE_NO_OP,?null);
//?轉換像素
bufImage?=?cOp.filter(bufImage,?null);
FileOutputStream?out?=?new?FileOutputStream(savedFile);
JPEGImageEncoder?encoder?=?JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam?param?=?encoder.getDefaultJPEGEncodeParam(bufImage);
//?設置壓縮質量
param.setQuality(quality,?true);
encoder.encode(bufImage,?param);
out.close();
System.out.println(newImage);
}?catch?(Exception?e)?{
e.printStackTrace();
System.out.println("壓縮失敗!"?+?e.getMessage());
}
}