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

com.hfg.image.ImageIO_Util Maven / Gradle / Ivy

There is a newer version: 20240423
Show newest version
package com.hfg.image;



import java.awt.Dimension;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Locale;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageOutputStream;

import com.hfg.util.StringUtil;


//------------------------------------------------------------------------------
/**
 * General Image IO functions using ImageIO.
 *
 * @author J. Alex Taylor, hairyfatguy.com
 */
//------------------------------------------------------------------------------
// com.hfg XML/HTML Coding Library
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
// J. Alex Taylor, President, Founder, CEO, COO, CFO, OOPS hairyfatguy.com
// [email protected]
//------------------------------------------------------------------------------

public class ImageIO_Util
{
   public static float DEFAULT_JPG_QUALITY = 0.85f;

   static
   {
      ImageIO.scanForPlugins();
   }

   //--------------------------------------------------------------------------
   public static void writeBufferedImageAsJpeg(BufferedImage inImage, OutputStream inStream)
   throws IOException
   {
      writeBufferedImageAsJpeg(inImage, inStream, DEFAULT_JPG_QUALITY);
   }

   //--------------------------------------------------------------------------
   public static void writeBufferedImageAsJpeg(BufferedImage inBufferedImage, OutputStream inStream, float inJpgQuality)
         throws IOException
   {
      ImageWriter jpegWriter = ImageIO.getImageWritersByFormatName("JPEG").next();

      ImageWriteParam params = jpegWriter.getDefaultWriteParam();
      params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
      params.setCompressionQuality(inJpgQuality);

      ImageOutputStream out = ImageIO.createImageOutputStream(inStream);
      jpegWriter.setOutput(out);
      jpegWriter.write(null, new IIOImage(inBufferedImage,null,null),params);
      jpegWriter.dispose();
   }

   //---------------------------------------------------------------------------
   public static Dimension getDimension(File inImgFile)
   {
      Dimension dimension;
      try
      {
         BufferedImage image = ImageIO.read(inImgFile);
         dimension = new Dimension(image.getWidth(), image.getHeight());
      }
      catch (IOException e)
      {
         throw new RuntimeException(e);
      }

      return dimension;
   }

   //---------------------------------------------------------------------------
   public static Dimension getDimension(InputStream inImgStream)
   {
      Dimension dimension;
      try
      {
         BufferedImage image = ImageIO.read(inImgStream);
         dimension = new Dimension(image.getWidth(), image.getHeight());
      }
      catch (IOException e)
      {
         throw new RuntimeException(e);
      }

      return dimension;
   }

