Java中圖片的常用操作代碼總結(jié)
前言
本文主要使用Java對(duì)圖片各種操作進(jìn)行處理。
一、獲取系統(tǒng)支持圖片格式
代碼:
System.out.println(Arrays.asList(ImageIO.getReaderFormatNames())); System.out.println(Arrays.asList(ImageIO.getReaderFileSuffixes())); System.out.println(Arrays.asList(ImageIO.getReaderMIMETypes())); String[] writerFormatName = ImageIO.getWriterFormatNames(); String[] writerSuffixName = ImageIO.getWriterFileSuffixes(); String[] writerMIMEType = ImageIO.getWriterMIMETypes();
輸出:
[JPG, jpg, tiff, pcx, PCX, bmp, BMP, gif, GIF, WBMP, png, PNG, raw, RAW, JPEG, pnm, PNM, tif, TIF, TIFF, wbmp, jpeg]
[, jpg, tiff, pcx, bmp, gif, png, ppm, tif, pgm, wbmp, jpeg, pbm]
[, image/vnd.wap.wbmp, image/png, image/jpeg, image/x-portable-graymap, image/pcx, image/bmp, image/gif, image/x-windows-pcx, image/x-windows-bmp, image/x-pc-paintbrush, image/x-pcx, image/x-bmp, image/x-png, image/x-portable-bitmap, image/x-portable-pixmap, image/tiff, image/x-portable-anymap]
二、生成自定義圖片
代碼:
@SneakyThrows
public static void main(String[] args) {
BufferedImage bufferedImage = new BufferedImage(400, 400, BufferedImage.TYPE_INT_BGR);
Graphics g = bufferedImage.getGraphics();
try {
g.fillRect(20, 40, 400, 400);
g.setColor(new Color(120, 120, 120));
g.setFont(new Font("隸書", Font.BOLD, 28));
g.drawString("自定義圖片", 200, 200);
ImageIO.write(bufferedImage, "jpg", new File("D:/test.jpg"));
} finally {
g.dispose();//釋放畫筆
}
}
輸出:

