其实若是是操做某些非公开的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()); } } }