title: Rotate a BufferedImage and storing as JPEG changes its color
body: <p>I am doing the following transformation of an image (initially as a String in base64):</p>
  
  <p>StringBuffer --> decode --> BufferedImage --> rotate --> encode --> StringBuffer</p>
  
  <p>Even though the resulting image is rotated, the color has been transformed and I don't know which could be the reason. Any ideas?</p>
  
  <p>This is the code:</p>
  
  <pre><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());
  }
  </code></pre>