1.从本地文本读取图片?
File sourceimage = new File("c:\\mypic.jpg");
Image image = ImageIO.read(sourceimage);
?2.从网络上获取图片
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("https://tse3-mm.cn.bing.net/th/id/OIP-C.g9UbVfyVZX-SfD09JcYr5QHaEK?rs=1&pid=ImgDetMain");
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);
}
}
结果:
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("https://tse3-mm.cn.bing.net/th/id/OIP-C.g9UbVfyVZX-SfD09JcYr5QHaEK?rs=1&pid=ImgDetMain");
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盘");
}
}
加载图片:
BufferedImage originalImage = ImageIO.read(new File("D:\\img\\0a3b3288-3446-4420-bbff-f263d0c02d8e.jpg"));
?写入图片:
ImageIO.write(originalImage, "jpg", new File("D:\\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(
"D:\\image\\1.jpg"));
ImageIO.write(originalImage, "jpg", new File(
"D:\\image\\1.jpg"));
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}