Scale, convert images : BufferedImage « 2D Graphics GUI « Java

Home
Java
1.2D Graphics GUI
2.2D Graphics GUI1
3.3D
4.Advanced Graphics
5.Ant
6.Apache Common
7.Chart
8.Class
9.Collections Data Structure
10.Data Type
11.Database SQL JDBC
12.Design Pattern
13.Development Class
14.EJB3
15.Email
16.Event
17.File Input Output
18.Game
19.Generics
20.GWT
21.Hibernate
22.I18N
23.J2EE
24.J2ME
25.JDK 6
26.JNDI LDAP
27.JPA
28.JSP
29.JSTL
30.Language Basics
31.Network Protocol
32.PDF RTF
33.Reflection
34.Regular Expressions
35.Scripting
36.Security
37.Servlets
38.Spring
39.Swing Components
40.Swing JFC
41.SWT JFace Eclipse
42.Threads
43.Tiny Application
44.Velocity
45.Web Services SOA
46.XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
SCJP
Java » 2D Graphics GUI » BufferedImageScreenshots 
Scale, convert images
     
// revised from richfaces photoalbum

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.zip.*;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageInputStream;

/**
 * Utility class for operations with file-system
 *
 */

public class FileUtils {

    private static final String JPEG = "jpeg";
  private static final String JPG = "jpg";
  private static final int BUFFER_SIZE = 1024;
    private static final boolean CLOCK = true;
    private static final boolean VERIFY = true;

