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("隸書(shū)", Font.BOLD, 28));
g.drawString("自定義圖片", 200, 200);
ImageIO.write(bufferedImage, "jpg", new File("D:/test.jpg"));
} finally {
g.dispose();//釋放畫(huà)筆
}
}
輸出:

三、獲取圖片格式
代碼:
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)建畫(huà)筆
Graphics2D g = bufImg.createGraphics();
//繪制原始圖片
g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
/*
//文字水印
//根據(jù)圖片的背景設(shè)置水印顏色
g.setColor(new Color(255, 255, 255, 128));
//設(shè)置字體 畫(huà)筆字體樣式為微軟雅黑,加粗,文字大小為60pt
g.setFont(new Font("微軟雅黑", Font.BOLD, 60));
String waterMarkContent = "自定義水印";
//設(shè)置水印的坐標(biāo)(為原圖片中間位置)
int x = srcImgWidth / 2;
int y = srcImgHeight / 2;
//畫(huà)出水印 第一個(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工具類
通過(guò)以上對(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)文章
SpringBoot無(wú)法識(shí)別bootstrap.yml小綠葉問(wèn)題的解決辦法
一般單獨(dú)使用?Spring?Boot?時(shí),bootstrap.yml?文件一般是不會(huì)生效的,也就是沒(méi)有小綠葉圖標(biāo),本文給大家介紹了SpringBoot無(wú)法識(shí)別bootstrap.yml小綠葉問(wèn)題的解決辦法,文中給出了兩種解決方案,需要的朋友可以參考下2024-07-07
java數(shù)據(jù)結(jié)構(gòu)之插入排序
這篇文章主要為大家詳細(xì)介紹了java數(shù)據(jù)結(jié)構(gòu)之插入排序的相關(guān)代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11
OpenFeign實(shí)現(xiàn)微服務(wù)間的文件下載方式
這篇文章主要介紹了OpenFeign實(shí)現(xiàn)微服務(wù)間的文件下載方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
Idea如何關(guān)閉或開(kāi)啟引用提示Usages和Annotations
這篇文章主要介紹了Idea如何關(guān)閉或開(kāi)啟引用提示Usages和Annotations問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01
SpringCloud-Hystrix實(shí)現(xiàn)原理總結(jié)
通過(guò)hystrix可以解決雪崩效應(yīng)問(wèn)題,它提供了資源隔離、降級(jí)機(jī)制、融斷、緩存等功能。接下來(lái)通過(guò)本文給大家分享SpringCloud-Hystrix實(shí)現(xiàn)原理,感興趣的朋友一起看看吧2021-05-05
Spring/Spring Boot 中優(yōu)雅地做參數(shù)校驗(yàn)拒絕 if/else 參數(shù)校驗(yàn)
這篇文章主要介紹了Spring/Spring Boot 中優(yōu)雅地做參數(shù)校驗(yàn)拒絕 if/else 參數(shù)校驗(yàn),本文使用最新的 Spring Boot 版本 2.4.5,通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-04-04
SpringBoot常用數(shù)據(jù)庫(kù)開(kāi)發(fā)技術(shù)匯總介紹
Spring Boot常用的數(shù)據(jù)庫(kù)開(kāi)發(fā)技術(shù)有JDBCTemplate、JPA和Mybatis,它們分別具有不同的特點(diǎn)和適用場(chǎng)景,可以根據(jù)具體的需求選擇合適的技術(shù)來(lái)進(jìn)行開(kāi)發(fā)2023-04-04

