因開發網站上大部份的圖均是透過管理介面讓管理者自行維運,
但有些圖檔過大,
故寫了一段產生縮圖的程式以免使用開啟網頁時塞爆頻寬。
1.指定圖檔寬度 : 傳入來源檔路徑(含檔名)、目的檔路徑(含檔名)、檔案副檔名、寬度
public void change2SmallImg_w(String fromImgPath, String destImgPath, String imgType, int maxWidth) {
try {
File fiBig = new File(fromImgPath);
File foSmall = new File(destImgPath);
AffineTransform transform = new AffineTransform();
BufferedImage bis = ImageIO.read(fiBig);
//原来的高宽
int w = bis.getWidth();
int h = bis.getHeight();
//等比例缩放
int nowWidth = maxWidth;
int nowHeight = (nowWidth * h) / w;
if (nowHeight > maxWidth) {
nowHeight = maxWidth;
nowWidth = (nowHeight * w) / h;
}
double sx = (double) nowWidth / w;
double sy = (double) nowHeight / h;
transform.setToScale(sx, sy);
AffineTransformOp ato = new AffineTransformOp(transform, null);
BufferedImage bid = new BufferedImage(nowWidth, nowHeight,
(imgType.compareToIgnoreCase("png") == 0)
? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_3BYTE_BGR);
ato.filter(bis, bid);
ImageIO.write(bid, imgType, foSmall);
} catch (Exception e) {
e.printStackTrace();
}
}
2.指定圖檔高度 : 傳入來源檔路徑(含檔名)、目的檔路徑(含檔名)、檔案副檔名、高度
public void change2SmallImg_h(String fromImgPath, String destImgPath, String imgType, int maxHeight) {
try {
File fiBig = new File(fromImgPath);
File foSmall = new File(destImgPath);
AffineTransform transform = new AffineTransform();
BufferedImage bis = ImageIO.read(fiBig);
//原来的高宽
int w = bis.getWidth();
int h = bis.getHeight();
//等比例缩放
int nowHeight = maxHeight;
int nowWidth = (nowHeight * w) / h;
if (nowWidth > maxHeight) {
nowWidth = maxHeight;
nowHeight = (nowWidth * h) / w;
}
double sx = (double) nowWidth / w;
double sy = (double) nowHeight / h;
transform.setToScale(sx, sy);
AffineTransformOp ato = new AffineTransformOp(transform, null);
BufferedImage bid = new BufferedImage(nowWidth, nowHeight,
(imgType.compareToIgnoreCase("png") == 0)
? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_3BYTE_BGR);
ato.filter(bis, bid);
ImageIO.write(bid, imgType, foSmall);
} catch (Exception e) {
e.printStackTrace();
}
}
