no jpeg in java.library.path;java.lang.NoClassDefFoundError: Could not initialize class sun.awt.image.codec.JPEGImageEncoderImpl
因為要壓縮圖片,所以用到了JPEGImageEncoder類,但這個類在1.7后就被拋棄了,導致現在調用總是報錯,雖然我在本地windows eclipse上可以成功調用,但到了centos上就出錯了。
從網上的建議看,就是取而代之用ImageIO類就能解決這個問題。
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
public class ImageUtil {
// 壓縮圖片到制定的寬度,同時長度壓縮到相同比例
private static final int COMPRESS_WIDTH = 150;
// 壓縮質量
private static final float RATIO = 0.99f;
/**
* 按寬度高度壓縮圖片文件<br> 先保存原文件,再壓縮、上傳
* @param oldFile 要進行壓縮的文件全路徑
* @param newFile 新文件
* @param width 寬度
* @param height 高度
* @param quality 質量
* @return 返回壓縮后的文件的全路徑
*/
public static boolean compressImage(
String oldPath, String newPath) {
File oldFile = new File(oldPath);
File newFile = new File(newPath);
if (!oldFile.exists()) {
return false;
}
String newImage = null;
try {
/** 對服務器上的臨時文件進行處理 */
Image srcFile = ImageIO.read(oldFile);
int w = srcFile.getWidth(null);
// System.out.println(w);
int h = srcFile.getHeight(null);
// System.out.println(h);
/** 寬,高設定 */
// 壓縮后的高
int height = (int)(1.0*COMPRESS_WIDTH/w*h);
BufferedImage tag = new BufferedImage(
COMPRESS_WIDTH, height
,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(srcFile, 0, 0, COMPRESS_WIDTH, height, null);
//String filePrex = oldFile.substring(0, oldFile.indexOf('.'));
/** 壓縮后的文件名 */
//newImage = filePrex + smallIcon+ oldFile.substring(filePrex.length());
/** 壓縮之后臨時存放位置 */
JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
/** 壓縮質量 */
jep.setQuality(RATIO, true);
// FileOutputStream out = new FileOutputStream(newFile);
// JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
// encoder.encode(tag, jep);
String formatName = newPath.substring(newPath.lastIndexOf(".") + 1);
//FileOutputStream out = new FileOutputStream(dstName);
//JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//encoder.encode(dstImage);
ImageIO.write(tag, /*"GIF"*/ formatName /* format desired */ , new File(newPath) /* target */ );
// out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}