Java to create thumbnails scale image scale generation method

  • 2020-04-01 03:34:03
  • OfStack

The example of this article describes the Java implementation of creating thumbnails, scale image scale generation method. Share with you for your reference. The specific implementation method is as follows:

This example supports zooming the width and height of an Image to the specified width and height, and saving it in the specified directory.

The specific code is as follows:


package com.hoo.util;
 
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
 
/**
 * <b>function:</b> Zoom image tool class, create thumbnails, scale image scale
 * @author hoojo
 * @createDate 2012-2-3 In the morning 10:08:47
 * @file ScaleImageUtils.java
 * @package com.hoo.util
 * @version 1.0
 */
public abstract class ScaleImageUtils {
 
    private static final float DEFAULT_SCALE_QUALITY = 1f;
    private static final String DEFAULT_IMAGE_FORMAT = ".jpg"; //Image file format
    private static final String DEFAULT_FILE_PATH = "C:/temp-";
   
    /**
     * <b>function:</b> Set image compression quality enumeration class;
     * Some guidelines: 0.75 high quality , 0.5  medium quality , 0.25 low quality
     * @author hoojo
     * @createDate 2012-2-7 In the morning 11:31:45
     * @file ScaleImageUtils.java
     * @package com.hoo.util
     * @project JQueryMobile
     * @version 1.0
     */
    public enum ImageQuality {
        max(1.0f), high(0.75f), medium(0.5f), low(0.25f);
       
        private Float quality;
        public Float getQuality() {
            return this.quality;
        }
        ImageQuality(Float quality) {
            this.quality = quality;
        }
    }
   
    private static Image image;
   
    /**
     * <b>function:</b> The scale of the image reduction is calculated from the size of the target object and the standard (specified) size
     * @author hoojo
     * @createDate 2012-2-6 In the afternoon 04:41:48
     * @param targetWidth Target width
     * @param targetHeight Target height
     * @param standardWidth Standard (specified) width
     * @param standardHeight Standard height
     * @return The smallest appropriate proportion
     */
    public static double getScaling(double targetWidth, double targetHeight, double standardWidth, double standardHeight) {
        double widthScaling = 0d;
        double heightScaling = 0d;
        if (targetWidth > standardWidth) {
            widthScaling = standardWidth / (targetWidth * 1.00d);
        } else {
            widthScaling = 1d;
        }
        if (targetHeight > standardHeight) {
            heightScaling = standardHeight / (targetHeight * 1.00d);
        } else {
            heightScaling = 1d;
        }
        return Math.min(widthScaling, heightScaling);
    }
   
