在Java中,我们可以使用javax.imageio。ImageIO类来读取和写入一个图像。
从文件读取图像。
BufferedImage image = ImageIO.read(new File("c:\test\image.png"));
读一个图像从一个URL。
BufferedImage image = ImageIO.read(new URL("https://example.com/image.png"));
以不同的图像格式写入或保存图像。
ImageIO.write(bufferedImage , "jpg", new File("c:\test\image.jpg"));
ImageIO.write(bufferedImage , "gif", new File("c:\test\image.gif"));
ImageIO.write(bufferedImage , "png", new File("c:\test\image.png"));
下面的代码片段列出了所有支持的格式。
String writerNames[] = ImageIO.getWriterFormatNames();
Arrays.stream(writerNames).forEach(System.out::println);
输出
PG
jpg
tiff
bmp
BMP
gif
GIF
WBMP
png
PNG
JPEG
tif
TIF
TIFF
wbmp
jpeg
一个完整的 Java 示例,ImageIO用于从 URL(Google 徽标)读取图像、调整大小并将其300x150保存到文件中。
package com.mkyong.io.image;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class ReadWriteImage {
// Google logo url
private static final String GOOGLE_LOGO =
"https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png";
public static void main(String[] args) {
try {
URL url = new URL(GOOGLE_LOGO);
// read an image from url
BufferedImage image = ImageIO.read(url);
// resize image to 300x150
Image scaledImage = image.getScaledInstance(300, 150, Image.SCALE_DEFAULT);
// save the resize image aka thumbnail
ImageIO.write(
convertToBufferedImage(scaledImage),
"png",
new File("C:\test\google.png"));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done");
}
// convert Image to BufferedImage
public static BufferedImage convertToBufferedImage(Image img) {
if (img instanceof BufferedImage) {
return (BufferedImage) img;
}
// Create a buffered image with transparency
BufferedImage bi = new BufferedImage(
img.getWidth(null), img.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics2D = bi.createGraphics();
graphics2D.drawImage(img, 0, 0, null);
graphics2D.dispose();
return bi;
}
}
下载的图像被调整为 300×150。
你适合学Java吗?4大专业测评方法
代码逻辑 吸收能力 技术学习能力 综合素质
先测评确定适合在学习