首页 > 解决方案 > 旋转后缓冲图像颜色变化

问题描述

当我在 Java Web 应用程序中旋转缓冲区图像时,它的颜色变为红色,并且这只发生在保存为 JPEG 格式时。如果格式是 PNG,它可以工作

代码..

public BufferedImage rotateImageByDegrees(BufferedImage img, double angle, int width, int height) {

        double rads = Math.toRadians(angle);
        double sin = Math.abs(Math.sin(rads)), cos = Math.abs(Math.cos(rads));
        int w = img.getWidth();
        int h = img.getHeight();
        int newWidth = (int) Math.floor(w * cos + h * sin);
        int newHeight = (int) Math.floor(h * cos + w * sin);

        BufferedImage rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = rotated.createGraphics();
        AffineTransform at = new AffineTransform();
        at.translate((newWidth - w) / 2, (newHeight - h) / 2);

        int x = w / 2;
        int y = h / 2;

        at.rotate(rads, x, y);
        g2d.setTransform(at);
        g2d.drawImage(img, null, 0, 0);
        g2d.setColor(Color.RED);
        g2d.drawRect(0, 0, newWidth - 1, newHeight - 1);
        g2d.dispose();

        return rotated;
    }

图像为 jpg 旋转图像

图像为png 在此处输入图像描述

标签: javaimagewebbufferedimage

解决方案


推荐阅读