旋转BufferedImage并以JPEG格式存储时更改其颜色

时间:2016-05-15 06:09:42

标签: java bufferedimage javax.imageio affinetransform

我正在对图像进行以下转换(最初作为base64中的String):

StringBuffer - >解码 - > BufferedImage - >旋转 - >编码 - > StringBuffer的

即使生成的图像被旋转,颜色也会被转换,我不知道是什么原因。有什么想法吗?

这是代码:

 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());
}

0 个答案:

没有答案