java对图片进行压缩和resize缩放的方法
序
这里展示一下如何对图片进行压缩和resize。分享给大家,具体如下:
压缩
publicstaticbooleancompress(Stringsrc,Stringto,floatquality){
booleanrs=true;
//Buildparam
JPEGEncodeParamparam=null;
//Buildencoder
Filedestination=newFile(to);
FileOutputStreamos=null;
try{
BufferedImageimage=ImageIO.read(newFile(src));
param=JPEGCodec.getDefaultJPEGEncodeParam(image);
param.setQuality(quality,false);
os=FileUtils.openOutputStream(destination);
JPEGImageEncoderencoder;
if(param!=null){
encoder=JPEGCodec.createJPEGEncoder(os,param);
}else{
returnfalse;
}
encoder.encode(image);
}catch(Exceptione){
e.printStackTrace();
rs=false;
}finally{
IOUtils.closeQuietly(os);
}
returnrs;
}
resize
publicstaticbooleanresize(Stringsrc,Stringto,intnewWidth,intnewHeight){
try{
FilesrcFile=newFile(src);
FiletoFile=newFile(to);
BufferedImageimg=ImageIO.read(srcFile);
intw=img.getWidth();
inth=img.getHeight();
BufferedImagedimg=newBufferedImage(newWidth,newHeight,img.getType());
Graphics2Dg=dimg.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(img,0,0,newWidth,newHeight,0,0,w,h,null);
g.dispose();
ImageIO.write(dimg,"jpg",toFile);
}catch(Exceptione){
e.printStackTrace();
returnfalse;
}
returntrue;
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。