图片工具类, 图片水印,文字水印,缩放,补白等
添加图片水印
/**
* 添加图片水印
* @param targetImg 目标图片路径,如:C://myPictrue//1.jpg
* @param waterImg 水印图片路径,如:C://myPictrue//logo.png
* @param x 水印图片距离目标图片左侧的偏移量,如果x<0, 则在正中间
* @param y 水印图片距离目标图片上侧的偏移量,如果y<0, 则在正中间
* @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
*/
public final static void pressImage(String targetImg, String waterImg, int x, int y, float alpha) {
try {
File file = new File(targetImg);
Image image = ImageIO.read(file);
int width = image.getWidth(null);
int height = image.getHeight(null);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufferedImage.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
Image waterImage = ImageIO.read(new File(waterImg)); // 水印文件
int width_1 = waterImage.getWidth(null);
int height_1 = waterImage.getHeight(null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
int widthDiff = width - width_1;
int heightDiff = height - height_1;
if (x < 0) {
x = widthDiff / 2;
} else if (x > widthDiff) {
x = widthDiff;
}
if (y < 0) {
y = heightDiff / 2;
} else if (y > heightDiff) {
y = heightDiff;
}
g.drawImage(waterImage, x, y, width_1, height_1, null); // 水印文件结束
g.dispose();
ImageIO.write(bufferedImage, PICTRUE_FORMATE_JPG, file);
} catch (IOException e) {
e.printStackTrace();
}
}
添加文字水印
/**
* 添加文字水印
* @param targetImg 目标图片路径,如:C://myPictrue//1.jpg
* @param pressText 水印文字, 如:中国证券网
* @param fontName 字体名称, 如:宋体
* @param fontStyle 字体样式,如:粗体和斜体(Font.BOLD|Font.ITALIC)
* @param fontSize 字体大小,单位为像素
* @param color 字体颜色
* @param x 水印文字距离目标图片左侧的偏移量,如果x<0, 则在正中间
* @param y 水印文字距离目标图片上侧的偏移量,如果y<0, 则在正中间
* @param alpha 透明度(0.0 -- 1.0, 0.0为完全透明,1.0为完全不透明)
*/
public static void pressText(String targetImg, String pressText, String fontName, int fontStyle, int fontSize, int x, int y,
float alpha) {
pressText(targetImg, pressText, fontName, fontStyle, fontSize, x, y, alpha, "jpg");
}
public static void pressText(String targetImg, String pressText, String fontName, int fontStyle, int fontSize, int x, int y,
float alpha, String ext) {
try {
File file = new File(targetImg);
Image image = ImageIO.read(file);
int width = image.getWidth(null);
int height = image.getHeight(null);
fontSize = width / ((2 * getLength(pressText)) == 0 ? 1 : (2 * getLength(pressText)));
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufferedImage.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
g.setFont(new Font(fontName, fontStyle, fontSize));
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
int width_1 = fontSize * getLength(pressText);
int height_1 = fontSize;
int widthDiff = width - width_1;
int heightDiff = height - height_1;
if (x < 0) {
x = 10;
} else if (x > widthDiff) {
x = widthDiff;
}
if (y < 0) {
y = heightDiff - 10;
} else if (y > heightDiff) {
y = heightDiff;
}
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
g.setBackground(Color.BLACK);
g.setColor(Color.WHITE);
g.drawString(pressText, x, y + height_1);
g.setColor(Color.BLACK);
g.drawString(pressText, x + 2, y + height_1 + 2);
// g.setColor(Color.WHITE);
// g.drawString(pressText, x + 1, y + height_1 + 1);
g.dispose();
ImageIO.write(bufferedImage, ext, file);
} catch (Exception e) {
e.printStackTrace();
}
}
检查传入file的format名称
/**
* 检查传入file的format名称
* @param f 传入的文件
* @return
*/
public static String getFormatInFile(File f) {
return getFormatName(f);
}
/**
* 对文件进行format检索
* .jpg .jpeg .jpe .jfif ===> JPEG
* .png ===> png
* .gif ===> gif
* .
* @param o
* @return
*/
// Returns the format name of the image in the object 'o'.
// Returns null if the format is not known.
public static String getFormatName(Object o) {
try {
// Create an image input stream on the image
ImageInputStream iis = ImageIO.createImageInputStream(o);
// Find all image readers that recognize the image format
Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
// No readers found
return null;
}
// Use the first reader
ImageReader reader = (ImageReader) iter.next();
// Close stream
iis.close();
// Return the format name
return reader.getFormatName();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
获取字符长度
/**
* 获取字符长度,一个汉字作为 1 个字符, 一个英文字母作为 0.5 个字符
* @param text
* @return 字符长度,如:text="中国",返回 2;text="test",返回 2;text="中国ABC",返回 4.
*/
public static int getLength(String text) {
int textLength = text.length();
int length = textLength;
for (int i = 0; i < textLength; i++) {
if (String.valueOf(text.charAt(i)).getBytes().length > 1) {
length++;
}
}
return (length % 2 == 0) ? length / 2 : length / 2 + 1;
}
图片缩放
public static BufferedImage resize(BufferedImage source, int targetW, int targetH) {
// targetW,targetH分别表示目标长和宽
int type = source.getType();
BufferedImage target = null;
double sx = (double) targetW / source.getWidth();
double sy = (double) targetH / source.getHeight();
// 这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放
// 则将下面的if else语句注释即可
if (sx > sy) {
sx = sy;
targetW = (int) (sx * source.getWidth());
} else {
sy = sx;
targetH = (int) (sy * source.getHeight());
}
if (type == BufferedImage.TYPE_CUSTOM) { // handmade
ColorModel cm = source.getColorModel();
WritableRaster raster = cm.createCompatibleWritableRaster(targetW,
targetH);
boolean alphaPremultiplied = cm.isAlphaPremultiplied();
target = new BufferedImage(cm, raster, alphaPremultiplied, null);
} else
target = new BufferedImage(targetW, targetH, type);
Graphics2D g = target.createGraphics();
// smoother than exlax:
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
g.dispose();
return target;
}
public static String resize(File file, int targetW, int targetH,String ext) throws IOException{
BufferedImage source = ImageIO.read(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
BufferedImage bi = resize( source, targetW, targetH);
ImageIO.write(bi, ext, baos);
String result = new BASE64Encoder().encode(baos.toByteArray()).trim();
return result;
}
/**
* 统一比例压缩。
* @param filePath
*/
public static void resize(String filePath) {
resize(filePath, finalX, finalY, false);
}
/**
* 图片缩放
* @param filePath 图片路径
* @param height 高度
* @param width 宽度
* @param bb 比例不对时是否需要补白
*/
public static void resize(String filePath, int height, int width, boolean bb) {
resize(filePath, height, width, bb, "jpg");
}
public static void resize(String filePath, int height, int width, boolean bb, String ext) {
try {
File f = new File(filePath);
BufferedImage bi = ImageIO.read(f);
ImageIO.write(resize(bi, height, height), ext, f);
} catch (IOException e) {
e.printStackTrace();
}
}