创建图片
import org.apache.commons.lang3.StringUtils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CreateImage {
public static void main(String[] args) throws IOException {
List<String> strList = new ArrayList<>();
for (int i = 1; i <= 4; i++) {
strList.add("这是第" + i + "行");
}
createImage("E:\\123.png", strList, new Font("宋体", Font.BOLD, 30), 720, 720);
}
private static void createImage(String filePath, List<String> strList, Font font, int width, int height) {
File file = new File(filePath);
try {
String suffix = StringUtils.substringAfterLast(file.getName(), ".");
checkSuffixValid(suffix);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics graphics = image.getGraphics();
graphics.setClip(0, 0, width, height);
graphics.setColor(Color.white);
graphics.fillRect(0, 0, width, height);
graphics.setColor(Color.red);
graphics.setFont(font);
Rectangle clip = graphics.getClipBounds();
FontMetrics fm = graphics.getFontMetrics(font);
int ascent = fm.getAscent();
int descent = fm.getDescent();
int y = (clip.height - (ascent + descent)) / 2 + ascent;
if (strList != null) {
int num;
if (strList.size() % 2 == 1) {
num = (strList.size() - 1) / 2;
} else {
num = strList.size() / 2;
}
int n = -num;
for (int i = 0; i < strList.size(); i++) {
graphics.drawString(strList.get(i), 2 * font.getSize(), y + (font.getSize() * n));
n++;
}
}
graphics.dispose();
ImageIO.write(image, suffix, file);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void checkSuffixValid(String suffix) {
String types = Arrays.toString(ImageIO.getReaderFormatNames()).replace("[", "").replace("]", ",");
if (suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase() + ",") < 0) {
throw new RuntimeException("文件后缀不规范,无法操作image文件,后缀示例:" + types.substring(0, types.length() - 1));
}
}
}
图片裁剪
import org.apache.commons.lang3.StringUtils;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class CroppingImage {
public static void main(String[] args) {
croppingImage("E:\\123.png", "_clip", 20, 180, 240, 240);
}
private static void croppingImage(String filePath, String sufixo, int x, int y, int width, int height) {
File file = new File(filePath);
Rectangle rect = new Rectangle(x, y, width, height);
FileInputStream fis = null;
ImageInputStream iis = null;
try {
String suffix = StringUtils.substringAfterLast(file.getName(), ".");
CreateImage.checkSuffixValid(suffix);
fis = new FileInputStream(file);
iis = ImageIO.createImageInputStream(fis);
ImageReader reader = ImageIO.getImageReadersBySuffix(suffix).next();
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
param.setSourceRegion(rect);
BufferedImage image = reader.read(0, param);
String path = file.getPath();
if (!file.isDirectory()) {
path = file.getParent();
}
if (!path.endsWith(File.separator)) {
path = path + File.separator;
}
String pathNew = path.substring(0, path.lastIndexOf(File.separator)) + File.separator + StringUtils.substringBeforeLast(file.getName(), ".") + sufixo + "." + StringUtils.substringAfterLast(file.getName(), ".");
ImageIO.write(image, suffix, new File(pathNew));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (iis != null) {
iis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
图片缩放
import org.apache.commons.lang3.StringUtils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
public class ZoomImage {
public static void main(String[] args) throws IOException {
zoomImage("E:\\123.png", 180, 180, "_zoom", true);
}
private static void zoomImage(String filePath, int w, int h, String sufixo, boolean proportion) throws IOException {
File file = new File(filePath);
String suffix = StringUtils.substringAfterLast(file.getName(), ".");
CreateImage.checkSuffixValid(suffix);
BufferedImage img = ImageIO.read(file);
if (proportion) {
int width = img.getWidth(null);
int height = img.getHeight(null);
if ((width * 1.0) / w < (height * 1.0) / h) {
if (width > w) {
h = Integer.parseInt(new DecimalFormat("0").format(height * w / (width * 1.0)));
}
} else {
if (height > h) {
w = Integer.parseInt(new DecimalFormat("0").format(width * h / (height * 1.0)));
}
}
}
System.out.println("修改后的图片:height=" + h + ", width=" + w);
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
graphics.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null);
graphics.dispose();
String path = file.getPath();
String pathNew = path.substring(0, path.lastIndexOf(File.separator)) + File.separator + StringUtils.substringBeforeLast(file.getName(), ".") + sufixo + "." + StringUtils.substringAfterLast(file.getName(), ".");
ImageIO.write(image, suffix, new File(pathNew));
}
}
图片水印
import org.apache.commons.lang3.StringUtils;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class WatermarkImage {
public static void main(String[] args) throws IOException {
markTextMark("E:\\123.jpg", "_watermark_txt", "@愚昧的取经人");
markImgMark("E:\\123.jpg", "_watermark_img", "E:\\watermark.jpg");
}
private static void markTextMark(String filePath, String sufixo, String waterMarkContent) throws IOException {
Color color = new Color(180, 180, 180, 100);
File file = new File(filePath);
String suffix = StringUtils.substringAfterLast(file.getName(), ".");
CreateImage.checkSuffixValid(suffix);
Image srcImg = ImageIO.read(file);
int width = srcImg.getWidth(null);
int height = srcImg.getHeight(null);
int fontLength = (int) (width * 0.028);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
graphics.drawImage(srcImg, 0, 0, width, height, null);
graphics.setColor(color);
graphics.setFont(new Font("微软雅黑", Font.PLAIN, fontLength));
int x = (int) (width * 0.962 - getWatermarkLength(waterMarkContent, graphics));
int y = (int) (height * 0.962 - fontLength);
graphics.drawString(waterMarkContent, x, y);
graphics.dispose();
String path = file.getPath();
String pathNew = path.substring(0, path.lastIndexOf(File.separator)) + File.separator + StringUtils.substringBeforeLast(file.getName(), ".") + sufixo + "." + StringUtils.substringAfterLast(file.getName(), ".");
ImageIO.write(image, suffix, new File(pathNew));
}
private static void markImgMark(String filePath, String sufixo, String watermarkUrl) throws IOException {
File file = new File(filePath);
String suffix = StringUtils.substringAfterLast(file.getName(), ".");
CreateImage.checkSuffixValid(suffix);
Image img = ImageIO.read(file);
int width = img.getWidth(null);
int height = img.getHeight(null);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics.drawImage(img.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
ImageIcon imgIcon = new ImageIcon(watermarkUrl);
Image con = imgIcon.getImage();
float clarity = 0.6f;
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, clarity));
int x = (int) (width * 0.962 - imgIcon.getIconWidth());
int y = (int) (height * 0.962 - imgIcon.getIconHeight());
graphics.drawImage(con, x, y, null);
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
graphics.dispose();
String path = file.getPath();
String pathNew = path.substring(0, path.lastIndexOf(File.separator)) + File.separator + StringUtils.substringBeforeLast(file.getName(), ".") + sufixo + "." + StringUtils.substringAfterLast(file.getName(), ".");
ImageIO.write(image, suffix, new File(pathNew));
}
private static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
}
}