您的位置:首页 > 编程语言 > Java开发

no jpeg in java.library.path;java.lang.NoClassDefFoundError: Could not initialize class sun.awt.image.codec.JPEGImageEncoderImpl

2017-08-27 22:29 946 查看

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