java jpeg library_no jpeg in java.library.path;java.lang.NoClassDefFoundError: Could not initialize ...

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;

/**

* 按宽度高度压缩图片文件
先保存原文件,再压缩、上传

* @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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值