本工具類的功能:縮放圖像、切割圖像、圖像類型轉換、彩色轉黑白、文字水印、圖片水印等
復制代碼代碼如下:
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
* 圖片處理工具類:<br>
* 功能:縮放圖像、切割圖像、圖像類型轉換、彩色轉黑白、文字水印、圖片水印等
*/
public class ImageUtils {
/**
* 相對于圖片的位置
*/
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;
/**
* 幾種常見的圖片格式
*/
public static String IMAGE_TYPE_GIF = "gif";// 圖形交換格式
public static String IMAGE_TYPE_JPG = "jpg";// 聯合照片專家組
public static String IMAGE_TYPE_JPEG = "jpeg";// 聯合照片專家組
public static String IMAGE_TYPE_BMP = "bmp";// 英文Bitmap(位圖)的簡寫,它是Windows操作系統中的標準圖像文件格式
public static String IMAGE_TYPE_PNG = "png";// 可移植網絡圖形
private static ImageUtils instance;
private ImageUtils() {
instance = this;
}
/**
* 獲取實例
* @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;
}
/**
* 縮放并轉換格式后保存
* @param srcPath源路徑
* @param destPath目標路徑
* @param width:目標寬
* @param height:目標高
* @param 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); // 讀入文件
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); // 繪制縮小后的圖
g.dispose();
flag = ImageIO.write(tag, format, new FileOutputStream(destFile));// 輸出到文件流
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
/**
* 縮放Image,此方法返回源圖像按百分比縮放后的圖像
* @param inputImage
* @param percentage 百分比 允許的輸入0<percentage<10000
* @return
*/
public static BufferedImage scaleByPercentage(BufferedImage inputImage,int percentage){
//允許百分比
if(0>percentage||percentage>10000){
throw new ImagingOpException("Error::不合法的參數:percentage->"+percentage+",percentage應該大于0~小于10000");
}
//獲取原始圖像透明度類型
int type = inputImage.getColorModel().getTransparency();
//獲取目標圖像大小
int w=inputImage.getWidth()*percentage;
int h=inputImage.getHeight()*percentage;
//開啟抗鋸齒
RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_ANTIALIAS_ON);
//使用高質量壓縮
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;
/*此代碼將返回Image類型
return inputImage.getScaledInstance(inputImage.getWidth()*percentage,
inputImage.getHeight()*percentage, Image.SCALE_SMOOTH);
*/
}
/**
* 縮放Image,此方法返回源圖像按給定最大寬度限制下按比例縮放后的圖像
* @param inputImage
* @param maxWidth:壓縮后允許的最大寬度
* @param maxHeight:壓縮后允許的最大高度
* @throws java.io.IOException
* return
*/
public static BufferedImage scaleByPixelRate(BufferedImage inputImage, int maxWidth, int maxHeight) throws Exception {
//獲取原始圖像透明度類型
int type = inputImage.getColorModel().getTransparency();
int width = inputImage.getWidth();
int height = inputImage.getHeight();
int newWidth = maxWidth;
int newHeight =maxHeight;
//如果指定最大寬度超過比例
if(width*maxHeight<height*maxWidth){
newWidth=(int)(newHeight*width/height) ;
}
//如果指定最大高度超過比例
if(width*maxHeight>height*maxWidth){
newHeight=(int)(newWidth*height/width);
}
//開啟抗鋸齒
RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_ANTIALIAS_ON);
//使用高質量壓縮
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;
}
/**
* 縮放Image,此方法返回源圖像按給定寬度、高度限制下縮放后的圖像
* @param inputImage
* @param maxWidth:壓縮后寬度
* @param maxHeight:壓縮后高度
* @throws java.io.IOException
* return
*/
public static BufferedImage scaleByPixel(BufferedImage inputImage, int newWidth, int newHeight) throws Exception {
//獲取原始圖像透明度類型
int type = inputImage.getColorModel().getTransparency();
int width = inputImage.getWidth();
int height = inputImage.getHeight();
//開啟抗鋸齒
RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
//使用高質量壓縮
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;
}
/**
* 切割圖像,返回指定范圍的圖像
* @param inputImage
* @param x 起點橫坐標
* @param y 起點縱坐標
* @param width 切割圖片寬度:如果寬度超出圖片,將改為圖片自x剩余寬度
* @param height 切割圖片高度:如果高度超出圖片,將改為圖片自y剩余高度
* @param fill 指定目標圖像大小超出時是否補白,如果true,則表示補白;false表示不補白,此時將重置目標圖像大小
* @return
*/
public static BufferedImage cut(BufferedImage inputImage,int x,int y,int width,int height,boolean fill){
//獲取原始圖像透明度類型
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("起點橫坐標超出源圖像范圍");
if(y>h)
throw new ImagingOpException("起點縱坐標超出源圖像范圍");
BufferedImage img;
//補白
if(fill){
img = new BufferedImage(width, height, type);
//寬度超出限制
if((w-x)<width){
width=w-x;
endx=w;
}
//高度超出限制
if((h-y)<height){
height=h-y;
endy=h;
}
//不補
}else{
//寬度超出限制
if((w-x)<width){
width=w-x;
endx=w;
}
//高度超出限制
if((h-y)<height){
height=h-y;
endy=h;
}
img = new BufferedImage(width, height, type);
}
//開啟抗鋸齒
RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_ANTIALIAS_ON);
//使用高質量壓縮
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;
}
/**
* 切割圖像,返回指定起點位置指定大小圖像
* @param inputImage
* @param startPoint 起點位置:左上:0、右上:10、左下:1、右下:11
* @param width 切割圖片寬度
* @param height 切割圖片高度
* @param fill 指定目標圖像大小超出時是否補白,如果true,則表示補白;false表示不補白,此時將重置目標圖像大小
* @return
*/
public static BufferedImage cut(BufferedImage inputImage,int startPoint,int width,int height,boolean fill){
//獲取原始圖像透明度類型
int type = inputImage.getColorModel().getTransparency();
int w = inputImage.getWidth();
int h = inputImage.getHeight();
BufferedImage img;
//補白
if(fill){
img = new BufferedImage(width, height, type);
if(width>w)
width=w;
if(height>h)
height=h;
//不補
}else{
if(width>w)
width=w;
if(height>h)
height=h;
img = new BufferedImage(width, height, type);
}
//開啟抗鋸齒
RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_ANTIALIAS_ON);
//使用高質量壓縮
renderingHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_RENDER_QUALITY);
Graphics2D graphics2d =img.createGraphics();
graphics2d.setRenderingHints(renderingHints);
switch(startPoint){
//右上
case POSITION_UPPERRIGHT:
graphics2d.drawImage(inputImage, w-width, 0, w, height, 0, 0, width, height, null);
break;
//左下
case POSITION_LOWERLEFT:
graphics2d.drawImage(inputImage, 0, h-height, width, h, 0, 0, width, height, null);
break;
//右下
case POSITION_LOWERRIGHT:
graphics2d.drawImage(inputImage, w-width, h-height, w, h, 0, 0, width, height, null);
break;
//默認左上
case POSITION_UPPERLEFT:
default:
graphics2d.drawImage(inputImage, 0, 0, width, height, 0, 0, width, height, null);
}
graphics2d.dispose();
return img;
}
/**
* 以指定角度旋轉圖片:使用正角度 theta 進行旋轉,可將正 x 軸上的點轉向正 y 軸。
* @param inputImage
* @param degree 角度:以度數為單位
* @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();
//開啟抗鋸齒
RenderingHints renderingHints=new RenderingHints(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_ANTIALIAS_ON);
//使用高質量壓縮
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;
}
/**
* 水平翻轉圖像
*
* @param bufferedimage 目標圖像
* @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;
}
/**
* 豎直翻轉圖像
*
* @param bufferedimage 目標圖像
* @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;
}
/**
* 圖片水印
*
* @param inputImage
* 待處理圖像
* @param markImage
* 水印圖像
* @param x
* 水印位于圖片左上角的 x 坐標值
* @param y
* 水印位于圖片左上角的 y 坐標值
* @param alpha
* 水印透明度 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);
// 加載水印圖像
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
alpha));
g.drawImage(markImage, x, y, null);
g.dispose();
return image;
}
/**
* 文字水印
*
* @param inputImage
* 待處理圖像
* @param text
* 水印文字
* @param font
* 水印字體信息
* @param color
* 水印字體顏色
* @param x
* 水印位于圖片左上角的 x 坐標值
* @param y
* 水印位于圖片左上角的 y 坐標值
* @param alpha
* 水印透明度 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;
}
/**
* 圖像彩色轉黑白色
* @param inputImage
* @return 轉換后的BufferedImage
*/
public final static BufferedImage toGray(BufferedImage inputImage)
{
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
//對源 BufferedImage 進行顏色轉換。如果目標圖像為 null,
//則根據適當的 ColorModel 創建 BufferedImage。
ColorConvertOp op = new ColorConvertOp(cs, null);
return op.filter(inputImage, null);
}
/**
* 圖像彩色轉為黑白
* @param srcImageFile
* 源圖像地址
* @param destImageFile
* 目標圖像地址
* @param formatType
* 目標圖像格式:如果formatType為null;將默認轉換為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);
//如果formatType為null;將默認轉換為PNG
if(formatType==null){
formatType="PNG";
}
ImageIO.write(src,formatType,new File(destImageFile));
} catch (IOException e)
{
e.printStackTrace();
}
}
/**
* 圖像類型轉換:GIF->JPG、GIF->PNG、PNG->JPG、PNG->GIF(X)、BMP->PNG
*
* @param inputImage
* 源圖像地址
* @param formatType
* 包含格式非正式名稱的 String:如JPG、JPEG、GIF等
* @param destImageFile
* 目標圖像地址
*/
public final static void convert(BufferedImage inputImage, String formatType,String destImageFile)
{
try
{
ImageIO.write(inputImage, formatType, new File(destImageFile));
} catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 圖像切割(指定切片的行數和列數)
*
* @param srcImageFile
* 源圖像地址
* @param destDir
* 切片目標文件夾
* @param formatType
* 目標格式
* @param rows
* 目標切片行數。默認2,必須是范圍 [1, 20] 之內
* @param cols
* 目標切片列數。默認2,必須是范圍 [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; // 切片行數
if (cols <= 0 || cols > 20)
cols = 2; // 切片列數
// 讀取源圖像
//BufferedImage bi = ImageIO.read(new File(srcImageFile));
int w = inputImage.getHeight(); // 源圖寬度
int h = inputImage.getWidth(); // 源圖高度
if (w > 0 && h > 0)
{
Image img;
ImageFilter cropFilter;
Image image = inputImage.getScaledInstance(w, h,
Image.SCALE_DEFAULT);
int destWidth = w; // 每張切片的寬度
int destHeight = h; // 每張切片的高度
// 計算切片的寬度和高度
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;
}
// 循環建立切片
// 改進的想法:是否可用多線程加快切割速度
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
// 四個參數分別為圖像起點坐標和寬高
// 即: 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); // 繪制縮小后的圖
g.dispose();
// 輸出為文件
ImageIO.write(tag, formatType, new File(destDir + "_r" + i
+ "_c" + j + "."+formatType.toLowerCase()));
}
}
}
} catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 給圖片添加文字水印
*
* @param pressText
* 水印文字
* @param srcImageFile
* 源圖像地址
* @param destImageFile
* 目標圖像地址
* @param fontName
* 水印的字體名稱
* @param fontStyle
* 水印的字體樣式
* @param color
* 水印的字體顏色
* @param fontSize
* 水印的字體大小
* @param x
* 修正值
* @param y
* 修正值
* @param alpha
* 透明度:alpha 必須是范圍 [0.0, 1.0] 之內(包含邊界值)的一個浮點數字
* @param formatType
* 目標格式
*/
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));
// 在指定坐標繪制水印文字
g.drawString(pressText, (width - (getLength(pressText) * fontSize))
/ 2 + x, (height - fontSize) / 2 + y);
g.dispose();
ImageIO.write((BufferedImage) image, formatType,
new File(destImageFile));// 輸出到文件流
} catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 給圖片添加圖片水印
*
* @param pressImg
* 水印圖片
* @param srcImageFile
* 源圖像地址
* @param destImageFile
* 目標圖像地址
* @param x
* 修正值。 默認在中間
* @param y
* 修正值。 默認在中間
* @param alpha
* 透明度:alpha 必須是范圍 [0.0, 1.0] 之內(包含邊界值)的一個浮點數字
* @param formatType
* 目標格式
*/
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);
// 水印文件
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);
// 水印文件結束
g.dispose();
ImageIO.write((BufferedImage) image, formatType,
new File(destImageFile));
} catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 計算text的長度(一個中文算兩個字符)
*
* @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;
}
}
非常實用的圖像處理功能,希望大家能夠喜歡。