1. 程式人生 > >java按比例壓縮圖片的原始碼,用java如何把圖片處理到指定大小

java按比例壓縮圖片的原始碼,用java如何把圖片處理到指定大小

public static void uploadImage(File p_in,File p_out,int height,int width,String ftype) throws FileNotFoundException,IOException
   {
//    取得圖片處理
//    ConvertImageFactory l_factory = ConvertImageFactory.getInstance();
//    AbstractProduct l_product = l_factory.createAbstractProduct(p_SourceFile.getContentType());
//    boolean l_result = l_product.convertImageSize(p_SourceFile
//      .getInputStream(), p_path );
    InputStream l_in = new FileInputStream(p_in);
    OutputStream l_out = new FileOutputStream(p_out);
    chgPic(l_in,l_out,width,height,ftype);
  
  
   }
 
   //按比例壓縮圖片
   public static boolean chgPic(InputStream in, OutputStream out,int newWidth, int newHeight,String ftype) {
    BufferedImage img = null;
    FileInputStream newin=null;
    File tempfile=null;
    try {
     if(ftype.compareToIgnoreCase("bmp")==0){
      PNGDecodeParam decodeParam = new PNGDecodeParam();
      String l_tempfile = Tool.createNewFileName("jpg");
    
      tempfile = new File(l_tempfile);
      JPEGEncodeParam encodeParam = new JPEGEncodeParam();
      //根據路徑開啟輸出流
      FileOutputStream tempout;
      tempout = new FileOutputStream(tempfile);  
      ImageDecoder decoder = ImageCodec.createImageDecoder("BMP",in,decodeParam);
      RenderedImage image = decoder.decodeAsRenderedImage();
      ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG",tempout,encodeParam);
      encoder.encode(image);
      tempout.close();
    
      newin = new FileInputStream(tempfile);
      img = ImageIO.read(newin);
     }else{
      img = ImageIO.read(in);
     }
   
     int width = img.getWidth(null);
     int height = img.getHeight(null);
   
     if (newWidth >= width) {
      if (newHeight < height) {
       width = (int) (width * newHeight / height);
       height = newHeight;
      }
     } else {
      if (newHeight >= height) {
       height = (int) (height * newWidth / width);
       width = newWidth;
      } else {
       if (height > width) {
        width = (int) (width * newHeight / height);
        height = newHeight;
       } else {
        height = (int) (height * newWidth / width);
        width = newWidth;
       }
      }
     }
   
     BufferedImage img2 = new BufferedImage(width, height,
       BufferedImage.TYPE_INT_RGB);
     img2.getGraphics().drawImage(img, 0, 0, width, height, null);
   
     if (ftype.compareToIgnoreCase("jpg") == 0 || ftype.compareToIgnoreCase("jpeg") == 0 ) {
      ImageIO.write(img2, "jpg", out);
     } else
      ImageIO.write(img2, "png", out);
   
     if( ftype.compareToIgnoreCase("bmp") == 0){
      ImageIO.write(img2, "jpg", out);
      newin.close();
      tempfile.delete();
     }
     return true;
    } catch (Exception ex) {
     ex.printStackTrace();
     return false;
    }finally{
     try{
      in.close();
      out.close();
     } catch (IOException e) {
    
     }  
    }
   }