0

When i rotated a buffer image in java web application its color change to red and this only happens in when save as JPEG format .If format is PNG it works

code..

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

image as jpg Rotated Image

image as png enter image description here

ysk
  • 159
  • 1
  • 3
  • 12
  • Strangely - you draw your background in red (`g2d.setColor(Color.RED); g2d.drawRect(0, 0, newWidth - 1, newHeight - 1)` - but your questions assumes that behaviour is not wanted... – Martin Frank Jun 22 '20 at 11:20
  • Quick fix: Change your image type to `TYPE_INT_RGB` (i.e.: don't use alpha in JPEGs, it just confuses most software). – Harald K Jun 28 '20 at 10:23

0 Answers0