等比例改变图片大小

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import javax.imageio.ImageIO;

public class ChangeImageSize {

    public static void main(String[] args) {
        /*String aa="{aa:{'name':'123'}}";
        JSONObject jSONObject = JSONObject.fromObject(aa);
        System.out.println(JSONObject.fromObject(jSONObject.get("aa")).get("name"));
        String a = "20170110200001";
        String b = "20170110200000";
        System.out.println(a.compareTo(b));// a>b => -1 0 1
*/        
        try {
            scaleImage("C:/log/1.jpg", "C:/log/2.jpg", 500, 500);
            System.out.println("yes");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
    
    
    public static String scaleImage(String inpath,String outpath, int width, int height) throws Exception {  
        BufferedImage buffered_oldImage = ImageIO.read(new File(inpath));  
        int imageOldWidth = buffered_oldImage.getWidth();  
        int imageOldHeight = buffered_oldImage.getHeight();  
        double scale_x = (double) width / imageOldWidth;  
        double scale_y = (double) height / imageOldHeight;  
        double scale_xy = Math.min(scale_x, scale_y);  
        int imageNewWidth = (int) (imageOldWidth * scale_xy);  
        int imageNewHeight = (int) (imageOldHeight * scale_xy);  
        BufferedImage buffered_newImage = new BufferedImage(imageNewWidth, imageNewHeight, BufferedImage.TYPE_INT_RGB);  
        buffered_newImage.getGraphics().drawImage(buffered_oldImage.getScaledInstance(imageNewWidth, imageNewHeight, BufferedImage.SCALE_SMOOTH), 0, 0, null);  
        buffered_newImage.getGraphics().dispose();  
        ByteArrayOutputStream outPutStream = new ByteArrayOutputStream();  
        ImageIO.write(buffered_newImage, "jpeg", outPutStream);  
     
        BufferedOutputStream bufferOutput = null;  
        File ff = new File(outpath);
        if(ff.exists()){
            ff.delete();
        }
        bufferOutput = new BufferedOutputStream(new FileOutputStream(ff), 2048);  
        bufferOutput.write(outPutStream.toByteArray());  
        bufferOutput.flush();  
        if (bufferOutput != null) {  
            try {  
                bufferOutput.close();  
            } catch (Exception e) {  
                throw new RuntimeException(e);  
            }  
        }  
        
        return outpath;  
    }  
    
    
    
    
    
}

 

转载于:https://www.cnblogs.com/syscn/p/7742349.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值