    /**
     * <b>function:</b> will Image Scale the width and height to the specified width , height And save in savePath directory
     * @author hoojo
     * @createDate 2012-2-6 In the afternoon 04:54:35
     * @param width Zoom width
     * @param height Height of scaling
     * @param savePath Save the directory
     * @param targetImage The target image is about to be scaled
     * @return Image save path, name
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resize(int width, int height, String savePath, Image targetImage) throws ImageFormatException, IOException {
        width = Math.max(width, 1);
        height = Math.max(height, 1);
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        image.getGraphics().drawImage(targetImage, 0, 0, width, height, null);
       
        if (savePath == null || "".equals(savePath)) {
            savePath = DEFAULT_FILE_PATH + System.currentTimeMillis() + DEFAULT_IMAGE_FORMAT;
        }
       
        FileOutputStream fos = new FileOutputStream(new File(savePath));
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
        encoder.encode(image);
 
        image.flush();
        fos.flush();
        fos.close();
       
        return savePath;
    }
   
    /**
     * <b>function:</b> The image scaling quality can be set and the image can be scaled according to the specified width and height
     * @author hoojo
     * @createDate 2012-2-7 In the morning 11:01:27
     * @param width Zoom width
     * @param height Height of scaling
     * @param quality Image compression quality, Max 1 ; Using enumerated values: {@link ImageQuality}
     *             Some guidelines: 0.75 high quality , 0.5  medium quality , 0.25 low quality
     * @param savePath Save the directory
     * @param targetImage The target image is about to be scaled
     * @return Image save path, name
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resize(int width, int height, Float quality, String savePath, Image targetImage) throws ImageFormatException, IOException {
        width = Math.max(width, 1);
        height = Math.max(height, 1);
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        image.getGraphics().drawImage(targetImage, 0, 0, width, height, null);
       
        if (savePath == null || "".equals(savePath)) {
            savePath = DEFAULT_FILE_PATH + System.currentTimeMillis() + DEFAULT_IMAGE_FORMAT;
        }
       
        FileOutputStream fos = new FileOutputStream(new File(savePath));
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
       
        JPEGEncodeParam encodeParam = JPEGCodec.getDefaultJPEGEncodeParam(image);
        if (quality == null || quality <= 0) {
            quality = DEFAULT_SCALE_QUALITY;
        }
         
        encodeParam.setQuality(quality, true); 
        encoder.encode(image, encodeParam); 
 
        image.flush();
        fos.flush();
        fos.close();
       
        return savePath;
    }
   
    /**
     * <b>function:</b> Calculate the appropriate size of the image reduction by specifying the size and the size of the image
     * @author hoojo
     * @createDate 2012-2-6 In the afternoon 05:53:10
     * @param width Specified width
     * @param height Specified height
     * @param image Image files
     * @return Returns the width and height int An array of
     */
    public static int[] getSize(int width, int height, Image image) {
        int targetWidth = image.getWidth(null);
        int targetHeight = image.getHeight(null);
        double scaling = getScaling(targetWidth, targetHeight, width, height);
        long standardWidth = Math.round(targetWidth * scaling);
        long standardHeight = Math.round(targetHeight * scaling);
        return new int[] { Integer.parseInt(Long.toString(standardWidth)), Integer.parseInt(String.valueOf(standardHeight)) };
    }
   
    /**
     * <b>function:</b> Returns a zoomed in or out width and height with the specified scale and image object
     * @author hoojo
     * @createDate 2012-2-7 In the morning 10:27:59
     * @param scale scaling
     * @param image Image objects
     * @return Returns width and height
     */
    public static int[] getSize(float scale, Image image) {
        int targetWidth = image.getWidth(null);
        int targetHeight = image.getHeight(null);
        long standardWidth = Math.round(targetWidth * scale);
        long standardHeight = Math.round(targetHeight * scale);
        return new int[] { Integer.parseInt(Long.toString(standardWidth)), Integer.parseInt(String.valueOf(standardHeight)) };
    }
   
    public static int[] getSize(int width, Image image) {
        int targetWidth = image.getWidth(null);
        int targetHeight = image.getHeight(null);
        long height = Math.round((targetHeight * width) / (targetWidth * 1.00f));
        return new int[] { width, Integer.parseInt(String.valueOf(height)) };
    }
   
    public static int[] getSizeByHeight(int height, Image image) {
        int targetWidth = image.getWidth(null);
        int targetHeight = image.getHeight(null);
        long width = Math.round((targetWidth * height) / (targetHeight * 1.00f));
        return new int[] { Integer.parseInt(String.valueOf(width)), height };
    }
   
