這里使用了java的javax.imageio.ImageIO類,對于不同圖片的支持擴展,在java的擴展包里面:
com.sun.imageio.plugins.XXX, 其中XXX為圖片格式,目前默認支持jpg,bmp,gif,png和wbmp格式,各種圖片處理擴展類可以通過IIORegistry進行注冊,在解析過程中,ImageIO會根據(jù)不同的格式類型尋找匹配的解析類,當然這些不需要我們?nèi)プ?,下面是縮小圖片的代碼
/**
* <p>縮小圖片。</p>
* @author 劉建峰
* @param img 原始圖片
* @param formatName 圖片類型
* @param out 輸出流
* @param length 圖片長都
* @throws ImageFormatException
* @throws IOException
*/
resizeImage(Image img, String formatName,
OutputStream out, long length) throws ImageFormatException, IOException {
if (StringUtils.isEmpty(formatName)) {
return;
}
int oldWidth = img.getWidth(null);
int oldHeight = img.getHeight(null);
int newWidth = oldWidth;
int newHeight = oldHeight;
if (length > maxImageSize) {//需要對圖片進行縮放,計算新圖片的大小
BigDecimal scale = BigDecimal.valueOf(maxImageSize).divide(
BigDecimal.valueOf(length), 3, BigDecimal.ROUND_DOWN);
scale = BigDecimal.valueOf(Math.sqrt(scale.doubleValue()));
newWidth = BigDecimal.valueOf(newWidth).multiply(scale).intValue();
newHeight = BigDecimal.valueOf(newHeight).multiply(scale).intValue();
}
BufferedImage newImage = new BufferedImage(newWidth, newHeight,
BufferedImage.TYPE_INT_RGB);//構(gòu)造一個緩沖圖片對象
newImage.getGraphics().drawImage(img, 0, 0, newWidth, newHeight, null);//繪制新圖像
ImageIO.write(newImage, formatName, out);將圖形以format的格式寫入輸出流
out.close();
}