专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java图片处理:读写

Java图片处理:读写

更新时间:2022-12-14 11:41:21 来源:赢咖4 浏览982次

Java实现一个特定类型的对象称为BufferedImage图像在Java中。可以从几个不同的图像读取BufferedImage类型(即BMP HEIC,等等)。不是所有这些都是由ImageIO本身,但也有插件扩展ImageIO例如Apache成像和JDeli和其他库。

在Java本身,所有各种图像类型隐藏的复杂性,我们只有在BufferedImage工作。Java提供了直接访问图像像素和颜色信息,并允许转换和图像处理。

类需要执行读写操作:

1. io .读写文件:一个图像文件,我们必须导入文件类。这个类代表文件和目录路径名。

2. io .IOException:处理错误,我们使用IOException类。

3. java.awt.image。BufferedImage:保存图像,我们创建BufferedImage对象;我们使用BufferedImage类。该对象用于存储在RAM中。

4. javax.imageio。ImageIO: p

// Java program to demonstrate read and write of image
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class MyImage {
	public static void main(String args[])
		throws IOException
	{
		// width of the image
		int width = 963;
		// height of the image
		int height = 640;
		// For storing image in RAM
		BufferedImage image = null;
		// READ IMAGE
		try {
			File input_file = new File(
				"C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png");
			// image file path create an object of
			// BufferedImage type and pass as parameter the
			// width, height and image int
			// type. TYPE_INT_ARGB means that we are
			// representing the Alpha , Red, Green and Blue
			// component of the image pixel using 8 bit
			// integer value.
			image = new BufferedImage(
				width, height, BufferedImage.TYPE_INT_ARGB);
			// Reading input file
			image = ImageIO.read(input_file);
			System.out.println("Reading complete.");
		}
		catch (IOException e) {
			System.out.println("Error: " + e);
		}
		// WRITE IMAGE
		try {
			// Output file path
			File output_file = new File(
				"C:/Users/hp/Desktop/Image Processing in Java/gfg.png");
			// Writing to file taking type and path as
			ImageIO.write(image, "png", output_file);
			System.out.println("Writing complete.");
		}
		catch (IOException e) {
			System.out.println("Error: " + e);
		}
	} // main() ends here
} // class ends here

输出

注意:这段代码不会在网上IDE运行,因为它需要一个磁盘上的形象。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>