三、獲取圖片格式
代碼:
public static String getImageFormatName(File file) throws IOException {
String formatName = null;
ImageInputStream iis = ImageIO.createImageInputStream(file);
Iterator<ImageReader> imageReader = ImageIO.getImageReaders(iis);
if (imageReader.hasNext()) {
ImageReader reader = imageReader.next();
formatName = reader.getFormatName();
}
return formatName;
}
四、圖片裁剪
public static String cutImage(String sourcePath, String targetPath, int x, int y, int width, int height) throws IOException {
File file = new File(sourcePath);
if (!file.exists()) {
throw new IOException("not found the image:" + sourcePath);
}
if (null == targetPath || targetPath.isEmpty()) {
targetPath = sourcePath;
}
String formatName = getImageFormatName(file);
if (null == formatName) {
return targetPath;
}
formatName = formatName.toLowerCase();
// 防止圖片后綴與圖片本身類型不一致的情況
String pathPrefix = getPathWithoutSuffix(targetPath);
targetPath = pathPrefix + formatName;
// GIF需要特殊處理
if (IMAGE_FORMAT.GIF.getValue() == formatName) {
GifDecoder decoder = new GifDecoder();
int status = decoder.read(sourcePath);
if (status != GifDecoder.STATUS_OK) {
throw new IOException("read image " + sourcePath + " error!");
}
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(targetPath);
encoder.setRepeat(decoder.getLoopCount());
for (int i = 0; i < decoder.getFrameCount(); i++) {
encoder.setDelay(decoder.getDelay(i));
BufferedImage childImage = decoder.getFrame(i);
BufferedImage image = childImage.getSubimage(x, y, width, height);
encoder.addFrame(image);
}
encoder.finish();
} else {
BufferedImage image = ImageIO.read(file);
image = image.getSubimage(x, y, width, height);
ImageIO.write(image, formatName, new File(targetPath));
}
return targetPath;
}
五、圖片壓縮
public static String zoom(String sourcePath, String targetPath, int width, int height) throws IOException {
File file = new File(sourcePath);
if (!file.exists()) {
throw new IOException("not found the image :" + sourcePath);
}
if (null == targetPath || targetPath.isEmpty()) {
targetPath = sourcePath;
}
String formatName = getImageFormatName(file);
if (null == formatName) {
return targetPath;
}
formatName = formatName.toLowerCase();
String pathPrefix = getPathWithoutSuffix(targetPath);
targetPath = pathPrefix + formatName;
// GIF處理
if (IMAGE_FORMAT.GIF.getValue() == formatName) {
GifDecoder decoder = new GifDecoder();
int status = decoder.read(sourcePath);
if (status != GifDecoder.STATUS_OK) {
throw new IOException("read image " + sourcePath + " error!");
}
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(targetPath);
encoder.setRepeat(decoder.getLoopCount());
for (int i = 0; i < decoder.getFrameCount(); i++) {
encoder.setDelay(decoder.getDelay(i));
BufferedImage image = zoom(decoder.getFrame(i), width, height);
encoder.addFrame(image);
}
encoder.finish();
} else {
BufferedImage image = ImageIO.read(file);
BufferedImage zoomImage = zoom(image, width, height);
ImageIO.write(zoomImage, formatName, new File(targetPath));
}
return targetPath;
}
六、圖片水印
private static void waterMark(Image srcImg, String path) throws IOException {
int srcImgWidth = srcImg.getWidth(null);
int srcImgHeight = srcImg.getHeight(null);
/*
//網(wǎng)絡(luò)圖片
URL url = new URL("url");
//將URL對(duì)象輸入流轉(zhuǎn)化為圖片對(duì)象 (url.openStream()方法,獲得一個(gè)輸入流)
Image srcImg = ImageIO.read(url.openStream());
//獲取圖片的寬
int srcImgWidth = srcImg.getWidth(null);
//獲取圖片的高
int srcImgHeight = srcImg.getHeight(null);
System.out.println("圖片的寬:"+srcImgWidth);
System.out.println("圖片的高:"+srcImgHeight);
*/
BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
// 加水印
//創(chuàng)建畫筆
Graphics2D g = bufImg.createGraphics();
//繪制原始圖片
g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
/*
//文字水印
//根據(jù)圖片的背景設(shè)置水印顏色
g.setColor(new Color(255, 255, 255, 128));
//設(shè)置字體 畫筆字體樣式為微軟雅黑,加粗,文字大小為60pt
g.setFont(new Font("微軟雅黑", Font.BOLD, 60));
String waterMarkContent = "自定義水印";
//設(shè)置水印的坐標(biāo)(為原圖片中間位置)
int x = srcImgWidth / 2;
int y = srcImgHeight / 2;
//畫出水印 第一個(gè)參數(shù)是水印內(nèi)容,第二個(gè)參數(shù)是x軸坐標(biāo),第三個(gè)參數(shù)是y軸坐標(biāo)
g.drawString(waterMarkContent, x, y);
g.dispose();*/
//圖片水印
// 水印文件
String waterMarkImage = "D:/print.jpg";
Image srcWaterMark = ImageIO.read(new File(waterMarkImage));
//獲取水印圖片的寬度
int widthWaterMark = srcWaterMark.getWidth(null);
//獲取水印圖片的高度
int heightWaterMark = srcWaterMark.getHeight(null);
//設(shè)置 alpha 透明度:alpha 必須是范圍 [0.0, 1.0] 之內(nèi)(包含邊界值)的一個(gè)浮點(diǎn)數(shù)字
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.9f));
//繪制水印圖片
g.drawImage(srcWaterMark, (srcImgWidth - widthWaterMark) / 10,
(srcImgHeight - heightWaterMark) / 10, widthWaterMark, heightWaterMark, null);
// 水印文件結(jié)束
g.dispose();
//文件輸出地址
String tarImgPath = path;
// 輸出圖片
FileOutputStream outImgStream = new FileOutputStream(tarImgPath);
ImageIO.write(bufImg, "png", outImgStream);
outImgStream.flush();
outImgStream.close();
}
七、Thumbnails工具類
通過以上對(duì)圖片的各種操作,還是需要對(duì)流進(jìn)行轉(zhuǎn)化,那是不是已經(jīng)有成型的工具類了呢?對(duì),Thumbnails工具類就能對(duì)以上各種情況處理。
主要有以下功能處理:
- 旋轉(zhuǎn)
- 水印
- 裁剪
- 指定大小進(jìn)行縮放
- 按照比例進(jìn)行縮放
- 不按照比例,指定大小進(jìn)行縮放
- 轉(zhuǎn)化圖片格式
- 輸出到OutputStream
- 輸出到BufferedImage
代碼示例如下:
依賴
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.17</version>
</dependency>
代碼
@SneakyThrows
public static void main(String[] args) {
//指定大小進(jìn)行縮放
Thumbnails.of("D:/test.jpg").size(100, 100).toFile("D:/test.jpg.jpg");
//按照比例進(jìn)行縮放
// scale 圖片的壓縮比例 值在0-1之間,1f就是原圖,0.5就是原圖的一半大小
// outputQuality 圖片壓縮的質(zhì)量 值在0-1 之間,越接近1質(zhì)量越好,越接近0 質(zhì)量越差
Thumbnails.of("D:/test.jpg").scale(0.75f).outputQuality(0.8f).toFile("D:/test.jpg");
//不按照比例,指定大小進(jìn)行縮放 100 keepAspectRatio(false) 默認(rèn)是按照比例縮放的
Thumbnails.of("D:/test.jpg").size(100, 100).keepAspectRatio(false).toFile("D:/test.jpg");
//旋轉(zhuǎn) rotate(角度),正數(shù):順時(shí)針 負(fù)數(shù):逆時(shí)針
Thumbnails.of("D:/test.jpg").size(1024, 1024).rotate(90).toFile("C:/image+90.jpg");
//水印 watermark(位置,水印圖,透明度)
Thumbnails.of("D:/test.jpg").size(1024, 1024)
.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File("水印地址")), 0.5f)
.outputQuality(0.4f).toFile("輸出地址");
//裁剪
Thumbnails.of("D:/test.jpg").sourceRegion(Positions.CENTER, 400, 400).size(200, 200).keepAspectRatio(false)
.toFile("輸出地址");
//轉(zhuǎn)化圖片格式
Thumbnails.of("D:/test.jpg").size(666, 666).outputFormat("png").toFile("D:/test.png");
// 輸出到OutputStream
OutputStream os = new FileOutputStream("D:/test.jpg");
Thumbnails.of("test.jpg").size(666, 666).toOutputStream(os);
//輸出到BufferedImage
BufferedImage thumbnail = Thumbnails.of("D:/test.jpg").size(666, 666).asBufferedImage();
ImageIO.write(thumbnail, "jpg", new File("test.jpg"));
}
到此這篇關(guān)于Java中圖片的常用操作代碼總結(jié)的文章就介紹到這了,更多相關(guān)Java圖片操作內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
劍指Offer之Java算法習(xí)題精講二叉樹專項(xiàng)訓(xùn)練
跟著思路走,之后從簡(jiǎn)單題入手,反復(fù)去看,做過之后可能會(huì)忘記,之后再做一次,記不住就反復(fù)做,反復(fù)尋求思路和規(guī)律,慢慢積累就會(huì)發(fā)現(xiàn)質(zhì)的變化2022-03-03
java 增強(qiáng)型for循環(huán)語法詳解
增強(qiáng)型 for 循環(huán)(也稱為 “for-each” 循環(huán))是 Java 從 JDK 5 開始引入的一種便捷循環(huán)語法,旨在簡(jiǎn)化對(duì)數(shù)組或集合類的迭代操作,這篇文章主要介紹了java 增強(qiáng)型for循環(huán) 詳解,需要的朋友可以參考下2025-04-04
SpringMVC多個(gè)文件上傳及上傳后立即顯示圖片功能
這篇文章主要介紹了SpringMVC多個(gè)文件上傳及上傳后立即顯示圖片功能,非常不錯(cuò),具有參考借鑒價(jià)值功能,需要的朋友可以參考下2017-10-10
Hibernate映射解析之關(guān)聯(lián)映射詳解
所謂關(guān)聯(lián)映射就是將關(guān)聯(lián)關(guān)系映射到數(shù)據(jù)庫里,在對(duì)象模型中就是一個(gè)或多個(gè)引用。下面這篇文章詳細(xì)的給大家介紹了Hibernate映射解析之關(guān)聯(lián)映射的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起看看吧。2017-02-02
Java調(diào)用groovy實(shí)現(xiàn)原理代碼實(shí)例
這篇文章主要介紹了Java調(diào)用groovy實(shí)現(xiàn)原理代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-12-12
Springboot實(shí)現(xiàn)ModbusTCP通信的示例詳解
ModbusTCP協(xié)議是Modbus由MODICON公司于1979年開發(fā),是一種工業(yè)現(xiàn)場(chǎng)總線協(xié)議標(biāo)準(zhǔn),本文主要介紹了Springboot實(shí)現(xiàn)ModbusTCP通信的相關(guān)知識(shí),需要的可以參考下2023-12-12

