public static byte[] bufferedImageToJPEG(BufferedImage img,float quality) throws IOException {
  Iterator<ImageWriter> writers=ImageIO.getImageWritersBySuffix("jpeg");
  if (!writers.hasNext())   throw new IllegalStateException("No writers for jpeg...");
  ImageWriter writer=(ImageWriter)writers.next();
  ImageWriteParam imageWriteParam=writer.getDefaultWriteParam();
  imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
  imageWriteParam.setCompressionQuality(quality);
  IIOImage iioImage=new IIOImage(img,null,null);
  ByteArrayOutputStream baos=new ByteArrayOutputStream(img.getWidth() * img.getHeight() * 2);
  MemoryCacheImageOutputStream mcios=new MemoryCacheImageOutputStream(baos);
  writer.setOutput(mcios);
  writer.write(null,iioImage,imageWriteParam);
  baos.flush();
  mcios.close();
  return baos.toByteArray();
}

public static byte [ ] bufferedImageToJPEG ( BufferedImage img , float quality ) throws IOException { Iterator < ImageWriter > writers = ImageIO . getImageWritersBySuffix ( "jpeg" ) ; if ( ! writers . hasNext ( ) ) throw new IllegalStateException ( "No writers for jpeg..." ) ; ImageWriter writer = ( ImageWriter ) writers . next ( ) ; ImageWriteParam imageWriteParam = writer . getDefaultWriteParam ( ) ; imageWriteParam . setCompressionMode ( ImageWriteParam . MODE_EXPLICIT ) ; imageWriteParam . setCompressionQuality ( quality ) ; IIOImage iioImage = new IIOImage ( img , null , null ) ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( img . getWidth ( ) * img . getHeight ( ) * 2 ) ; MemoryCacheImageOutputStream mcios = new MemoryCacheImageOutputStream ( baos ) ; writer . setOutput ( mcios ) ; writer . write ( null , iioImage , imageWriteParam ) ; baos . flush ( ) ; mcios . close ( ) ; return baos . toByteArray ( ) ; }
converts a buffered image to a jpeg image
