The functions of this tool class: zooming images, cutting images, image type conversion, color to black and white, text watermark, picture watermark, etc.
The code copy is as follows:
package net.kitbox.util;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImagingOpException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* author:lldy
* time:2012-5-6 6:37:18 pm
* Image processing tool category: <br>
* Functions: zoom image, cut image, image type conversion, color to black and white, text watermark, picture watermark, etc.
*/
public class ImageUtils {
/**
* Relative to the location of the picture
*/
private static final int POSITION_UPPERLEFT=0;
private static final int POSITION_UPPERRIGHT=10;
private static final int POSITION_LOWERLEFT=1;
private static final int POSITION_LOWERRIGHT=11;
/**
* Several common picture formats
*/
public static String IMAGE_TYPE_GIF = "gif";// Graphic Exchange Format
public static String IMAGE_TYPE_JPG = "jpg";// Joint Photo Expert Group
public static String IMAGE_TYPE_JPEG = "jpeg";// Joint Photo Expert Group
public static String IMAGE_TYPE_BMP = "bmp";// English Bitmap (bitmap), it is the standard image file format in Windows operating system
public static String IMAGE_TYPE_PNG = "png";// Portable network graphics
private static ImageUtils instance;
private ImageUtils() {
instance = this;
}
/**
* Get an instance
* @return
*/
public static ImageUtils getInstance() {
if (instance == null) {
instance = new ImageUtils();
}
return instance;
}
public BufferedImage image2BufferedImage(Image image){
System.out.println(image.getWidth(null));
System.out.println(image.getHeight(null));
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bufferedImage.createGraphics();
g.drawImage(image, null, null);
g.dispose();
System.out.println(bufferedImage.getWidth());
System.out.println(bufferedImage.getHeight());
return bufferedImage;
}
/**
* Scale and convert format and save
* @param srcPath source path
* @param destPath target path
* @param width: Target width
* @param height: high target
* @param format: file format
* @return
*/
public static boolean scaleToFile(String srcPath, String destPath, int width, int height,String format) {
boolean flag = false;
try {
File file = new File(srcPath);
File destFile = new File(destPath);
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdir();
}
BufferedImage src = ImageIO.read(file); // Read in the file
Image image = src.getScaledInstance(width, height, Image.SCALE_DEFAULT);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // Draw the reduced figure
g.dispose();
flag = ImageIO.write(tag, format, new FileOutputStream(destFile));// Output to file stream
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
/**
* Scale Image, this method returns the image after the source image is scaled by percentage.
* @param inputImage
* @param percentage Percentage Permitted input 0<percentage<10000
* @return
*/
public static BufferedImage scaleByPercentage(BufferedImage inputImage,int percentage){
// Percentage allowed
if(0>percentage||percentage>10000){
throw new ImagingOpException("Error::Illegal parameters: percentage->"+percentage+", percentage should be greater than 0~ less than 10000");
}
//Get the original image transparency type
int type = inputImage.getColorModel().getTransparency();
//Get the target image size
int w=inputImage.getWidth()*percentage;
int h=inputImage.getHeight()*percentage;
//Open anti-aliasing
RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_ANTIALIAS_ON);
//Use high-quality compression
renderingHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_RENDER_QUALITY);
BufferedImage img = new BufferedImage(w, h, type);
Graphics2D graphics2d =img.createGraphics();
graphics2d.setRenderingHints(renderingHints);
graphics2d.drawImage(inputImage, 0, 0, w, h, 0, 0, inputImage
.getWidth(), inputImage.getHeight(), null);
graphics2d.dispose();
return img;
/*This code will return the Image type
return inputImage.getScaledInstance(inputImage.getWidth()*percentage,
inputImage.getHeight()*percentage, Image.SCALE_SMOOTH);
*/
}
/**
* Scaling Image, this method returns the image after the source image is scaled proportionally under the given maximum width limit.
* @param inputImage
* @param maxWidth: Maximum allowable width after compression
* @param maxHeight: Maximum allowable height after compression
* @throws java.io.IOException
* return
*/
public static BufferedImage scaleByPixelRate(BufferedImage inputImage, int maxWidth, int maxHeight) throws Exception {
//Get the original image transparency type
int type = inputImage.getColorModel().getTransparency();
int width = inputImage.getWidth();
int height = inputImage.getHeight();
int newWidth = maxWidth;
int newHeight =maxHeight;
//If the specified maximum width exceeds the proportion
if(width*maxHeight<height*maxWidth){
newWidth=(int)(newHeight*width/height);
}
//If the specified maximum height exceeds the proportion
if(width*maxHeight>height*maxWidth){
newHeight=(int)(newWidth*height/width);
}
//Open anti-aliasing
RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_ANTIALIAS_ON);
//Use high-quality compression
renderingHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_RENDER_QUALITY);
BufferedImage img = new BufferedImage(newWidth, newHeight, type);
Graphics2D graphics2d =img.createGraphics();
graphics2d.setRenderingHints(renderingHints);
graphics2d.drawImage(inputImage, 0, 0, newWidth, newHeight, 0, 0, width, height, null);
graphics2d.dispose();
return img;
}
/**
* Scaling Image, this method returns the image after the source image is scaled by the given width and height limit.
* @param inputImage
* @param maxWidth: Width after compression
* @param maxHeight: height after compression
* @throws java.io.IOException
* return
*/
public static BufferedImage scaleByPixel(BufferedImage inputImage, int newWidth, int newHeight) throws Exception {
//Get the original image transparency type
int type = inputImage.getColorModel().getTransparency();
int width = inputImage.getWidth();
int height = inputImage.getHeight();
//Open anti-aliasing
RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
//Use high-quality compression
renderingHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
BufferedImage img = new BufferedImage(newWidth, newHeight, type);
Graphics2D graphics2d =img.createGraphics();
graphics2d.setRenderingHints(renderingHints);
graphics2d.drawImage(inputImage, 0, 0, newWidth, newHeight, 0, 0, width, height, null);
graphics2d.dispose();
return img;
}
/**
* Cut the image and return the image in the specified range
* @param inputImage
* @param x Starting point horizontal axis
* @param y Starting point vertical coordinate
* @param width Cut image width: If the width exceeds the image, it will be changed to the image from x remaining width
* @param height Cut image height: If the height exceeds the image, it will be changed to the image's remaining height
* @param fill Specifies whether to fill if the target image size exceeds the size. If true, it means fill; false means not fill, the target image size will be reset.
* @return
*/
public static BufferedImage cut(BufferedImage inputImage,int x,int y,int width,int height,boolean fill){
//Get the original image transparency type
int type = inputImage.getColorModel().getTransparency();
int w = inputImage.getWidth();
int h = inputImage.getHeight();
int endx=x+width;
int endy=y+height;
if(x>w)
throw new ImagingOpException("The horizontal axis of the starting point exceeds the range of the source image");
if(y>h)
throw new ImagingOpException("The vertical coordinate of the starting point exceeds the source image range");
BufferedImage img;
//Fill in white
if(fill){
img = new BufferedImage(width, height, type);
//The width exceeds the limit
if((wx)<width){
width=wx;
endx=w;
}
//Height exceeds limit
if((hy)<height){
height=hy;
endy=h;
}
//Not repaired
}else{
//The width exceeds the limit
if((wx)<width){
width=wx;
endx=w;
}
//Height exceeds limit
if((hy)<height){
height=hy;
endy=h;
}
img = new BufferedImage(width, height, type);
}
//Open anti-aliasing
RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_ANTIALIAS_ON);
//Use high-quality compression
renderingHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_RENDER_QUALITY);
Graphics2D graphics2d =img.createGraphics();
graphics2d.setRenderingHints(renderingHints);
graphics2d.drawImage(inputImage, 0, 0, width, height, x, y, endx, endy, null);
graphics2d.dispose();
return img;
}
/**
* Cut the image and return the specified starting point position and the specified size image
* @param inputImage
* @param startPoint Start Point: upper left: 0, upper right: 10, lower left: 1, lower right: 11
* @param width Cut image width
* @param height Cut image height
* @param fill Specifies whether to fill if the target image size exceeds the size. If true, it means fill; false means not fill, the target image size will be reset.
* @return
*/
public static BufferedImage cut(BufferedImage inputImage,int startPoint,int width,int height,boolean fill){
//Get the original image transparency type
int type = inputImage.getColorModel().getTransparency();
int w = inputImage.getWidth();
int h = inputImage.getHeight();
BufferedImage img;
//Fill in white
if(fill){
img = new BufferedImage(width, height, type);
if(width>w)
width=w;
if(height>h)
height=h;
//Not repaired
}else{
if(width>w)
width=w;
if(height>h)
height=h;
img = new BufferedImage(width, height, type);
}
//Open anti-aliasing
RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_ANTIALIAS_ON);
//Use high-quality compression
renderingHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_RENDER_QUALITY);
Graphics2D graphics2d =img.createGraphics();
graphics2d.setRenderingHints(renderingHints);
switch(startPoint){
//Up to the right
case POSITION_UPPERRIGHT:
graphics2d.drawImage(inputImage, w-width, 0, w, height, 0, 0, width, height, null);
break;
//Lower left
case POSITION_LOWERLEFT:
graphics2d.drawImage(inputImage, 0, h-height, width, h, 0, 0, width, height, null);
break;
//Lower right
case POSITION_LOWERRIGHT:
graphics2d.drawImage(inputImage, w-width, h-height, w, h, 0, 0, width, height, null);
break;
//Default upper left
case POSITION_UPPERLEFT:
default:
graphics2d.drawImage(inputImage, 0, 0, width, height, 0, width, height, null);
}
graphics2d.dispose();
return img;
}
/**
* Rotate the picture at a specified angle: Use theta to rotate the point on the positive x-axis toward the positive y-axis.
* @param inputImage
* @param degree angle: in degrees
* @return
*/
public static BufferedImage rotateImage(final BufferedImage inputImage,
final int degree) {
int w = inputImage.getWidth();
int h = inputImage.getHeight();
int type = inputImage.getColorModel().getTransparency();
BufferedImage img=new BufferedImage(w, h, type);
Graphics2D graphics2d =img.createGraphics();
//Open anti-aliasing
RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_ANTIALIAS_ON);
//Use high-quality compression
renderingHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_RENDER_QUALITY);
graphics2d.setRenderingHints(renderingHints);
graphics2d.rotate(Math.toRadians(degree), w / 2, h / 2);
graphics2d.drawImage(inputImage, 0, 0, null);
graphics2d.dispose();
return img;
}
/**
* Flip the image horizontally
*
* @param bufferedimage Target image
* @return
*/
public static BufferedImage flipHorizontalImage(final BufferedImage inputImage) {
int w = inputImage.getWidth();
int h = inputImage.getHeight();
BufferedImage img;
Graphics2D graphics2d;
(graphics2d = (img = new BufferedImage(w, h, inputImage
.getColorModel().getTransparency())).createGraphics())
.drawImage(inputImage, 0, 0, w, h, w, 0, 0, h, null);
graphics2d.dispose();
return img;
}
/**
* Flip the image vertically
*
* @param bufferedimage Target image
* @return
*/
public static BufferedImage flipVerticalImage(final BufferedImage inputImage) {
int w = inputImage.getWidth();
int h = inputImage.getHeight();
BufferedImage img;
Graphics2D graphics2d;
(graphics2d = (img = new BufferedImage(w, h, inputImage
.getColorModel().getTransparency())).createGraphics())
.drawImage(inputImage, 0, 0, w, h, 0, h, w, 0, null);
graphics2d.dispose();
return img;
}
/**
* Picture watermark
*
* @param inputImage
* Images to be processed
* @param markImage
* Watermark image
* @param x
* The watermark is located in the upper left corner of the picture.
* @param y
* The watermark is located in the upper left corner of the picture. The y coordinate value
* @param alpha
* Watermark transparency 0.1f ~ 1.0f
* */
public static BufferedImage waterMark(BufferedImage inputImage,BufferedImage markImage, int x, int y,
float alpha) {
BufferedImage image = new BufferedImage(inputImage.getWidth(), inputImage
.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.drawImage(inputImage, 0, 0, null);
// Load the watermark image
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
alpha));
g.drawImage(markImage, x, y, null);
g.dispose();
return image;
}
/**
* Text watermark
*
* @param inputImage
* Images to be processed
* @param text
* Watermark text
* @param font
* Watermark font information
* @param color
* Watermark font color
* @param x
* The watermark is located in the upper left corner of the picture.
* @param y
* The watermark is located in the upper left corner of the picture. The y coordinate value
* @param alpha
* Watermark transparency 0.1f ~ 1.0f
*/
public static BufferedImage textMark(BufferedImage inputImage, String text, Font font,
Color color, int x, int y, float alpha) {
Font dfont = (font == null) ? new Font("宋体", 20, 13): font;
BufferedImage image = new BufferedImage(inputImage.getWidth(), inputImage
.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.drawImage(inputImage, 0, 0, null);
g.setColor(color);
g.setFont(dfont);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
alpha));
g.drawString(text, x, y);
g.dispose();
return image;
}
/**
* Image color to black and white
* @param inputImage
* @return Converted BufferedImage
*/
public final static BufferedImage toGray(BufferedImage inputImage)
{
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
//Colour conversion of source BufferedImage. If the target image is null,
// Create a BufferedImage based on the appropriate ColorModel.
ColorConvertOp op = new ColorConvertOp(cs, null);
return op.filter(inputImage, null);
}
/**
* Image color turns black and white
* @param srcImageFile
* Source image address
* @param destImageFile
* Target image address
* @param formatType
* Target image format: If formatType is null; convert the default to PNG
*/
public final static void toGray(String srcImageFile, String destImageFile, String formatType)
{
try
{
BufferedImage src = ImageIO.read(new File(srcImageFile));
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorConvertOp op = new ColorConvertOp(cs, null);
src = op.filter(src, null);
//If formatType is null; it will be converted to PNG by default
if(formatType==null){
formatType="PNG";
}
ImageIO.write(src,formatType,new File(destImageFile));
} catch (IOException e)
{
e.printStackTrace();
}
}
/**
* Image type conversion: GIF->JPG, GIF->PNG, PNG->JPG, PNG->GIF(X), BMP->PNG
*
* @param inputImage
* Source image address
* @param formatType
* String containing informal names of formats: such as JPG, JPEG, GIF, etc.
* @param destImageFile
* Target image address
*/
public final static void convert(BufferedImage inputImage, String formatType,String destImageFile)
{
try
{
ImageIO.write(inputImage, formatType, new File(destImageFile));
} catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Image cutting (specify the number of rows and columns of slices)
*
* @param srcImageFile
* Source image address
* @param destDir
* Slice the target folder
* @param formatType
* Target format
* @param rows
* Number of rows of target slices. Default 2, must be within range [1, 20]
* @param cols
* Number of target slice columns. Default 2, must be within range [1, 20]
*/
public final static void cut(BufferedImage inputImage, String destDir,
String formatType,int rows, int cols)
{
try
{
if (rows <= 0 || rows > 20)
rows = 2; // Number of slice rows
if (cols <= 0 || cols > 20)
cols = 2; // Number of slice columns
// Read source image
//BufferedImage bi = ImageIO.read(new File(srcImageFile));
int w = inputImage.getHeight(); // Source image width
int h = inputImage.getWidth(); // Source image height
if (w > 0 && h > 0)
{
Image img;
ImageFilter cropFilter;
Image image = inputImage.getScaledInstance(w, h,
Image.SCALE_DEFAULT);
int destWidth = w; // Width of each slice
int destHeight = h; // height of each slice
// Calculate the width and height of the slice
if (w % cols == 0)
{
destWidth = w / cols;
} else
{
destWidth = (int) Math.floor(w / cols) + 1;
}
if (h % rows == 0)
{
destHeight = h / rows;
} else
{
destHeight = (int) Math.floor(h / rows) + 1;
}
// Create slices in loop
// Idea of improvement: whether multithreading can be used to speed up cutting speed
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
// The four parameters are the image starting point coordinate and width and height
// That is: CropImageFilter(int x,int y,int width,int height)
cropFilter = new CropImageFilter(j * destWidth, i
* destHeight, destWidth, destHeight);
img = Toolkit.getDefaultToolkit().createImage(
new FilteredImageSource(image.getSource(),
cropFilter));
BufferedImage tag = new BufferedImage(destWidth,
destHeight, BufferedImage.TYPE_INT_ARGB);
Graphics g = tag.getGraphics();
g.drawImage(img, 0, 0, null); // Draw the reduced figure
g.dispose();
// Output as a file
ImageIO.write(tag, formatType, new File(destDir + "_r" + i
+ "_c" + j + "."+formatType.toLowerCase()));
}
}
}
} catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Add text watermark to the picture
*
* @param pressText
* Watermark text
* @param srcImageFile
* Source image address
* @param destImageFile
* Target image address
* @param fontName
* Font name of the watermark
* @param fontStyle
* Font style of watermark
* @param color
* Font color of watermark
* @param fontSize
* Font size of watermark
* @param x
* Corrected value
* @param y
* Corrected value
* @param alpha
* Transparency: alpha must be a floating point number within the range [0.0, 1.0] (including boundary values)
* @param formatType
* Target format
*/
public final static void pressText(String pressText, String srcImageFile,
String destImageFile, String fontName, int fontStyle, Color color,
int fontSize, int x, int y, float alpha,String formatType)
{
try
{
File img = new File(srcImageFile);
Image src = ImageIO.read(img);
int width = src.getWidth(null);
int height = src.getHeight(null);
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.drawImage(src, 0, 0, width, height, null);
g.setColor(color);
g.setFont(new Font(fontName, fontStyle, fontSize));
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
alpha));
// Draw watermark text in specified coordinates
g.drawString(pressText, (width - (getLength(pressText) * fontSize))
/ 2 + x, (height - fontSize) / 2 + y);
g.dispose();
ImageIO.write((BufferedImage) image, formatType,
new File(destImageFile));// Output to file stream
} catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Add image watermark to the image
*
* @param pressImg
* Watermark picture
* @param srcImageFile
* Source image address
* @param destImageFile
* Target image address
* @param x
* Fixed value. Default is in the middle
* @param y
* Fixed value. Default is in the middle
* @param alpha
* Transparency: alpha must be a floating point number within the range [0.0, 1.0] (including boundary values)
* @param formatType
* Target format
*/
public final static void pressImage(String pressImg, String srcImageFile,
String destImageFile, int x, int y, float alpha,String formatType)
{
try
{
File img = new File(srcImageFile);
Image src = ImageIO.read(img);
int wideth = src.getWidth(null);
int height = src.getHeight(null);
BufferedImage image = new BufferedImage(wideth, height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.drawImage(src, 0, 0, wideth, height, null);
// Watermark file
Image src_biao = ImageIO.read(new File(pressImg));
int wideth_biao = src_biao.getWidth(null);
int height_biao = src_biao.getHeight(null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
alpha));
g.drawImage(src_biao, (wideth - wideth_biao) / 2,
(height - height_biao) / 2, wideth_biao, height_biao, null);
// End of watermark file
g.dispose();
ImageIO.write((BufferedImage) image, formatType,
new File(destImageFile));
} catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Calculate the length of text (one Chinese counts two characters)
*
* @param text
* @return
*/
public final static int getLength(String text)
{
int length = 0;
for (int i = 0; i < text.length(); i++)
{
if (new String(text.charAt(i) + "").getBytes().length > 1)
{
length += 2;
} else
{
length += 1;
}
}
return length / 2;
}
}
Very practical image processing function, I hope you like it.