자바 그림 등 크기 조정

2702 단어
더 읽 기
package main.feng;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * Created by songfeng on 2017/2/16.
 */
public class ImgUtils {
    public static void main(String[] args) {
        try {
            ImgUtils.zoomImage("D:\\111.jpg", "D:\\222.jpg", 100, 200);
            ImgUtils.zoomImage("D:\\111.jpg", "D:\\333.jpg", 0.6);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     *     ,w,h           
     * src      ,dest        
     */
    public static void zoomImage(String src,String dest,int w,int h) throws Exception {

        double wr=0,hr=0;
        File srcFile = new File(src);
        File destFile = new File(dest);

        BufferedImage bufImg = ImageIO.read(srcFile); //    
        Image Itemp = bufImg.getScaledInstance(w, h, bufImg.SCALE_SMOOTH);//          

        wr=w*1.0/bufImg.getWidth();     //      
        hr=h*1.0 / bufImg.getHeight();

        AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);
        Itemp = ato.filter(bufImg, null);
        try {
            ImageIO.write((BufferedImage) Itemp,dest.substring(dest.lastIndexOf(".")+1), destFile); //        
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /*
     *        
     * rate     
     */
    public static void zoomImage(String src,String dest,double rate) throws Exception {
        File srcFile = new File(src);
        File destFile = new File(dest);

        long fileSize = srcFile.length();
        if (rate >= 1d)   //      1 ,     
            return;

        BufferedImage bufImg = ImageIO.read(srcFile);
        Image Itemp = bufImg.getScaledInstance(bufImg.getWidth(), bufImg.getHeight(), bufImg.SCALE_SMOOTH);

        AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(rate, rate), null);
        Itemp = ato.filter(bufImg, null);
        try {
            ImageIO.write((BufferedImage) Itemp, dest.substring(dest.lastIndexOf(".") + 1), destFile);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

좋은 웹페이지 즐겨찾기