ImageIO工具类简介及应用

版权声明:本文为博主原创文章,转载请注明作者和出处,如有错误,望不吝赐教。 https://blog.csdn.net/weixin_41888813/article/details/85043969

Java中进行图像I/O(即读图片和写图片,不涉及到复杂图像处理)有三个方法:

  1. Java Image I/O API,支持常见图片,从Java 2 version 1.4.0开始就内置了。主页:http://java.sun.com/javase/6/docs/technotes/guides/imageio/index.html
  2. JAI 中的 Image I/O Tools,支持更多图片类型,例如JPEG-LS, JPEG2000, 和 TIFF。JAI 是一个关于图像处理的框架,很庞大,其中仅仅jai-imageio是关于图像I/O的,其他的可以不看。JAI的com.sun.media.jai.codec 也有一定的图像解码能力
  3. 当然,还有众多的java开源工具包可以读写图像,例如JIMI, JMagic等,但JDK目前本身能够读写图片,就用JDK的,开发和部署方便,不需要额外下载jar包。

如果你仅仅想读取常见格式的图片,不需要用JAI这么高级这么庞大的东西,用Java Image I/O API即可。

下面重点介绍Java中进行图像I/O的第一种方法 Java Image I/O API。


读取图片

 源码介绍

public static BufferedImage read(File input) throws IOException

public static BufferedImage read(InputStream input) throws IOException

public static BufferedImage read(URL input) throws IOException

public static BufferedImage read(ImageInputStream stream) throws IOException

实际应用:获取图片的大小和尺寸

java获取图片的大小和尺寸,有两种获取的源:

  1. 一种是读取本地的图片获取大小和尺寸
  2. 一种是通过服务器上图片的地址获取图片的尺寸

第一种,获取本地图片的大小和尺寸

     /**
      * 本地获取
      * */
     @Test
     public void testImg2() throws IOException{
            File picture = new File("C:/Users/aflyun/Pictures/Camera Roll/1.jpg");
            BufferedImage sourceImg =ImageIO.read(new FileInputStream(picture)); 
            System.out.println(String.format("%.1f",picture.length()/1024.0));// 源图大小
            System.out.println(sourceImg.getWidth()); // 源图宽度
            System.out.println(sourceImg.getHeight()); // 源图高度

     }

第二种,获取服务器图片的尺寸

     /**
      * 获取服务器上的
      */
     @Test
     public void getImg() throws FileNotFoundException, IOException{
         URL url = new URL("http://img.mall.tcl.com/dev1/0/000/148/0000148235.fid");
         URLConnection connection = url.openConnection();
         connection.setDoOutput(true);
         BufferedImage image = ImageIO.read(connection.getInputStream());  
         int srcWidth = image .getWidth();      // 源图宽度
         int srcHeight = image .getHeight();    // 源图高度

         System.out.println("srcWidth = " + srcWidth);
         System.out.println("srcHeight = " + srcHeight);
     }

     /**
      * 获取服务器上的
      */
     @Test
     public void testImg1() throws IOException{
            InputStream murl = new URL("http://img.mall.tcl.com/dev1/0/000/148/0000148235.fid").openStream();
            BufferedImage sourceImg =ImageIO.read(murl);   
            System.out.println(sourceImg.getWidth());   // 源图宽度
            System.out.println(sourceImg.getHeight());   // 源图高度
     }

写图片

BufferedImage bi;
File f = new File(“c:\images\myimage.png”);
ImageIO.write(im, “png”, f);

参考来源于:

https://blog.csdn.net/fanhenghui/article/details/70200901

https://blog.csdn.net/u010648555/article/details/51647557

猜你喜欢

转载自blog.csdn.net/weixin_41888813/article/details/85043969