经典重庆
标题:
java对图片进行“高保真”压缩
[打印本页]
作者:
lianrangsiw
时间:
2020-12-28 23:13
标题:
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); ?
? ? ? ?
? ? } ?
} ?
欢迎光临 经典重庆 (http://bbs.jdcq.net/)
Powered by Discuz! X3.1