Java Image Scale ScaleToSize(Image srcImg, int w, int h)

Here you can find the source of ScaleToSize(Image srcImg, int w, int h)

Description

Scale To Size

License

Apache License

Declaration

public static BufferedImage ScaleToSize(Image srcImg, int w, int h) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.awt.Graphics;
import java.awt.Graphics2D;

import java.awt.Image;

import java.awt.RenderingHints;

import java.awt.geom.AffineTransform;

import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;

import java.io.BufferedInputStream;

import java.io.File;
import java.io.IOException;

import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;

import javax.swing.ImageIcon;

public class Main {
    static int COLORTYPE = BufferedImage.TYPE_INT_ARGB;

    public static BufferedImage ScaleToSize(Image srcImg, int w, int h) {
        if (w == -1)
            w = srcImg.getWidth(null);/*from   w  w w .ja v  a  2  s . co m*/
        if (h == -1)
            h = srcImg.getHeight(null);
        if (w == -1 || h == -1) {
            srcImg = new ImageIcon(srcImg).getImage();
            w = srcImg.getWidth(null);
            h = srcImg.getHeight(null);
        }
        System.out.println("AWT Image Wt: " + w + " And Ht: " + h);
        BufferedImage buffImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = buffImg.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(srcImg, 0, 0, null);
        g2.dispose();
        return buffImg;
    }

    public static BufferedImage ScaleToSize(String inFileName, int maxCols, int maxRows, String outFileName,
            String format) {
        BufferedImage img = LoadImage(inFileName);
        BufferedImage altImg = ScaleToSize(img, maxCols, maxRows);
        SaveImageToFile(altImg, outFileName, format);
        return altImg;
    }

    public static BufferedImage ScaleToSize(BufferedImage bimg, int maxCols, int maxRows) {
        if (maxCols == -1)
            maxCols = bimg.getWidth(null);
        if (maxRows == -1)
            maxRows = bimg.getHeight(null);
        if (maxCols == -1 || maxRows == -1) {
            Image srcImg = new ImageIcon(bimg).getImage();
            maxCols = srcImg.getWidth(null);
            maxRows = srcImg.getHeight(null);
        }
        BufferedImage bimgnew = new BufferedImage(maxCols, maxRows, COLORTYPE);
        Graphics g = bimgnew.createGraphics();
        g.drawImage(bimg, 0, 0, maxCols, maxRows, null);
        // g.drawImage(bimg, 0, 0, null);
        g.dispose();
        return (bimgnew);
    }

    public static void drawImage(BufferedImage srcImg, BufferedImage img2Draw, int w, int h) {
        if (w == -1)
            w = (int) (srcImg.getWidth() / 2);
        if (h == -1)
            h = (int) (srcImg.getHeight() / 2);
        System.out.println("AWT Image Wt: " + w + " And Ht: " + h);
        Graphics2D g2 = srcImg.createGraphics();
        g2.drawImage(img2Draw, w, h, null);
        g2.dispose();
    }

    public static byte[] loadImage(String imgPath, Class caller) {
        int MAX_IMAGE_SIZE = 2400; // Change this to the size of
        // your biggest image, in bytes.
        byte buf[] = null;
        int count = 0;
        System.out.println("Load Image Stream: " + imgPath);
        BufferedInputStream imgStream = null;
        imgStream = new BufferedInputStream(caller.getResourceAsStream(imgPath));
        if (imgStream == null) {
            System.err.println("Couldn't find file: " + imgPath);
            return null;
        }

        // Creating the Image Icon from the stream
        try {
            System.out.println("Image Stream is Not Null: " + imgStream);
            System.out.println("Image Stream 4: " + imgPath + " is: " + imgStream.available());
            buf = new byte[imgStream.available()];
            count = imgStream.read(buf, 0, buf.length);
            System.out.println("Buffered Size: " + buf.length + " count: " + count);
            imgStream.close();
        } catch (IOException ioe) {
            System.err.println("Couldn't read stream from file: " + imgPath);
            return null;
        } catch (Throwable th) {
            th.printStackTrace();
            System.out.println("Cought Exception while reading stream");
            return null;
        }
        if (count <= 0) {
            System.err.println("Empty file: " + imgPath);
            return null;
        }
        return buf;
    }

