Here you can find the source of crop4Square(BufferedImage source, File to, int size)
public static void crop4Square(BufferedImage source, File to, int size)
//package com.java2s; //License from project: Open Source License import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.FileImageOutputStream; public class Main { public static void crop4Square(BufferedImage source, File to, int size) { try {/*from w w w .java 2s . com*/ String mimeType = "image/jpeg"; if (to.getName().endsWith(".png")) { mimeType = "image/png"; } if (to.getName().endsWith(".gif")) { mimeType = "image/gif"; } int width = source.getWidth(); int height = source.getHeight(); Image croppedImage; if (width == height) { croppedImage = source.getScaledInstance(size, size, Image.SCALE_SMOOTH); } else { int left, top; if (width > height) { left = (width - height) / 2; top = 0; croppedImage = source.getSubimage(left, top, height, height); } else { left = 0; top = (height - width) / 2; croppedImage = source.getSubimage(left, top, width, width); } croppedImage = croppedImage.getScaledInstance(size, size, Image.SCALE_SMOOTH); } // out BufferedImage dest = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); Graphics graphics = dest.getGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, size, size); graphics.drawImage(croppedImage, 0, 0, null); ImageWriter writer = ImageIO.getImageWritersByMIMEType(mimeType).next(); writer.setOutput(new FileImageOutputStream(to)); IIOImage image = new IIOImage(dest, null, null); writer.write(null, image, createImageWriteParam(writer)); } catch (Exception e) { throw new RuntimeException(e); } } public static ImageWriteParam createImageWriteParam(ImageWriter writer) { ImageWriteParam params = writer.getDefaultWriteParam(); // JPEGImageWriteParam jpegImageWriteParam = new // JPEGImageWriteParam(writer.getLocale()); // jpegImageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); // jpegImageWriteParam.setCompressionQuality(0.8F); params.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); params.setCompressionQuality(0.95F); return params; } }