本例的错误信息为 : 程序包com.sun.image.codec.jpeg不存在
一下所引入的包也有可能会发生问题: 例如 import sun.misc.BASE64Decoder; import com.sun.image.codec.jpeg.JPEGCodec;
会发现有一些解决方案:
解决办法一:
1. Open project properties.
2. Select Java Build Path node.
3. Select Libraries tab.
4. Remove JRE System Library 一次
5. 再次 Add Library JRE System Library
解决方案二:
Window-->Preferences-->Java-->Compiler-->Error/Warnings-->Deprecated and Restricted API 改为 warning
其实如果是操作某些非公开的JDK API的话,会出现这些问题,可以使用上述的解决方案,但是建议使用其他的方案代替,例如下例所给出的解决方案,用scaleImage2 代替 scaleImage 不使用受保护的方法
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());
}
}
}