其實若是是操做某些非公開的JDK API的話,會出現這些問題,能夠使用上述的解決方案,可是建議使用其餘的方案代替,例以下例所給出的解決方案,用scaleImage2 代替 scaleImage 不使用受保護的方法 java
package com.zy.common.util; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import javax.imageio.ImageIO; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGEncodeParam; import com.sun.image.codec.jpeg.JPEGImageEncoder; public class ImagesUtil { /** * 縮略圖片 * @param oldpath 原圖片 * @param newpath 新生成的圖片存放地址 * @param wdith 縮略後的寬 * @param height 縮略後的高 */ public static void scaleImage(String oldpath, String newpath, int wdith, int height) { // 獲取老的圖片 File oldimg = new File(oldpath); try { BufferedImage bi = ImageIO.read(oldimg); Image Itemp = bi.getScaledInstance(wdith, height, BufferedImage.SCALE_SMOOTH); BufferedImage thumbnail = new BufferedImage(wdith, height, BufferedImage.TYPE_INT_RGB); thumbnail.getGraphics().drawImage(Itemp, 0, 0, null); // 縮略後的圖片路徑 File newimg = new File(newpath); //FileOutputStream out = new FileOutputStream(newimg); // 繪圖 //JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); //JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbnail); //param.setQuality(1.0f, false); //encoder.encode(thumbnail); //out.close(); String formatName = newpath.substring(newpath.lastIndexOf(".") + 1); ImageIO.write(thumbnail, formatName , new File(newpath) ); bi.flush(); bi = null; } catch (IOException e) { System.out.println(e.getStackTrace()); } } /** * 縮略圖片 * @param oldpath 原圖片 * @param newpath 新生成的圖片存放地址 * @param wdith 縮略後的寬 * @param height 縮略後的高 */ public static void scaleImage2(String oldpath, String newpath, int wdith, int height) { // 獲取老的圖片 File oldimg = new File(oldpath); try { BufferedImage bi = ImageIO.read(oldimg); Image Itemp = bi.getScaledInstance(wdith, height, BufferedImage.SCALE_SMOOTH); BufferedImage thumbnail = new BufferedImage(wdith, height, BufferedImage.TYPE_INT_RGB); thumbnail.getGraphics().drawImage(Itemp, 0, 0, null); // 縮略後的圖片路徑 File newimg = new File(newpath); FileOutputStream out = new FileOutputStream(newimg); // 繪圖 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbnail); param.setQuality(1.0f, false); encoder.encode(thumbnail); out.close(); bi.flush(); bi = null; } catch (IOException e) { System.out.println(e.getStackTrace()); } } }