I trying convert an image in tiff format with background transparent, to jpeg to resize to 200x200 or 1200x1200, but when convert, the background turn to black, i want keep the background transparent or white after conversion
My code is following:
public static void TiffToJpg(String tiff, String output) throws IOException {
File tiffFile = new File(tiff);
SeekableStream s = new FileSeekableStream(tiffFile);
TIFFDecodeParam param = null;
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
RenderedImage op = dec.decodeAsRenderedImage(0);
FileOutputStream fos = new FileOutputStream(output);
JPEGEncodeParam jpgparam = new JPEGEncodeParam();
jpgparam.setQuality(100);
ImageEncoder en = ImageCodec.createImageEncoder("jpeg", fos, jpgparam);
en.encode(op);
BufferedImage in = javax.imageio.ImageIO.read(new java.io.File("oi.jpg"));
BufferedImage out = scaleImage(in, BufferedImage.TYPE_INT_RGB, 200, 200);
javax.imageio.ImageIO.write(out, "JPG", new java.io.File("thumbnail.jpg"));
BufferedImage out2 = scaleImage(in, BufferedImage.TYPE_INT_RGB, 1200, 1200);
javax.imageio.ImageIO.write(out2, "JPG", new java.io.File("web-image.jpg"));
fos.flush();
fos.close();
}
public static void main(String[] args) throws Exception {
Tiffthumbs.TiffToJpg("oi.tif", "oi.jpg");
}
public static BufferedImage scaleImage(BufferedImage image, int imageType, int newWidth, int newHeight) {
// Make sure the aspect ratio is maintained, so the image is not distorted
double thumbRatio = (double) newWidth / (double) newHeight;
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
double aspectRatio = (double) imageWidth / (double) imageHeight;
if (thumbRatio < aspectRatio) {
newHeight = (int) (newWidth / aspectRatio);
} else {
newWidth = (int) (newHeight * aspectRatio);
}
// Draw the scaled image
BufferedImage newImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D graphics2D = newImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, newWidth, newHeight, null);
return newImage;
}
How do this in java JAI?