实现图片按照比例显示(java代码)

来源:互联网 发布:苏州爱知科技招聘 编辑:程序博客网 时间:2024/05/16 01:14

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

 

public class ImageSizeCol {

//获得Jsp自定义标签中的<img>的属性width和height。
 public String getJspTag(String str,int int0,int int1) throws IOException{
  File file;
  BufferedImage bi;
  int x = 0;
  int y = 0;
  String productPicturePath = PageSource.getAppLogicPath() + str;
  file = new File(productPicturePath);
  if(file.exists() && file.isFile()){
   double ratio = 0.0;   
    bi = ImageIO.read(file);  
    ratio = new java.math.BigDecimal(new Double(bi.getWidth()).doubleValue()/new Double(bi.getHeight()).doubleValue()).setScale(2, 4).doubleValue();
    if(bi.getWidth()>bi.getHeight()){
     if(bi.getWidth()>int0){
      x = int0;
      y = (int)(x/ratio);
     }else{
      x = bi.getWidth();
      y = (int)(x/ratio);
     }
    }else if(bi.getHeight()>bi.getWidth()){
     if(bi.getHeight()>int1){
      y = int1;
      x = (int)(y*ratio);
     }else{
      y = bi.getHeight();
      x = (int)(y*ratio);
     }
    }
  }
  return "width=/""+x+"/" height=/""+ y +"/"";
 }

//获得html<img>中的属性width和height。
 public String getHtmlAtt(String str,int int0,int int1){
  int x = 0;
  int y = 0;
  String productPicturePath = PageSource.getAppLogicPath() + str;
  File file = new File(productPicturePath);
  if(file.exists() && file.isFile()){
   double ratio = 0.0;
   BufferedImage bi;
   try {
    bi = ImageIO.read(file);  
    ratio = new java.math.BigDecimal(new Double(bi.getWidth()).doubleValue()/new Double(bi.getHeight()).doubleValue()).setScale(2, 4).doubleValue();
    if(bi.getWidth()>bi.getHeight()){
     if(bi.getWidth()>int0){
      x = int0;
      y = (int)(x/ratio);
     }else{
      x = bi.getWidth();
      y = (int)(x/ratio);
     }
    }else if(bi.getHeight()>bi.getWidth()){
     if(bi.getHeight()>int1){
      y = int1;
     }else{
      y = bi.getHeight();
     }
    }
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  return "width='"+x+"' height='"+ y +"'";
 }
}

原创粉丝点击