Java Rotating Images


This is the exemple of Java code how to rotate image.
package myjavaexample; 

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.geom.AffineTransform; 
import java.awt.image.AffineTransformOp; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.IOException; 
import javax.imageio.ImageIO; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.WindowConstants; 

public class MyJavaExample extends JFrame 
{ 
    private BufferedImage image; 
    private int rotation=0; 
    public void openImage() 
    { 
        try{ 
            image = ImageIO.read(new File("C:\\Users\\Edugame\\Documents\\kincir.png")); 
        }catch(IOException e){} 

        JPanel pane = new JPanel() { 
            protected void paintComponent(Graphics g) { 
                super.paintComponent(g); 

                g.setColor(Color.RED); 
                g.fillRect((int)(0.5*getWidth()-15),(int)(50+0.5*image.getHeight()),30,getHeight()); 

                if(image!=null){ 
                    rotation+=5; 
                    double rotationRequired = Math.toRadians (-rotation); 
                    double posX = image.getWidth() / 2; 
                    double posY = image.getHeight() / 2; 
                    AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired,posX,posY); 
                    AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR); 
                    g.drawImage(op.filter(image, null),(int)(0.5*(getWidth()-image.getWidth())),30, null); 
                } 
            } 
        }; 
        pane.setPreferredSize(new Dimension(2*image.getWidth(),2*image.getHeight())); 
        add(pane); 
 
        setTitle("Rotating Image"); 
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
        setSize(200,200); 
        setLocation(100,100); 
        pack(); 
        setVisible(true); 

        Thread th=new Thread(new Runnable(){ 
            public void run() 
            { 
                while(true){ 
                    try{ 
                        Thread.sleep(10); 
                        pane.repaint(); 
                    }catch(InterruptedException e){} 
                } 
            } 
        }); 
        th.start(); 
    } 
 
    public static void main(String[] args) { 
        MyJavaExample mainwin=new MyJavaExample(); 
        mainwin.openImage(); 
    } 
} 

Image Asset


Comments



Popular posts from this blog

Simple Java Code HTML Highlighter

How to Use Extends and Implements

Fibonacci Algorithm in Java Array