private void encodeJPEG(ByteArrayOutputStream baos, BufferedImage image)throws IOException{
int width = image.getWidth();
int height = image.getHeight();
JFIFOutputStream os;
if(image.getType()==BufferedImage.TYPE_BYTE_GRAY){ // one component; grey scale
os =new JFIFOutputStream(baos,false,height,width); // SOF:start of frame
WritableRaster raster=image.getRaster();
DataBufferByte buffer=(DataBufferByte)raster.getDataBuffer();
byte[] imgdata=(byte[])buffer.getData();
os.write(imgdata);
os.close(); // EOF: end of frame
}else if(image.getType()==BufferedImage.TYPE_INT_RGB){ // three components; YCbCr
os =new JFIFOutputStream(baos,true,height,width); // SOF:start of frame
WritableRaster raster=image.getRaster();
DataBufferInt buffer=(DataBufferInt)raster.getDataBuffer();
int[] imgdata=(int[])buffer.getData();
os.write(imgdata);
os.close(); // EOF: end of frame
}
}