2

The below code resizes an image. Unfortunately the image which is a vertical image has black bars on the sides. It looks as though the transparent, or blank space is being filled with black. I've tried setting the background color to white, and using alphaRGB but can't seem to shake it.

    OrderProductAssetEntity orderProductAssetEntity = productAssets.get(jobUnitEntity.getId());
    File asset = OrderProductAssetService.getAssetFile(orderProductAssetEntity);
    if (asset.exists()) {
        //resize the asset to a smaller size
        BufferedImage resizedImage = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = resizedImage.createGraphics();
        g.setBackground(Color.WHITE);
        g.drawImage(ImageIO.read(asset), 0, 0, width, height, null);
        g.dispose();

        jobUnitImages.put(orderProductAssetEntity.getOriginalLocation(), new PDJpeg(document, resizedImage));
    } else {
        jobUnitImages.put(orderProductAssetEntity.getOriginalLocation(), null);
    }

1 Answer 1

3

First, if you need transparency, BufferedImage.TYPE_INT_RGB won't work, you'll need BufferedImage.TYPE_INT_ARGB. Not sure if you already tried it, just want to be clear.

Second, this line:

g.setBackground(Color.WHITE);

...does only set the current background color for the graphics context. It does not fill the background with that color. For that, you'll need to do g.clearRect(0, 0, width, height) as well. But I usually prefer to use g.setColor(...) and g.fillRect(...) instead to avoid confusion.

Or, if you like, you can also use the drawImage method that takes a Color as the second last parameter like this:

g.drawImage(image, 0, 0, width, height, Color.WHITE, null);

EDIT:

Third, the class name PDJpeg implies that the image is later stored as JPEG, so you will probably lose transparency anyway. So the best is probably to stick with TYPE_INT_RGB, and fill the background with the right color (and do it the right way ;-).

1
  • Perfect! I used g.drawImage(...) Thanks!!
    – Ben
    Sep 30, 2013 at 12:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.