{
ImageInfo info = new ImageInfo();
try
{
LosslessImage image = new LosslessImage(sourceFile.getName(),
sourceFile.getInputStream(),
sourceFile.getLastModified());
// If compression is true, use JPEG compression. Otherwise, use the lossless format.
if (args.containsKey(COMPRESSION) && Boolean.parseBoolean((String) args.get(COMPRESSION)))
{
// We use DefineBitsJPEG3, because it supports an alpha channel
DefineBitsJPEG3 defineBits = new DefineBitsJPEG3();
int imageSize = image.getWidth() * image.getHeight();
byte[] alphaData = new byte[imageSize];
int[] pixels = image.getPixels();
BufferedImage bufferedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
bufferedImage.setRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth());
for (int i = 0; i < imageSize; ++i)
{
alphaData[i] = (byte) ((pixels[i] >> 24) & 0xff);
}
float quality = 1.0f;
if (args.containsKey(QUALITY))
{
try
{
String qualityString = (String) args.get(QUALITY);
double qualityPercentage = Double.parseDouble(qualityString);
// quality must be a number between 0 and 100.
if (qualityPercentage < 0 || qualityPercentage > 100)
{
throw new InvalidQuality();
}
quality = (float)(qualityPercentage / 100.0);
}
catch (NumberFormatException numberFormatException)
{
throw new InvalidQuality();
}
}
defineBits.data = bufferedImageToJPEG(bufferedImage, quality);
defineBits.alphaDataOffset = alphaData.length;
defineBits.alphaData = alphaData;
info.defineBits = defineBits;
}
else
{
// quality doesn't make sense without compression.
if (args.containsKey(QUALITY))
{
throw new QualityRequiresCompression();
}
DefineBitsLossless defineBits = DefineBitsLosslessBuilder.build(image.getPixels(), image.getWidth(), image.getHeight());
info.defineBits = defineBits;
}
info.width = image.getWidth();
info.height = image.getHeight();
}
catch (TranscoderException transcoderException)
{
throw transcoderException;
}