    /**
     *
     * <b>function:</b> Specifies the targetFile The width and height of the image file are greater than specified width , height The image is zoomed out and saved in savePath directory
     * @author hoojo
     * @createDate 2012-2-6 In the afternoon 04:57:02
     * @param width Reduced width
     * @param height Reduced height
     * @param savePath Save the directory
     * @param targetImage Change the target image
     * @return Image save path, name
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resize(int width, int height, String savePath, File targetFile) throws ImageFormatException, IOException {
        image = ImageIO.read(targetFile);
        int[] size = getSize(width, height, image);
        return resize(size[0], size[1], savePath, image);
    }
   
    /**
     *
     * <b>function:</b> Specifies the targetURL The width and height of the network image file are greater than specified width , height The image is zoomed out and saved in savePath directory
     * @author hoojo
     * @createDate 2012-2-6 In the afternoon 04:57:07
     * @param width Reduced width
     * @param height Reduced height
     * @param savePath Save the directory
     * @param targetImage Change the target image
     * @return Image save path, name
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resize(int width, int height, String savePath, URL targetURL) throws ImageFormatException, IOException {
        image = ImageIO.read(targetURL);
        int[] size = getSize(width, height, image);
        return resize(size[0], size[1], savePath, image);
    }
   
    /**
     * <b>function:</b> Scale a local image file to the specified scale
     * @author hoojo
     * @createDate 2012-2-7 In the morning 10:29:18
     * @param scale scaling
     * @param savePath Save the file path and name
     * @param targetFile Local picture file
     * @return New file name
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resize(float scale, String savePath, File targetFile) throws ImageFormatException, IOException {
        image = ImageIO.read(targetFile);
        int[] size = getSize(scale, image);
        return resize(size[0], size[1], savePath, image);
    }
   
    /**
     * <b>function:</b> Scale a network image file to the specified scale
     * @author hoojo
     * @createDate 2012-2-7 In the morning 10:30:56
     * @param scale scaling
     * @param savePath Save the file path and name
     * @param targetFile Local picture file
     * @return New file name
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resize(float scale, String savePath, URL targetURL) throws ImageFormatException, IOException {
        image = ImageIO.read(targetURL);
        int[] size = getSize(scale, image);
        return resize(size[0], size[1], savePath, image);
    }
   
    /**
     * <b>function:</b> Scale the local image equally to a fixed width
     * @author hoojo
     * @createDate 2012-2-7 In the morning 10:49:56
     * @param width A fixed width
     * @param savePath Save path, name
     * @param targetFile Local target file
     * @return Back to save path
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resize(int width, String savePath, File targetFile) throws ImageFormatException, IOException {
        image = ImageIO.read(targetFile);
        int[] size = getSize(width, image);
        return resize(size[0], size[1], savePath, image);
    }
   
    /**
     * <b>function:</b> Scale the network image according to the fixed width
     * @author hoojo
     * @createDate 2012-2-7 In the morning 10:50:52
     * @param width A fixed width
     * @param savePath Save path, name
     * @param targetFile Local target file
     * @return Back to save path
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resize(int width, String savePath, URL targetURL) throws ImageFormatException, IOException {
        image = ImageIO.read(targetURL);
        int[] size = getSize(width, image);
        return resize(size[0], size[1], savePath, image);
    }
   
    /**
     *
     * <b>function:</b> Scale the local image to a fixed height
     * @author hoojo
     * @createDate 2012-2-7 In the morning 10:51:17
     * @param height Fixed height
     * @param savePath Save path, name
     * @param targetFile Local target file
     * @return Back to save path
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resizeByHeight(int height, String savePath, File targetFile) throws ImageFormatException, IOException {
        image = ImageIO.read(targetFile);
        int[] size = getSizeByHeight(height, image);
        return resize(size[0], size[1], savePath, image);
    }
   
    /**
     * <b>function:</b> Scale the network image according to the fixed height
     * @author hoojo
     * @createDate 2012-2-7 In the morning 10:52:23
     * @param height Fixed height
     * @param savePath Save path, name
     * @param targetFile Local target file
     * @return Back to save path
     * @throws ImageFormatException
     * @throws IOException
     */
    public static String resizeByHeight(int height, String savePath, URL targetURL) throws ImageFormatException, IOException {
        image = ImageIO.read(targetURL);
        int[] size = getSizeByHeight(height, image);
        return resize(size[0], size[1], savePath, image);
    }
   
    /**
     * <b>function:</b>
     * @author hoojo
     * @createDate 2012-2-3 In the morning 10:08:47
     * @param args
     * @throws IOException
     * @throws MalformedURLException
     * @throws ImageFormatException
     */
    public static void main(String[] args) throws ImageFormatException, MalformedURLException, IOException {
       
        System.out.println(ScaleImageUtils.resize(140, 140, null, new URL("http://www.open-open.com/lib/images/logo.jpg")));
        ScaleImageUtils.resize(100, 100, ImageQuality.high.getQuality(), null, ImageIO.read(new URL("http://www.open-open.com/lib/images/logo.jpg")));
    }
}

I hope this article has been helpful to your Java programming.


Related articles: