Me Myself and My way

Posts tagged ‘java’

Image Rotate in Java #2 : easier to use

I’ve combine the source I provided in the first article , which receive and return BufferedImage object , with the Image to a BufferedImage code that I’ve found from http://www.exampledepot.com/egs/java.awt.image/Image2Buf.html.

The result is the Class ImageUtils with the rotateImage() method that receive 2 parameters , img – an Image object to rotate and degree – the integer value of the degree that img will be rotated, the code is all shown below :).

** please note that I’m ONLY just combine these code to make it easier to use and I DIDN’T wrote it all myself.

// ImageUtils.java

package mystic.utils;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.PixelGrabber;
import javax.swing.ImageIcon;

public class ImageUtils {

    public static Image rotateImage(Image img,double degree){
        BufferedImage bufImg = toBufferedImage(img);
        double angle = Math.toRadians(degree);

        return tilt(bufImg,angle);
    }

    public static BufferedImage tilt(BufferedImage image, double angle) {
        double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
        int w = image.getWidth(), h = image.getHeight();
        int neww = (int)Math.floor(w*cos+h*sin), newh = (int)Math.floor(h*cos+w*sin);
        GraphicsConfiguration gc = getDefaultConfiguration();
        BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT);
        Graphics2D g = result.createGraphics();
        g.translate((neww-w)/2, (newh-h)/2);
        g.rotate(angle, w/2, h/2);
        g.drawRenderedImage(image, null);
        g.dispose();
        return result;
    }

    public static GraphicsConfiguration getDefaultConfiguration() {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice gd = ge.getDefaultScreenDevice();
        return gd.getDefaultConfiguration();
    }

    // http://www.exampledepot.com/egs/java.awt.image/Image2Buf.html
    // An Image object cannot be converted to a BufferedImage object.
    // The closest equivalent is to create a buffered image and then draw the image on the buffered image.
    // This example defines a method that does this.

    // This method returns a buffered image with the contents of an image
    public static BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage)image;
        }

        // This code ensures that all the pixels in the image are loaded
        image = new ImageIcon(image).getImage();

        // Determine if the image has transparent pixels; for this method's
        // implementation, see e661 Determining If an Image Has Transparent Pixels
        boolean hasAlpha = hasAlpha(image);

        // Create a buffered image with a format that's compatible with the screen
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        try {
            // Determine the type of transparency of the new buffered image
            int transparency = Transparency.OPAQUE;
            if (hasAlpha) {
                transparency = Transparency.BITMASK;
            }

            // Create the buffered image
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(
                image.getWidth(null), image.getHeight(null), transparency);
        } catch (HeadlessException e) {
            // The system does not have a screen
        }

        if (bimage == null) {
            // Create a buffered image using the default color model
            int type = BufferedImage.TYPE_INT_RGB;
            if (hasAlpha) {
                type = BufferedImage.TYPE_INT_ARGB;
            }
            bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
        }

        // Copy image to buffered image
        Graphics g = bimage.createGraphics();

        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();

        return bimage;
    }

    // http://www.exampledepot.com/egs/java.awt.image/HasAlpha.html
    // This method returns true if the specified image has transparent pixels
    public static boolean hasAlpha(Image image) {
        // If buffered image, the color model is readily available
        if (image instanceof BufferedImage) {
            BufferedImage bimage = (BufferedImage)image;
            return bimage.getColorModel().hasAlpha();
        }

        // Use a pixel grabber to retrieve the image's color model;
        // grabbing a single pixel is usually sufficient
         PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
        try {
            pg.grabPixels();
        } catch (InterruptedException e) {
        }

        // Get the image's color model
        ColorModel cm = pg.getColorModel();
        return cm.hasAlpha();
    }
}

Using the Desktop API in Java SE 6

Author : John O’Conner,

Source : http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/

Conclude by : ME

More info : http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html

Desktop Overview

This new functionality is provided by the java.awt.Desktop class. The API is adopted from the JDesktop Integration Components (JDIC) project. The goal of that project is to make “Java technology-based applications first-class citizens” of the desktop, enabling seamless integration. Specifically, the new Desktop API allows your Java applications to do the following:

  • Launch the host system’s default browser with a specific Uniform Resource Identifier (URI)
  • Launch the host system’s default email client
  • Launch applications to open, edit, or print files associated with those applications

The Desktop API uses your host operating system’s file associations to launch applications associated with specific file types. For example, if OpenDocument text (.odt) file extensions are associated with the OpenOffice Writer application, your Java application could launch OpenOffice Writer to open, edit, or even print files with that association. Depending on your host system, different applications may be associated with each different action.

Opening the Browser

Calling the following instance method will open your host’s default browser:

    
    public void browse(URI uri) throws IOException

ex.

    
    private void onLaunchBrowser(java.awt.event.ActionEvent evt) {
        URI uri = null;
        try {
            uri = new URI(txtBrowserURI.getText());
            desktop.browse(uri);
        }
        catch(IOException ioe) {
            ioe.printStackTrace();
        }
        catch(URISyntaxException use) {
            use.printStackTrace();

        }
        ...
    }
Sending Email

Applications can launch the host’s default email client, if that action is supported, by calling this Desktop instance method:

    public void mail(URI uri) throws IOException

ex.

     private void onLaunchMail(java.awt.event.ActionEvent evt) {
        String mailTo = txtMailTo.getText();
        URI uriMailTo = null;
        try {
            if (mailTo.length() > 0) {
                uriMailTo = new URI("mailto", mailTo, null);
                desktop.mail(uriMailTo);
            } else {
                desktop.mail();
            }
        }
        catch(IOException ioe) {
            ioe.printStackTrace();
        }
        catch(URISyntaxException use) {
            use.printStackTrace();
        }
        ...
    }
Opening, Editing, and Printing a File

Java applications can open, edit, and print files from their associated application using a Desktop object’s open(), edit(), and print() methods, respectively (see Figure 8). Again, DesktopDemo allows these actions only if the Desktop instance supports them, so in this application scenario, it is not necessary to check for support again.

    private void onLaunchDefaultApplication(java.awt.event.ActionEvent evt) {
        String fileName = txtFile.getText();
        File file = new File(fileName);

        try {
            switch(action) {
                case OPEN:
                    desktop.open(file);
                    break;
                case EDIT:
                    desktop.edit(file);
                    break;
                case PRINT:
                    desktop.print(file);
                    break;
            }
        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
        ...
    }

Image Rotate in Java

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
import javax.swing.*;

public class Tilt {
    public static void main(String[] args) throws IOException {
        URL url = new URL("http://weblogs.java.net/jag/Image1-large.jpeg");
        final BufferedImage image = ImageIO.read(url);
        final JLabel label = new JLabel(new ImageIcon(image));
        new Timer(100, new ActionListener(){
            double angle = 0;
            public void actionPerformed(ActionEvent evt) {
                angle += Math.PI/50;
                label.setIcon(new ImageIcon(tilt(image, angle)));
            }
        }).start();
        JFrame f = new JFrame("TILT");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(label);
        f.setSize(400,400);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static BufferedImage tilt(BufferedImage image, double angle) {
        double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
        int w = image.getWidth(), h = image.getHeight();
        int neww = (int)Math.floor(w*cos+h*sin), newh = (int)Math.floor(h*cos+w*sin);
        GraphicsConfiguration gc = getDefaultConfiguration();
        BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT);
        Graphics2D g = result.createGraphics();
        g.translate((neww-w)/2, (newh-h)/2);
        g.rotate(angle, w/2, h/2);
        g.drawRenderedImage(image, null);
        g.dispose();
        return result;
    }

    public static GraphicsConfiguration getDefaultConfiguration() {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice gd = ge.getDefaultScreenDevice();
        return gd.getDefaultConfiguration();
    }
}
you can also try a getRotateInstance (double, int, int) too. (from comment in that thread)