All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.bidib.wizard.common.utils.ImageUtils Maven / Gradle / Ivy

package org.bidib.wizard.common.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 java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;

import org.imgscalr.Scalr;
import org.imgscalr.Scalr.Method;
import org.imgscalr.Scalr.Mode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This ImageUtils class contains parts from:
 * 
 * @see image-rotate-in-java-2-easier-to-use
 * 
 */
public class ImageUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ImageUtils.class);

    /**
     * Returns an ImageIcon, or null if the path was invalid.
     * 
     * @param clazz
     *            the class
     * @param path
     *            the path
     * @return the image or null if path was invalid
     */
    public static ImageIcon createImageIcon(Class clazz, String path) {
        java.net.URL imgURL = clazz.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        }
        else {
            LOGGER.error("Couldn't find file: {}", path);
            return null;
        }
    }

    public static ImageIcon createImageIcon(Class clazz, String path, int width, int height) {

        if (path == null) {
            LOGGER.error("The path to the icon is not provided!");
            throw new IllegalArgumentException("The path to the icon is not provided!");
        }

        java.net.URL imgURL = clazz.getResource(path);
        if (imgURL != null) {
            try {
                BufferedImage image = ImageIO.read(imgURL);

                return new ImageIcon(Scalr.resize(image, Mode.AUTOMATIC, width, height));
            }
            catch (IOException ex) {
                LOGGER.warn("Create imageIcon failed: {}", path, ex);
            }
            // return new ImageIcon(imgURL);
        }
        else {
            LOGGER.error("Couldn't find file for imageIcon: {}", path);
        }
        return null;
    }

    public static ImageIcon loadImageIcon(Class clazz, String path, int width, int height) {
        InputStream imgURL = clazz.getResourceAsStream(path);
        if (imgURL != null) {
            BufferedImage image;
            try {
                image = ImageIO.read(imgURL);

                return new ImageIcon(Scalr.resize(image, Method.QUALITY, Mode.AUTOMATIC, width, height));
            }
            catch (IOException ex) {
                LOGGER.warn("Load image failed: {}", path, ex);
            }
        }
        else {
            LOGGER.error("Couldn't find file: {}", path);
        }
        return null;
    }

    public static ImageIcon loadImageIcon(File file, int width, int height) {
        BufferedImage image;
        try {
            image = ImageIO.read(file);

            return new ImageIcon(Scalr.resize(image, Mode.AUTOMATIC, width, height));
        }
        catch (IOException ex) {
            LOGGER.warn("Load image failed: {}", file, ex);
        }
        return null;
    }

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

    public static ImageIcon mergeIcons(Icon i1, Icon i2, int offsetTopRight) {
        Image image1 = ((ImageIcon) i1).getImage();
        Image image2 = ((ImageIcon) i2).getImage();

        Image image = new BufferedImage(i1.getIconWidth(), i1.getIconWidth(), BufferedImage.TRANSLUCENT);
        Graphics g = image.getGraphics();
        try {
            g.drawImage(image1, 0, 0, null);
            g.drawImage(image2, i1.getIconWidth() - i2.getIconWidth() /* + offsetTopRight/2 */, offsetTopRight, null);
        }
        finally {
            g.dispose();
        }

        return new ImageIcon(image);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy