void makeImage(Object stream, ImageWriter writer, ImageWriteParam iwp) throws IOException {
BufferedImage outputImage = img;
ImageWriterSpi imgProvider = writer.getOriginatingProvider();
img.coerceData(false);
if (! imgProvider.canEncodeImage(outputImage) || "image/jpeg".equals(imgProvider.getMIMETypes()[0].toLowerCase())) {
int w = img.getWidth();
int h = img.getHeight();
outputImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
outputImage.getGraphics().drawImage(img, 0, 0, w, h, null);
if (! imgProvider.canEncodeImage(outputImage)) {
throw new RuntimeException("Invalid image type");
}
}
if (! imgProvider.canEncodeImage(outputImage)) {
throw new RuntimeException("Invalid image type");
}
try (ImageOutputStream imageStream = ImageIO.createImageOutputStream(stream)) {
writer.setOutput(imageStream);
writer.write(null, new IIOImage(outputImage, null, null), iwp);
imageStream.flush();
} catch (IOException e) {
writer.abort();
throw e;
} finally {
writer.dispose();
}
}