    /**
     * Utility method for copying file
     @param srcFile - source file
     @param destFile - destination file
     */
    public static void copyFile(File srcFile, File destFilethrows IOException {
        if (!srcFile.getPath().toLowerCase().endsWith(JPG&& !srcFile.getPath().toLowerCase().endsWith(JPEG)) {
            return;
        }
        final InputStream in = new FileInputStream(srcFile);
        final OutputStream out = new FileOutputStream(destFile);
        try{
            long millis = System.currentTimeMillis();
            CRC32 checksum;
            if (VERIFY) {
                checksum = new CRC32();
                checksum.reset();
            }
            final byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead = in.read(buffer);
            while (bytesRead >= 0) {
                if (VERIFY) {
                    checksum.update(buffer, 0, bytesRead);
                }
                out.write(buffer, 0, bytesRead);
                bytesRead = in.read(buffer);
            }
            if (CLOCK) {
                millis = System.currentTimeMillis() - millis;
                System.out.println("Copy file '" + srcFile.getPath() "' on " + millis / 1000L " second(s)");
            }
        }catch(IOException e){
          throw e;
        }finally{
          out.close();
            in.close();
        }
    }

    /**
     * Utility method for copying directory
     @param srcDir - source directory
     @param dstDir - destination directory
     */
    public static void copyDirectory(File srcDir, File dstDir)
            throws IOException {

        if (".svn".equals(srcDir.getName())) {
            return;
        }

        if (srcDir.isDirectory()) {
            if (!dstDir.exists()) {
                dstDir.mkdir();
            }

            for (String aChildren : srcDir.list()) {
                copyDirectory(new File(srcDir, aChildren)new File(dstDir, aChildren));
            }
        else {
            copyFile(srcDir, dstDir);
        }
    }

    /**
     * Utility method for delete directory
     @param dir - directory to delete
     @param isInitialDelete - determine if the deleting process running at startup or on destroy of application
     @return true if directory succesfully deleted
     */
    public static boolean deleteDirectory(File dir , boolean isInitialDelete){
        if (dir.isDirectory()) {
            if (dir.exists()) {
                for (File child : dir.listFiles()) {
                  try{
                    deleteDirectory(child, isInitialDelete);
                  }catch(Exception e){
                    if(isInitialDelete){
                      continue;
                    }
                    else return false;
                  }
                }
            }

        else {
            if (dir.exists()) {
                final boolean isFileDeleted = dir.delete();
                System.out.println((isFileDeleted ? "OK     " "ERROR "+
                        "Delete file '" + dir.getPath() '\'');
            }
        }
        dir.delete();
        return true;
    }
  
    /**
     * Utility method for concatenation names of collection of files
     @param files - array of strings to concatenate
     @return concatenated string
     */
  public static String joinFiles(String... files) {
    final StringBuilder res = new StringBuilder();
    for (String file : files) {
      res.append(file).append(File.separatorChar);
    }

    return res.substring(0, res.length() 1);
  }

   /**
     * Utility method for delete file
     @param file - file to delete
     */
    public static void deleteFile(File file) {
        if (file.exists()) {
            file.delete();
        }
    }
    
    /**
     * Utility method to read image from disk and transform image to BufferedImage object
     @param data - relative path to the image
     @param format - file prefix of the image
     @return BufferedImage representation of the image
     *
     */
    public static BufferedImage bitmapToImage(String data, String formatthrows IOException {
        final InputStream inb = new FileInputStream(data);
        final ImageReader rdr = ImageIO.getImageReadersByFormatName(format).next();
        final ImageInputStream imageInput = ImageIO.createImageInputStream(inb);
        rdr.setInput(imageInput);
        final BufferedImage image = rdr.read(0);
        inb.close();
        return image;
    }

    /**
     * Utility method to write BufferedImage object to disk
     @param image - BufferedImage object to save.
     @param data - relative path to the image
     @param format - file prefix of the image
     @return BufferedImage representation of the image
     *
     */
    public static void imageToBitmap(BufferedImage image, String data, String formatthrows IOException {
        final OutputStream inb = new FileOutputStream(data);
        final ImageWriter wrt = ImageIO.getImageWritersByFormatName(format).next();
        final ImageInputStream imageInput = ImageIO.createImageOutputStream(inb);
        wrt.setOutput(imageInput);
        wrt.write(image);
        inb.close();
    }

    /**
     * Convenience method that returns a scaled instance of the
     * provided {@code BufferedImage}.
     *
     @param img           the original image to be scaled
     @param targetWidth   the desired width of the scaled instance,
     *                      in pixels
     @param targetHeight  the desired height of the scaled instance,
     *                      in pixels
     @param hint          one of the rendering hints that corresponds to
     *                      {@code RenderingHints.KEY_INTERPOLATION} (e.g.
     *                      {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR},
     *                      {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR},
     *                      {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC})
     @param higherQuality if true, this method will use a multi-step
     *                      scaling technique that provides higher quality than the usual
     *                      one-step technique (only useful in downscaling cases, where
     *                      {@code targetWidth} or {@code targetHeight} is
     *                      smaller than the original dimensions, and generally only when
     *                      the {@code BILINEAR} hint is specified)
     @return a scaled version of the original {@code BufferedImage}
     */
    public static BufferedImage getScaledInstance(BufferedImage img,
                                                  int targetWidth,
                                                  int targetHeight,
                                                  Object hint,
                                                  boolean higherQuality) {
        final int type = img.getTransparency() == Transparency.OPAQUE ?
                BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
        BufferedImage ret = (BufferedImageimg;
        int w;
        int h;
        if (higherQuality) {
            // Use multi-step technique: start with original size, then
            // scale down in multiple passes with drawImage()
            // until the target size is reached
            w = img.getWidth();
            h = img.getHeight();
        else {
            // Use one-step technique: scale directly from original
            // size to target size with a single drawImage() call
            w = targetWidth;
            h = targetHeight;
        }

        do {
            if (higherQuality && w > targetWidth) {
                w /= 2;
                if (w < targetWidth) {
                    w = targetWidth;
                }
            }

            if (higherQuality && h > targetHeight) {
                h /= 2;
                if (h < targetHeight) {
                    h = targetHeight;
                }
            }

            final BufferedImage tmp = new BufferedImage(w, h, type);
            final Graphics2D g2 = tmp.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
            g2.drawImage(ret, 00, w, h, null);
            g2.dispose();

            ret = tmp;
        while (w != targetWidth || h != targetHeight);

        return ret;
    }

    /**
     * Utility method for creation of directory
     @param directory - directory to create
     *
     */
  public static void addDirectory(File directory) {
    if (directory.exists()) {
            deleteDirectory(directory, false);
        }
    directory.mkdirs();
  }
}

   
    
    
    
    
  
Related examples in the same category
1.BufferImage based Label
2.Animated clipping of an image and shapes with alphaAnimated clipping of an image and shapes with alpha
3.Renders an ellipse overlapping a rectangle with the compositing rule and alpha value selected by the userRenders an ellipse overlapping a rectangle with the compositing rule and alpha value selected by the user
4.Image operationsImage operations
5.BufferedImage with Jumbled images
6.Save an image after operations
7.Create buffered image that does not support transparency
8.Create a buffered image that supports transparency
9.Display image after operation
10.Compositing is the combining of elements from separate sources into single images
11.Convert a non-RGB image to an RGB buffered image
12.Blurring a Buffered Image
13.Sharpening a Buffered Image
14.Converting a Colored Buffered Image to Gray
15.Get average of a set of images with WritableRaster
16.Creating a BufferedImage from an Image object
17.Create Headless BufferedImage
18.Constructs a BufferedImage with a linear sRGB colorModel, and alpha
19.Creates and returns a buffered version of the specified image.
20.Make Linear Buffered Image
21.Renders multiple paragraphs of text in an array to an image (created and returned).
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.