When I run your code, I don't get a black background, but the colors of the image look all weird (channels seem to be messed up).
When I change the image type in toBufferedImage(..)
to BufferedImage.TYPE_INT_RGB
(no alpha, as JPEG doesn't support transparency), all works fine.
Still weird that the ImageIO
doesn't take this into regard when writing JPEG images...
By the way, asynchronous image scaling (as getScaledInstance(..)
does) was not the problem, I made sure the image resizing was done before continuing, this had no effect on the outcome.
To load an image completely, use MediaTracker
:
public static void loadCompletely (Image img) {
MediaTracker tracker = new MediaTracker(new JPanel());
tracker.addImage(img, 0);
try {
tracker.waitForID(0);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
EDIT
Here's the code I use to resize images, retaining proportions (different resizing methods depending on whether you're upscaling or downscaling, and faster alternative to area averaging):
public static BufferedImage resizeImage (BufferedImage image, int areaWidth, int areaHeight) {
float scaleX = (float) areaWidth / image.getWidth();
float scaleY = (float) areaHeight / image.getHeight();
float scale = Math.min(scaleX, scaleY);
int w = Math.round(image.getWidth() * scale);
int h = Math.round(image.getHeight() * scale);
int type = image.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
boolean scaleDown = scale < 1;
if (scaleDown) {
// multi-pass bilinear div 2
int currentW = image.getWidth();
int currentH = image.getHeight();
BufferedImage resized = image;
while (currentW > w || currentH > h) {
currentW = Math.max(w, currentW / 2);
currentH = Math.max(h, currentH / 2);
BufferedImage temp = new BufferedImage(currentW, currentH, type);
Graphics2D g2 = temp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(resized, 0, 0, currentW, currentH, null);
g2.dispose();
resized = temp;
}
return resized;
} else {
Object hint = scale > 2 ? RenderingHints.VALUE_INTERPOLATION_BICUBIC : RenderingHints.VALUE_INTERPOLATION_BILINEAR;
BufferedImage resized = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = resized.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
g2.drawImage(image, 0, 0, w, h, null);
g2.dispose();
return resized;
}
}