1

I am doing the following transformation of an image (initially as a String in base64):

StringBuffer --> decode --> BufferedImage --> rotate --> encode --> StringBuffer

Even though the resulting image is rotated, the color has been transformed and I don't know which could be the reason. Any ideas?

This is the code:

 public static StringBuffer rotateImage(StringBuffer img) {
    BufferedImage bufferedImage = decodeImage(img);
    bufferedImage = rotate(bufferedImage);
    return encodeImage(bufferedImage);
}

private static BufferedImage decodeImage(StringBuffer img) {
    byte[] decode = Base64.getDecoder().decode(String.valueOf(img).getBytes());
    InputStream input = new ByteArrayInputStream(decode);

    try {
        BufferedImage bufferedImage = ImageIO.read(input);
        return bufferedImage;
    } catch (IOException exception) {
        logger.warning(exception.toString());
    }

    return null;
}

private static BufferedImage rotate(BufferedImage img) {
    AffineTransform tx = new AffineTransform();
    tx.rotate(Math.PI, img.getWidth() / 2, img.getHeight() / 2);

    AffineTransformOp op = new AffineTransformOp(tx,
            AffineTransformOp.TYPE_BILINEAR);
    op.createCompatibleDestImage(img, null);
    img = op.filter(img, null);
    return img;
}

private static StringBuffer encodeImage(BufferedImage img) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        ImageIO.write(img, "jpeg", Base64.getEncoder().wrap(os));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new StringBuffer(os.toString());
}
Harald K
  • 26,314
  • 7
  • 65
  • 111
mmiracle
  • 11
  • 1
  • Might it be due to aliasing artifacts? Can you give us an idea of what kind of images you're seeing? Are these subtle or large color changes? – Ted Hopp May 15 '16 at 06:13
  • 2
    If the image contains an alpha channel, saving it out as JPEG may break it – MadProgrammer May 15 '16 at 06:14
  • [For more details](http://stackoverflow.com/questions/4386446/problem-using-imageio-write-jpg-file) – MadProgrammer May 15 '16 at 06:20
  • Unrelated, but the line `op.createCompatibleDestImage(img, null);` returns a new `BufferedImage` that you just throw away. This is probably not the intention... It's impossible to know without seeing a before/after image (you should add or link such images), but I also think @MadProgrammer is right. Does it work as expected, if you change to PNG format? – Harald K May 15 '16 at 09:20

0 Answers0