    public static Image loadImage(byte[] imgStr, int imageSize) {
        ImageIcon imgIcon = new ImageIcon(imgStr);
        if (imgIcon == null)
            return null;
        return getScaledImage(imgIcon.getImage(), imageSize);
    }

    public static Image loadImage(String filePath, int imageSize) {
        ImageIcon imgIcon = new ImageIcon(filePath);
        if (imgIcon == null)
            return null;
        return getScaledImage(imgIcon.getImage(), imageSize);
    }

    public static BufferedImage LoadImage(String filename) {
        return LoadImage(new File(filename));
    }

    public static BufferedImage LoadImage(File imgFile) {
        BufferedImage bimg = null;
        try {
            System.out.println("Image File Size: " + imgFile.length());
            bimg = ImageIO.read(imgFile);
        } catch (Exception e) {
            System.out.println("Exception at LoadImage");
            e.printStackTrace();
        }
        return bimg;
    }

    public static void SaveImageToFile(Image img, String filename, String outformat) {
        BufferedImage bimg = ScaleToSize(img, -1, -1);
        if (outformat.equalsIgnoreCase("JPEG") || outformat.equalsIgnoreCase("JPG"))
            SaveJPEG(bimg, new File(filename));
        else
            SaveImageToFile(bimg, filename, outformat);
    }

    public static void SaveImageToFile(BufferedImage bimg, String filename, String outformat) {
        File f = new File(filename);
        if (outformat.equalsIgnoreCase("JPEG") || outformat.equalsIgnoreCase("JPG"))
            SaveJPEG(bimg, f);
        else
            SaveImageToFile(bimg, f, outformat);
    }

    public static void SaveImageToFile(BufferedImage bimg, File f, String outformat) {
        if (outformat.equalsIgnoreCase("JPEG") || outformat.equalsIgnoreCase("JPG"))
            SaveJPEG(bimg, f);
        try {
            ImageIO.write(bimg, outformat, f);
        } catch (Exception e) {
            System.out.println("SaveImage");
            e.printStackTrace();
        }
    }

    public static Image getScaledImage(Image image, int imageSize) {
        if (imageSize == -1 || image.getWidth(null) <= imageSize)
            return image;
        // Reseampling the Image to create Thumbview. The getScaledInstance
        // method
        // maintains the Aspect Ratio.
        image = image.getScaledInstance(imageSize, -1, Image.SCALE_DEFAULT);
        return image;
    }

    public static void SaveJPEG(BufferedImage bimg, File file) {
        // *********************** For JPEG output files, this code is required.
        AffineTransform s = new AffineTransform();
        AffineTransformOp sop = new AffineTransformOp(s, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
        BufferedImage jpgimage = new BufferedImage(bimg.getWidth(), bimg.getHeight(), BufferedImage.TYPE_INT_RGB);
        sop.filter(bimg, jpgimage);
        // *********************************************************
        Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
        ImageWriter writer = (ImageWriter) iter.next();

        // instantiate an ImageWriteParam object with default compression
        // options

        ImageWriteParam iwp = writer.getDefaultWriteParam();

        iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        iwp.setCompressionQuality(1); // an integer between 0 and 1
        // 1 specifies minimum compression and maximum quality

        try {
            FileImageOutputStream output = new FileImageOutputStream(file);
            writer.setOutput(output);
            IIOImage image = new IIOImage(jpgimage, null, null);
            writer.write(null, image, iwp);
            output.close();
        } catch (Exception e) {
            System.out.println("SaveJPEG");
            e.printStackTrace();
        }
    }
}

Related

  1. getScaleToFit(JPanel componentToFit, File imageFile)
  2. scaleImage(Image image, float scale)
  3. scaleImage(Image image, float widthPercentage, float heightPercentage)
  4. scaleImage(Image sourceImage, int width, int height)
  5. scaleImage(Image src, int width, int height)