java image compression tool class


java image compression code:

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

public class ImageProcess {
 /**
  *  The picture
  */
 private Image img;
 /**
  *  The width of the
  */
 private int width;
 /**
  *  highly
  */
 private int height;
 /**
  *  The file format
  */
 private String imageFormat;
 /**
  *  The constructor
  * @throws Exception
  */
 public ImageProcess(InputStream in,String fileName) throws Exception{
   // structure Image object
   img = ImageIO.read(in);
   // Get the source map width
   width = img.getWidth(null);
   // Get the source map length
   height = img.getHeight(null);
   // The file format
   imageFormat = fileName.substring(fileName.lastIndexOf(".")+1);
 }
 /**
  *  Compress by width or by height
  * @param w int  Maximum width
  * @param h int  Maximum height
  */
 public byte[] resizeFix(int w, int h) throws IOException {
   if (width / height > w / h) {
     return resizeByWidth(w);
   } else {
     return resizeByHeight(h);
   }
 }
 /**
  *  Take the width as the reference, and scale the picture equally
  * @param w int  The new width
  */
 public byte[] resizeByWidth(int w) throws IOException {
   int h = (int) (height * w / width);
   return resize(w, h);
 }
 /**
  *  Take the height as the base and scale the picture equally
  * @param h int  New height
  */
 public byte[] resizeByHeight(int h) throws IOException {
   int w = (int) (width * h / height);
   return resize(w, h);
 }
 /**
  *  Mandatory compressed / Enlarge image to fixed size
  * @param w int  The new width
  * @param h int  New height
  */
 public byte[] resize(int w, int h) throws IOException {
   // SCALE_SMOOTH  Thumbnail algorithm of   The smoothness of the thumbnail image is generated   Priority is higher than speed   The resulting images are of better quality   But slowly
   BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB );
   image.getGraphics().drawImage(img, 0, 0, w, h, null); //  Draw a scaled down diagram
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   ImageIO.write(image, imageFormat, baos);
   return baos.toByteArray();
 }
}