java对图片进行“高保真”压缩

应项目需要,对上传的商品图片进行压缩处理,且必须要保证原图片的高保真显示效果。压缩牛的相关问题可以到网站了解,为您耐心解答问题,相信可以帮到您,值得您的信赖和支持。!
于是网上down资料,找到其中效果最好的一种方法,供大家使用和学习:
代码如下:
package com.hhsj.demo;
import java.awt.image.bufferedimage;
import java.io.file;
import java.io.fileoutputstream;
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 imagecompress2 { ?
? ??
? ? public bufferedimage zoomimage(string src) { ?
? ? ? ? bufferedimage result=null; ?
? ? ? ? try { ?
? ? ? ? ? ? file srcfile=new file(src); ?
? ? ? ? ? ? if (!srcfile.exists()) { ?
? ? ? ? ? ? ? ? system.out.println("文件不存在"); ?
? ? ? ? ? ? } ?
? ? ? ? ? ? bufferedimage im=imageio.read(srcfile); ?
? ? ? ? ? ??
? ? ? ? ? ? int width=im.getwidth(); ?
? ? ? ? ? ? int height=im.getheight(); ?
? ? ? ? ? ?
? ? ? ? ? ? //压缩计算 ?
? ? ? ? ? ? float resizetimes=0.3f; ? ?
? ? ? ? ? ?
? ? ? ? ? ??
? ? ? ? ? ? int towidth=(int) (width * resizetimes); ?
? ? ? ? ? ? int toheight=(int) (height * resizetimes); ?
? ? ? ? ? ??
? ? ? ? ? ? result=new bufferedimage(towidth, toheight, ?
? ? ? ? ? ? ? ? ? ? bufferedimage.type_int_rgb); ?
? ? ? ? ? ? result.getgraphics().drawimage( ?
? ? ? ? ? ? ? ? ? ? im.getscaledinstance(towidth, toheight, ?
? ? ? ? ? ? ? ? ? ? ? ? ? ? java.awt.image.scale_smooth), 0, 0, null); ?
? ? ? ? ? ?
? ? ? ? } catch (exception e) { ?
? ? ? ? ? ? system.out.println("创建缩略图发生异常" + e.getmessage()); ?
? ? ? ? } ?
? ? ? ?
? ? ? ? return result; ?
? ? } ?
? ?
? ? ?public boolean writehighquality(bufferedimage im, string filefullpath) { ?
? ? ? ? ? ? try { ?
? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? fileoutputstream newimage=new fileoutputstream(filefullpath); ?
? ? ? ? ? ? ? ? jpegimageencoder encoder=jpegcodec.createjpegencoder(newimage); ?
? ? ? ? ? ? ? ? jpegencodeparam jep=jpegcodec.getdefaultjpegencodeparam(im); ?
? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? jep.setquality(0.9f, true); ?
? ? ? ? ? ? ? ? encoder.encode(im, jep); ?
? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? newimage.close(); ?
? ? ? ? ? ? ? ? return true; ?
? ? ? ? ? ? } catch (exception e) { ?
? ? ? ? ? ? ? ? return false; ?
? ? ? ? ? ? } ?
? ? ? ? } ?
? ? ? ?
? ? ?public static void main(string[] args) { ?
? ? ? ? ?string inputfoler="d:\\img.jpg" ;
? ? ? ? ? ?
? ? ? ? string outputfolder="d:\\newimg.jpg"; ? ?
? ? ? ??
? ? ? ? imagecompress2 narrowimage=new imagecompress2(); ?
? ? ? ? ?narrowimage.writehighquality(narrowimage.zoomimage(inputfoler), outputfolder); ?
? ? ? ?
? ? } ?
} ?