   //--------------------------------------------------------------------------
   public static void convertImage(File inOrigImg, File inDestImg, float inCompressionQuality)
   {
      ImageFormat destFormat = ImageFormat.guessFormatFromName(inDestImg.getName());

      try
      {
         // Read input image from file
         BufferedImage srcImage = readImageFile(inOrigImg);

         if (destFormat == ImageFormat.JPEG)
         {
            Iterator writerIter = ImageIO.getImageWritersBySuffix(destFormat.getFileExtension());
            ImageWriteParam param = new JPEGImageWriteParam(Locale.getDefault());
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(inCompressionQuality);
            ImageWriter writer =writerIter.next();
            IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(srcImage), param);
            ImageOutputStream outputStream = new FileImageOutputStream(inDestImg);
            writer.setOutput(outputStream);
            writer.write(metadata, new IIOImage(srcImage, null, metadata), param);
            writer.dispose();
            outputStream.close();
         }
         else
         {
            FileOutputStream outputStream = null;
            try
            {
               outputStream = new FileOutputStream(inDestImg);
               // Format to be converted to can be one of: jpeg, png, bmp, wbmp, and gif
               ImageIO.write(srcImage, destFormat.getFileExtension(), outputStream);
            }
            finally
            {
               if (outputStream != null) outputStream.close();
            }
         }
      }
      catch (IOException e)
      {
         throw new RuntimeException(e);
      }
   }
   /*
   BufferedImage sourceImage = ImageIO.read(inputStream);
   Image thumbnail = sourceImage.getScaledInstance(width, -1, Image.SCALE_SMOOTH);
   BufferedImage bufferedThumbnail = new BufferedImage(thumbnail.getWidth(null),
                                                       thumbnail.getHeight(null),
                                                       BufferedImage.TYPE_INT_RGB);
   bufferedThumbnail.getGraphics().drawImage(thumbnail, 0, 0, null);
   ImageIO.write(bufferedThumbnail, "jpeg", outputStream);
    */


   //--------------------------------------------------------------------------

   /**
    If the destination format is JPG, a default compression quality of 0.7 is used.
    */
   public static void scaleDownImage(File inImgFile, int inMaxDimension, File inDestFile)
   {
      scaleDownImage(inImgFile, inMaxDimension, inDestFile, 0.7f);
   }

   //---------------------------------------------------------------------------
   public static void scaleDownImage(File inOrigImgFile, int inMaxDimension, File inDestImgFile, float inCompressionQuality)
   {
      if (null == inOrigImgFile)
      {
         throw new RuntimeException("No source image was specified!");
      }

      ImageFormat destFormat = ImageFormat.guessFormatFromName(inDestImgFile.getName());

      try
      {
         // Read input image from file
         BufferedImage sourceImage = readImageFile(inOrigImgFile);

         int width = -1;
         int height = -1;
         if (sourceImage.getWidth() > sourceImage.getHeight())
         {
            width = inMaxDimension;
         }
         else
         {
            height = inMaxDimension;
         }

         Image resizedImage = sourceImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
         // Allocate a new BufferedImage
         BufferedImage bufferedResizedImage = new BufferedImage(resizedImage.getWidth(null),
               resizedImage.getHeight(null),
               BufferedImage.TYPE_INT_RGB);
         // Draw the resized image onto the new BufferedImage
         bufferedResizedImage.getGraphics().drawImage(resizedImage, 0, 0, null);

         if (destFormat == ImageFormat.JPEG)
         {
            Iterator writerIter = ImageIO.getImageWritersBySuffix(destFormat.getFileExtension());
            ImageWriteParam param = new JPEGImageWriteParam(Locale.getDefault());
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(inCompressionQuality);
            ImageWriter writer =writerIter.next();
            IIOMetadata metadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(bufferedResizedImage), param);
            ImageOutputStream outputStream = new FileImageOutputStream(inDestImgFile);
            writer.setOutput(outputStream);
            writer.write(metadata, new IIOImage(bufferedResizedImage, null, metadata), param);
            writer.dispose();
            outputStream.close();
         }
         else
         {
            FileOutputStream outputStream = null;
            try
            {
               outputStream = new FileOutputStream(inDestImgFile);
               // Format to be converted to can be one of: jpeg, png, bmp, wbmp, and gif
               if (! ImageIO.write(bufferedResizedImage, destFormat.getFileExtension(), outputStream))
               {
                  String msg = "The destination image " + StringUtil.singleQuote(inDestImgFile) + " couldn't be written!";
                  if (destFormat.equals(ImageFormat.TIFF))
                  {
                     msg += " The jai-imageio-core jar is needed to read/write TIFF format.";
                  }

                  throw new RuntimeException(msg);
               }
            }
            finally
            {
               if (outputStream != null) outputStream.close();
            }
         }
      }
      catch (IOException e)
      {
         throw new RuntimeException(e);
      }
   }


   //--------------------------------------------------------------------------
   private static BufferedImage readImageFile(File inSrcImg)
         throws IOException
   {
      BufferedImage srcImage = null;

      ImageFormat srcFormat = ImageFormat.guessFormatFromName(inSrcImg.getName());

      FileInputStream inputStream = null;
      try
      {
         inputStream = new FileInputStream(inSrcImg);

         // Read input image from file
         srcImage = ImageIO.read(inputStream);
         if (null == srcImage)
         {
            String msg = "The input image " + StringUtil.singleQuote(inSrcImg) + " couldn't be read!";
            if (srcFormat != null
                && srcFormat.equals(ImageFormat.TIFF))
            {
               msg += " The jai-imageio-core jar is needed to read/write TIFF format.";
            }

            throw new RuntimeException(msg);
         }
      }
      finally
      {
         if (inputStream != null) inputStream.close();
      }

      return srcImage;
   }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy