ImageIO类的使用

重点内容
(一) How to read an image from file or URL?

  1. 从本地文本读取图片
File sourceimage = new File("c:\\mypic.jpg");
Image image = ImageIO.read(sourceimage);
  1. 从网络上获取图片
URL url = new URL("http://www.mkyong.com/image/mypic.jpg");
Image image = ImageIO.read(url);

3.使用ImageIO读取图片实例

package ImageIO;
import java.awt.Image;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class ReadImage
{
    public static void main( String[] args )
    {
        Image image = null;
        try {
            URL url = new URL("http://img04.tooopen.com/images/20130805/tooopen_10473021.jpg");
            image = ImageIO.read(url);
        } catch (IOException e) {
            e.printStackTrace();
        }

        JFrame frame = new JFrame();
        frame.setSize(300, 300);
        JLabel label = new JLabel(new ImageIcon(image));
        frame.add(label);
        frame.setVisible(true);
    }
}

结果:
ImageIO类的使用_第1张图片


(二)How to write an image to file - Java ImageIO?

1.ImageIO可以从本地文件中读取图片和写入图片,也可以从网络上读取图片写入本地文件中。

2.演示ImageIO读取URL资源

package ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;

public class WriteImage
{
    public static void main( String[] args )
    {
        BufferedImage image = null;
        try {

            URL url = new URL("http://p3.so.qhmsg.com/t014d3503dd2d67d728.jpg");
            image = ImageIO.read(url);
            //.jpg文件占空间最小
            ImageIO.write(image, "jpg",new File("D:\\out.jpg"));
            ImageIO.write(image, "gif",new File("D:\\out.gif"));
            ImageIO.write(image, "png",new File("D:\\out.png"));

        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("成功写入D盘");
    }
}

3.How to load and write an image in Java?

加载图片:

BufferedImage originalImage = ImageIO.read(new File("c:\\image\\1.jpg"));

写入图片:

ImageIO.write(originalImage, "jpg", new File("c:\\image\\1.jpg"));

读写操作实例代码演示:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageTest {

    public static void main(String[] args) {

        try {
           //使用jpg格式,可以减少存储空间
            BufferedImage originalImage = ImageIO.read(new File(
                    "c:\\image\\1.jpg"));

            ImageIO.write(originalImage, "jpg", new File(
                    "c:\\image\\1.jpg"));

        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

    }

}

你可能感兴趣的:(Java基础)