/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import javax.activation.MimetypesFileTypeMap;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
/**
*
* @author monirul
*/
public class ImageResizer {
@SuppressWarnings("OverridableMethodCallInConstructor")
ImageResizer()
{
try
{
// this is just for my own local testing
// simulate byte[] input from database
FileWriter writer = new FileWriter(new File("D:/output2/error.txt"));
File source = new File("D:/input/");
File[] dir = null;
if(source.isDirectory())
{
// Get a list of all of the Excel spreadsheet files (workbooks) in
// the source folder/directory
dir = source.listFiles();
}
else
{
// Assume that it must be a file handle - although there are other
// options the code should perhaps check - and store the reference
// into the filesList variable.
dir = new File[]{source};
}
int i=0;
for(File dir1: dir)
{
i++;
System.out.println("Folder :"+i+" "+dir1);
File[] filesList = null;
//System.out.println(dir1.toString());
if(dir1.isDirectory())
{
try
{
File outputPath = new File(dir1.toString().replaceAll("input","output1"));
outputPath.mkdir();
//System.out.println("Monirul");
}
catch(Exception e)
{
//System.out.println(e);
}
try
{
File outputPath = new File(dir1.toString().replaceAll("input","output2"));
outputPath.mkdir();
//System.out.println("Monirul");
}
catch(Exception e)
{
//System.out.println(e);
}
// Get a list of all of the Excel spreadsheet files (workbooks) in
// the source folder/directory
filesList = dir1.listFiles();
getFiles1(filesList,writer);
}
else
{
// Assume that it must be a file handle - although there are other
// options the code should perhaps check - and store the reference
// into the filesList variable.
filesList = new File[]{dir1};
getFiles1(filesList,writer);
}
}
writer.close();
}
catch(Exception e)
{
// System.out.println(e);
}
}
public void getFiles1(File[] filesList,FileWriter writer)
{
try
{
for(File imageFile:filesList)
{
//BufferedImage image = ImageIO.read(new File("D:/input/image1.jpg"));
BufferedImage image1 = ImageIO.read(imageFile);
BufferedImage image2 = ImageIO.read(imageFile);
int imageSourceWidth = image1.getWidth();
int imageSourceHeight = image1.getHeight();
int newImageHight1=0;
int newImageWidth1=0;
int newImageHight2=0;
int newImageWidth2=0;
//System.out.println(imageSourceWidth);
//System.out.println(imageSourceHeight);
if(imageSourceWidth>imageSourceHeight)
{
newImageHight1=50;
newImageWidth1=100;
newImageHight2=300;
newImageWidth2=450;
}
else if(imageSourceWidth
{
newImageHight1=100;
newImageWidth1=50;
newImageHight2=450;
newImageWidth2=300;
}
else if(imageSourceWidth==imageSourceHeight)
{
newImageHight1=106;
newImageWidth1=106;
newImageHight2=450;
newImageWidth2=450;
}
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(image1, "PNG", byteArrayOutputStream);
byte[] sourceBytes = byteArrayOutputStream.toByteArray();
byte[] scaledBytes = resizeImage1(sourceBytes,imageSourceWidth,imageSourceHeight,newImageWidth1,newImageHight1);
// write out again to check result
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(scaledBytes);
image1 = ImageIO.read(byteArrayInputStream);
String path = imageFile.toString().replaceAll("input","output1");
//System.out.println(path);
ImageIO.write(image1, "PNG", new File(path));
}
{
// File file = new File();
String fType = new MimetypesFileTypeMap().getContentType(imageFile).replaceAll("image/", "");
System.out.println("Extension of the file is : "+fType);
String path = imageFile.toString().replaceAll("input","output2");
try
{
compressAndSave(image2,0.5f,fType,newImageHight2,newImageWidth2,new File(path));
}
catch(Exception e)
{
writer.append(path);
writer.append("\n");
System.out.println(e);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(image2, "PNG", byteArrayOutputStream);
byte[] sourceBytes = byteArrayOutputStream.toByteArray();
byte[] scaledBytes = resizeImage1(sourceBytes,imageSourceWidth,imageSourceHeight,newImageWidth2,newImageHight2);
// write out again to check result
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(scaledBytes);
image2 = ImageIO.read(byteArrayInputStream);
String path1 = imageFile.toString().replaceAll("input","output2");
//System.out.println(path);
ImageIO.write(image2, "PNG", new File(path1));
}
// ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// ImageIO.write(image2, "PNG", byteArrayOutputStream);
// byte[] sourceBytes = byteArrayOutputStream.toByteArray();
// byte[] scaledBytes = resizeImage2(image2,sourceBytes,imageSourceWidth,imageSourceHeight,newImageWidth2,newImageHight2);
// // write out again to check result
// ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(scaledBytes);
// image2 = ImageIO.read(byteArrayInputStream);
}
}
}catch(Exception e)
{
// System.out.println(e);
}
}
public static void main(String []args)
{
new ImageResizer();
}
public static void compressAndSave(BufferedImage image, float quality,String fileType,int newHeight,int newWidth,File outputFile) throws IOException
{
// Get a ImageWriter for jpeg format.
Iterator
writers = ImageIO.getImageWritersBySuffix(fileType);
if (!writers.hasNext()) throw new IllegalStateException("No writers found");
ImageWriter writer = (ImageWriter) writers.next();
// Create the ImageWriteParam to compress the image.
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
// The output will be a ByteArrayOutputStream (in memory)
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
ImageOutputStream ios = ImageIO.createImageOutputStream(bos);
writer.setOutput(ios);
writer.write(null, new IIOImage(image, null, null), param);
ios.flush(); // otherwise the buffer size will be zero!
// From the ByteArrayOutputStream create a RenderedImage.
ByteArrayInputStream in = new ByteArrayInputStream(bos.toByteArray());
BufferedImage out = ImageIO.read(in);
int type=out.getType();
int size = bos.toByteArray().length;
BufferedImage resizedImage = new BufferedImage(newWidth,newHeight, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(image, 0, 0,newWidth,newHeight, null);
g.dispose();
//Uncomment code below to save the compressed files.
ImageIO.write(resizedImage,fileType,outputFile);
//FileImageOutputStream output = new FileImageOutputStream(outputFile);
//writer.setOutput(output); writer.write(null, new IIOImage(resizedImage, null,null), param);
}
private byte[] resizeImage2(BufferedImage image2,byte[] sourceBytes,int imageSourceWidth,int imageSourceHeight, int newWidth, int newHeight) throws Exception
{
byte[] scaledBytes;
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(sourceBytes);
// Why not just use ImageIO.read(inputStream)? - Because there would be
// no way to know the original image format (I am assuming here that
// you need to write back the image in the same format as the original)
ImageInputStream imageInputStream = ImageIO.createImageInputStream(byteArrayInputStream);
// assuming there is at least one ImageReader able to read the image
ImageReader imageReader = ImageIO.getImageReaders(imageInputStream).next();
// save image format name so we can write it back in the same format
String formatName = imageReader.getFormatName();
imageReader.setInput(imageInputStream);
BufferedImage sourceImage = imageReader.read(0);
//int imageSourceWidth = sourceImage.getWidth();
//int imageSourceHeight = sourceImage.getHeight();
//if (imageSourceWidth > newWidth) {
// be careful with integer divisions ( 500 / 1000 = 0!)
//double scaleFactor = (double) newWidth / (double) imageSourceWidth;
//int newHeight = (int) Math.round(imageSourceHeight * scaleFactor);
//System.out.println("newWidth=" + newWidth + ", newHeight=" + newHeight + ", formatName=" + formatName);
// getScaledInstance provides the best downscaling quality but is
// orders of magnitude slower than the alternatives
// since you're saying performance is not issue, I leave it as is
Image scaledImage = sourceImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
// Unfortunately we need a RenderedImage to use ImageIO.write.
// So the next lines convert whatever type of Image was returned
// by getScaledImage into a BufferedImage.
// Using TYPE_INT_ARGB so potential alpha channels are preserved
BufferedImage scaledBufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = scaledBufferedImage.createGraphics();
g2.drawImage(scaledImage, 0, 0, null);
g2.dispose();
// Now use ImageIO.write to encode the image back into a byte[],
// using the same image format
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(32768);
ImageIO.write(scaledBufferedImage, formatName, byteArrayOutputStream);
scaledBytes = byteArrayOutputStream.toByteArray();
//} else {
// if not scaling happened, just return the original byte[]
//scaledBytes = sourceBytes;
//}
return scaledBytes;
}
private byte[] resizeImage1(byte[] sourceBytes,int imageSourceWidth,int imageSourceHeight, int newWidth, int newHeight) throws Exception
{
byte[] scaledBytes;
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(sourceBytes);
// Why not just use ImageIO.read(inputStream)? - Because there would be
// no way to know the original image format (I am assuming here that
// you need to write back the image in the same format as the original)
ImageInputStream imageInputStream = ImageIO.createImageInputStream(byteArrayInputStream);
// assuming there is at least one ImageReader able to read the image
ImageReader imageReader = ImageIO.getImageReaders(imageInputStream).next();
// save image format name so we can write it back in the same format
String formatName = imageReader.getFormatName();
imageReader.setInput(imageInputStream);
BufferedImage sourceImage = imageReader.read(0);
//int imageSourceWidth = sourceImage.getWidth();
//int imageSourceHeight = sourceImage.getHeight();
//if (imageSourceWidth > newWidth) {
// be careful with integer divisions ( 500 / 1000 = 0!)
//double scaleFactor = (double) newWidth / (double) imageSourceWidth;
//int newHeight = (int) Math.round(imageSourceHeight * scaleFactor);
//System.out.println("newWidth=" + newWidth + ", newHeight=" + newHeight + ", formatName=" + formatName);
// getScaledInstance provides the best downscaling quality but is
// orders of magnitude slower than the alternatives
// since you're saying performance is not issue, I leave it as is
Image scaledImage = sourceImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
// Unfortunately we need a RenderedImage to use ImageIO.write.
// So the next lines convert whatever type of Image was returned
// by getScaledImage into a BufferedImage.
// Using TYPE_INT_ARGB so potential alpha channels are preserved
BufferedImage scaledBufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = scaledBufferedImage.createGraphics();
g2.drawImage(scaledImage, 0, 0, null);
g2.dispose();
// Now use ImageIO.write to encode the image back into a byte[],
// using the same image format
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(32768);
ImageIO.write(scaledBufferedImage, formatName, byteArrayOutputStream);
scaledBytes = byteArrayOutputStream.toByteArray();
//} else {
// if not scaling happened, just return the original byte[]
//scaledBytes = sourceBytes;
//}
return scaledBytes;
}
}