等比例改变图片大小

Posted 冬天不眠

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了等比例改变图片大小相关的知识,希望对你有一定的参考价值。

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;  
    }  
    
    
    
    
    
}

 

以上是关于等比例改变图片大小的主要内容,如果未能解决你的问题,请参考以下文章

S实现控制图片显示大小的方法图片等比例缩放功能

用 jQuery实现图片等比例缩放大小

背景图怎么等比例缩放?

弹性盒子布局解决不规则图片的等比例缩放的利器!

css响应式问题,图片随页面宽度等比例缩小该怎么设置

php实现等比例不失真缩放上传图片的方法