private static byte[] bufferedImageToJPEG(BufferedImage bufferedImage, float quality)
throws Exception
{
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
ImageWriteParam writeParam = writer.getDefaultWriteParam();
ColorModel colorModel = new DirectColorModel(24, 0x00ff0000, 0x0000ff00, 0x000000ff);
ImageTypeSpecifier imageTypeSpecifier =
new ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(1, 1)/*ignored*/);
writeParam.setDestinationType(imageTypeSpecifier);
writeParam.setSourceBands(new int[] {0, 1, 2});
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionQuality(quality);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
writer.setOutput(new MemoryCacheImageOutputStream(buffer));
IIOImage ioImage = new IIOImage(bufferedImage, null, null);