Java image processing utility class
- 2020-04-01 03:39:44
- OfStack
The functions of this tool: zoom image, cut image, image type conversion, color to black and white, text watermark, image watermark, etc
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 In the afternoon 6:37:18
* Image processing tools: <br>
* Functions: zoom image, cut image, image type conversion, color to black and white, text watermark, image watermark, etc
*/
public class ImageUtils {
/**
* Position relative to 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 interchange 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";//Bitmap, short for Bitmap, 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;
}
/**
* For 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;
}
/**
* Save after scaling and converting formats
* @param srcPath The source path
* @param destPath The target path
* @param width : the target width
* @param height : the target high
* @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 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 a reduced graph
g.dispose();
flag = ImageIO.write(tag, format, new FileOutputStream(destFile));//Output to file stream
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
/**
* The zoom Image , this method returns a scaled image of the source image
* @param inputImage
* @param percentage The percentage Permissible input 0<percentage<10000
* @return
*/
public static BufferedImage scaleByPercentage(BufferedImage inputImage,int percentage){
//Allowed percentage
if(0>percentage||percentage>10000){
throw new ImagingOpException("Error:: Invalid parameter :percentage->"+percentage+",percentage Should be greater than 0~ Less than 10000");
}
//Gets the original image transparency type
int type = inputImage.getColorModel().getTransparency();
//Gets the target image size
int w=inputImage.getWidth()*percentage;
int h=inputImage.getHeight()*percentage;
//Open antialiasing
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 returns Image type
return inputImage.getScaledInstance(inputImage.getWidth()*percentage,
inputImage.getHeight()*percentage, Image.SCALE_SMOOTH);
*/
}
/**
* The zoom Image , this method returns the scaled image of the source image within a given maximum width limit
* @param inputImage
* @param maxWidth : the maximum width allowed after compression
* @param maxHeight : maximum height allowed after compression
* @throws java.io.IOException
* return
*/
public static BufferedImage scaleByPixelRate(BufferedImage inputImage, int maxWidth, int maxHeight) throws Exception {
//Gets 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 scale
if(width*maxHeight<height*maxWidth){
newWidth=(int)(newHeight*width/height) ;
}
//If the specified maximum height exceeds the ratio
if(width*maxHeight>height*maxWidth){
newHeight=(int)(newWidth*height/width);
}
//Open antialiasing
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;
}
/**
* The zoom Image , this method returns the scaled image of the source image with a given width and height limit
* @param inputImage
* @param maxWidth : compressed width
* @param maxHeight : height after compression
* @throws java.io.IOException
* return
*/
public static BufferedImage scaleByPixel(BufferedImage inputImage, int newWidth, int newHeight) throws Exception {
//Gets the original image transparency type
int type = inputImage.getColorModel().getTransparency();
int width = inputImage.getWidth();
int height = inputImage.getHeight();
//Open antialiasing
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;
}
/**
* Cuts the image and returns the image in the specified range
* @param inputImage
* @param x Starting abscissa
* @param y Starting ordinate
* @param width Cutting picture width : If the width exceeds the image, it will be changed to image from x The remaining width
* @param height Cut image height: if the height exceeds the image, it will be changed to image height y The remaining highly
* @param fill Specifies whether the target image is whitened when the size is exceeded, if true , is to make up; false Represents no padding, at which point the target image size is reset
* @return
*/
public static BufferedImage cut(BufferedImage inputImage,int x,int y,int width,int height,boolean fill){
//Gets 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 origin abscissa is out of the range of the source image ");
if(y>h)
throw new ImagingOpException(" The origin ordinate is out of the range of the source image ");
BufferedImage img;
//Padding < br / >
if(fill){
img = new BufferedImage(width, height, type);
//Width exceeded
if((w-x)<width){
width=w-x;
endx=w;
}
//Height exceeded
if((h-y)<height){
height=h-y;
endy=h;
}
//Don't fill the < br / >
}else{
//Width exceeded
if((w-x)<width){
width=w-x;
endx=w;
}
//Height exceeded
if((h-y)<height){
height=h-y;
endy=h;
}
img = new BufferedImage(width, height, type);
}
//Open antialiasing
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;
}
/**
* Returns the size of the image at the specified starting position
* @param inputImage
* @param startPoint Starting position: top left: 0 The upper right of the, :10 , left :1 And the lower right :11
* @param width Cutting picture width
* @param height Cutting picture height
* @param fill Specifies whether the target image is whitened when the size is exceeded, if true , is to make up; false Represents no padding, at which point the target image size is reset
* @return
*/
public static BufferedImage cut(BufferedImage inputImage,int startPoint,int width,int height,boolean fill){
//Gets the original image transparency type
int type = inputImage.getColorModel().getTransparency();
int w = inputImage.getWidth();
int h = inputImage.getHeight();
BufferedImage img;
//Padding < br / >
if(fill){
img = new BufferedImage(width, height, type);
if(width>w)
width=w;
if(height>h)
height=h;
//Don't fill the < br / >
}else{
if(width>w)
width=w;
if(height>h)
height=h;
img = new BufferedImage(width, height, type);
}
//Open antialiasing
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){
//Upper right < br / >
case POSITION_UPPERRIGHT:
graphics2d.drawImage(inputImage, w-width, 0, w, height, 0, 0, width, height, null);
break;
//Lower left < br / >
case POSITION_LOWERLEFT:
graphics2d.drawImage(inputImage, 0, h-height, width, h, 0, 0, width, height, null);
break;
//The lower right < br / >
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, 0, width, height, null);
}
graphics2d.dispose();
return img;
}
/**
* Rotate the image at the specified Angle: use a positive Angle theta Rotate to make it positive x The point on the axis turns positive y Axis.
* @param inputImage
* @param degree The 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 antialiasing
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;
}
/**
* Horizontal flip image
*
* @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;
}
/**
* Vertical flip
*
* @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;
}
/**
* Image watermarking
*
* @param inputImage
* Pending image
* @param markImage
* Watermark image
* @param x
* The watermark is located in the upper left corner of the image x Coordinate values
* @param y
* The watermark is located in the upper left corner of the image y Coordinate values
* @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 watermark image
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
alpha));
g.drawImage(markImage, x, y, null);
g.dispose();
return image;
}
/**
* Text watermarking
*
* @param inputImage
* Pending image
* @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 image x Coordinate values
* @param y
* The watermark is located in the upper left corner of the image y Coordinate values
* @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(" Song typeface ", 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 The transformed BufferedImage
*/
public final static BufferedImage toGray(BufferedImage inputImage)
{
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
//Color conversion to source BufferedImage. If the target image is null,
//Creates a BufferedImage based on the appropriate ColorModel. < br / >
ColorConvertOp op = new ColorConvertOp(cs, null);
return op.filter(inputImage, null);
}
/**
* The image changes color to black and white
* @param srcImageFile
* Source image address
* @param destImageFile
* Target image address
* @param formatType
* Target image format: If formatType is null; Converts 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; Converts the default to PNG
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
* Containing the informal name of the format String , 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 (specifies the number of rows and columns of slices)
*
* @param srcImageFile
* Source image address
* @param destDir
* Slice target folder
* @param formatType
* Target format
* @param rows
* Number of target slice rows. The default 2 It has to be the scope [1, 20] within
* @param cols
* Number of target slice columns. The default 2 It has to be the scope [1, 20] within
*/
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 slices
if (cols <= 0 || cols > 20)
cols = 2; //Number of slice columns
//Read the source image
//BufferedImage bi = ImageIO.read(new File(srcImageFile));
int w = inputImage.getHeight(); //Source width
int h = inputImage.getWidth(); //Source height
if (w > 0 && h > 0)
{
Image img;
ImageFilter cropFilter;
Image image = inputImage.getScaledInstance(w, h,
Image.SCALE_DEFAULT);
int destWidth = w; //The width of each slice is
int destHeight = h; //The height of each slice is
//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;
}
//Loop to create slices
//Improved ideas: can multithreading be used to speed up cutting
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
//The four parameters are the starting coordinates of the image and the width and height
//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 a reduced graph
g.dispose();
//The output is a file
ImageIO.write(tag, formatType, new File(destDir + "_r" + i
+ "_c" + j + "."+formatType.toLowerCase()));
}
}
}
} catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Add a text watermark to the picture
*
* @param pressText
* Watermark text
* @param srcImageFile
* Source image address
* @param destImageFile
* Target image address
* @param fontName
* The font name of the watermark
* @param fontStyle
* Font style of watermark
* @param color
* The font color of the watermark
* @param fontSize
* The font size of the watermark
* @param x
* revised
* @param y
* revised
* @param alpha
* Transparency: alpha It has to be the range [0.0, 1.0] A floating point number within (containing 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));
//Draws the watermark
at the 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 a picture watermark to the picture
*
* @param pressImg
* The watermark image
* @param srcImageFile
* Source image address
* @param destImageFile
* Target image address
* @param x
* Revised. Default in the middle
* @param y
* Revised. Default in the middle
* @param alpha
* Transparency: alpha It has to be the range [0.0, 1.0] A floating point number within (containing 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
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);
//Watermark file ends
g.dispose();
ImageIO.write((BufferedImage) image, formatType,
new File(destImageFile));
} catch (Exception e)
{
e.printStackTrace();
}
}
/**
* To calculate text Length (one Chinese character counts as 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 can like.