图片压缩 SCALE_SMOOTH算法

来源:互联网 发布:如何找天使投 知乎 编辑:程序博客网 时间:2024/05/21 10:34

第一种:最简洁的SCALE_SMOOTH



package test;



import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;


import javax.imageio.ImageIO;


//这两个包需要手动导入
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


/**
 * 使用 SCALE_SMOOTH进行
 * 图片压缩处理

 */
public class ImgCompress {
private static Image img;
private static int width;
private static int height;


public static void main(String[] args) throws Exception {
System.out.println("开始:" + new Date().toLocaleString());
ImgCompress1("D:\\1.png");//需要压缩的图片路径
System.out.println("结束:" + new Date().toLocaleString());
}


/**
* 构造函数
*/
public static void ImgCompress1(String fileName) throws IOException {
int w=600;int h=800;
File file = new File(fileName);// 读入文件
img = ImageIO.read(file); // 构造Image对象
width = img.getWidth(null); // 得到源图宽
height = img.getHeight(null); // 得到源图长
if(width>height){  //设置图片宽高度
h = height * w / width;
}else{
w = width * h / height;
}
BufferedImage image = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB ); //获得图片的详细信息
 
// Graphics有六个drawImage方法,我们用的最多的是  
// public abstract boolean drawImage(Image img, int x, int y,int width, int height,ImageObserver observer);
// img是要加载的图像,x,y是指定绘制图像矩形左上角的位置,width是指定绘制图像矩形的宽,width是指定绘制图像矩形的高,observer是要绘制图像的容器。
image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图
// 最后一个添null就可以了,那是用来检测图片改变的“图片观察者”,实际中基本用不到。
// 因为这个观察者类在java设计中有严重缺陷,会导致图片绘制不及时,所以图片更新的工作往往都是由开发者自己来做。
 
File destFile = new File("D:\\1234.jpg"); //新图片保存的位置和名称
FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流
// 可以正常实现bmp、png、gif转jpg
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image); // JPEG编码
out.close();
}


}




第二种方法:同样使用SCALE_SMOOTH缩略算法,但是可以按比例压缩(进行简单的逻辑运算)


package test;


import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


public class TestCompress {

public static void main(String[] args){
//     /** 
//      * d://3.jpg 源图片 
//      * d://31.jpg 目标图片 
//      * 压缩宽度和高度都是1000
//      */  
//     System.out.println("压缩图片开始...");  
//     File srcfile = new File("d://3.jpg");  
//     System.out.println("压缩前srcfile size:" + srcfile.length());  
////     float f = (float) 1;
//     reduceImg("d://3.jpg", "d://3.jpg", 100, 100,null);  
//     File distfile = new File("d://31.jpg");  
//     System.out.println("压缩后distfile size:" + distfile.length()); 
////     distfile.delete();
}

   public void reduceImg(String imgsrc, String imgdist, int widthdist,  
            int heightdist, Float rate) {
        try {
            File srcfile = new File(imgsrc);  
            // 检查文件是否存在  
            if (!srcfile.exists()) {  
                return;  
            }  
            // 如果rate不为空说明是按比例压缩  
            if (rate != null && rate > 0) { 
                // 获取文件高度和宽度  
                int[] results = getImgWidth(srcfile);  
                if (results == null || results[0] == 0 || results[1] == 0) {  
                    return;  
                } else {  
                    widthdist = (int) (results[0] * rate);  
                    heightdist = (int) (results[1] * rate);  
                }  
            }  
            // 开始读取文件并进行压缩  
            Image src = javax.imageio.ImageIO.read(srcfile);  
            BufferedImage tag = new BufferedImage((int) widthdist,  
                    (int) heightdist, BufferedImage.TYPE_INT_RGB);  
  
            tag.getGraphics().drawImage( 
                    src.getScaledInstance(widthdist, heightdist,  
                            Image.SCALE_SMOOTH), 0, 0, null);  
  
            FileOutputStream out = new FileOutputStream(imgdist);  
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
            encoder.encode(tag);  
            out.close(); 
        } catch (IOException ex) {  
            ex.printStackTrace();  
        }  
    }  
   
   
    public static int[] getImgWidth(File file) {  
        InputStream is = null;  
        BufferedImage src = null;  
        int result[] = { 0, 0 };  
        try {  
            is = new FileInputStream(file);  
            src = javax.imageio.ImageIO.read(is);  
            result[0] = src.getWidth(null); // 得到源图宽  
            result[1] = src.getHeight(null); // 得到源图高  
            is.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return result;  
    }
    
}




以上都是本人在网上找的一些关于java实现图片压缩的资料,亲测能用,第一种也最简单,有不好的地方请各路大佬指教!

原创粉丝点击