个性化阅读
专注于IT技术分析

Java中的图像处理基础介绍S1(读和写)

点击下载

在这一组中, 我们将学习如何读和写Java中的图像文件。

需要执行以下操作:

  1. 要读写图像文件, 我们必须导入File类[importjava.io.File; ]。此类通常表示文件和目录路径名。
  2. 为了处理错误, 我们使用IOException类[import java.io.IOException; ]
  3. 为了保存图像, 我们创建了BufferedImage对象, 为此我们使用BufferedImage类[importjava.awt.image.BufferedImage; ]。该对象用于在RAM中存储图像。
  4. 要执行图像读写操作, 我们将导入ImageIO类[importjavax.imageio.ImageIO;]。此类具有读取和写入图像的静态方法。
//Java program to demonstrate read and write of image
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
  
public class MyImage
{
     public static void main(String args[]) throws IOException
     {
         int width = 963 ;    //width of the image
         int height = 640 ;   //height of the image
  
         //For storing image in RAM
         BufferedImage image = null ;
  
         //READ IMAGE
         try
         {
             File input_file = new File( "G:\\Inp.jpg" ); //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( "G:\\Out.jpg" );
  
             //Writing to file taking type and path as
             ImageIO.write(image, "jpg" , output_file);
  
             System.out.println( "Writing complete." );
         }
         catch (IOException e)
         {
             System.out.println( "Error: " +e);
         }
     } //main() ends here
} //class ends here

注意 :该代码将无法在在线IDE上运行, 因为它需要磁盘上的映像。

在下一组中, 我们将学习如何在JAVA中获取和设置图像的像素值。

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

赞(0)
未经允许不得转载:srcmini » Java中的图像处理基础介绍S1(读和写)

评论 抢沙发

评论前必须登录!