ImageIo.read读取图片有一层红色解决办法

使用ImageIo读取图片时,有时候会出现一层红色遮罩,起初以为是自己程序出问题,上网查了下,有人说是JAVA的BUG,

http://blog.csdn.net/shixing_11/article/details/6897871这篇文章中介绍的是利用ToolKit.getImage方法替代ImageIo的read方法,但由于我要读取的网络图片,尽管ToolKit有提供通过url获取图片的方法,但由于有些网站需要UA和其他字段的验证,所以只能自己获取图片字节数组,但数组要转换成Image对象又要通过ImageIo的read方法,所以不得不另寻他路,在类ImageIcon中发现了ImageIcon(byte[] imageData) 构造函数,虽然ImageIcon没有实现Image接口但提供了一个返回Image对象的函数,试了一下,可以正常读取图像,而且画质和ImageIo没什么差别,代码如下

 1 package org.fzu.datamaker.gui.util;
 2 
 3 import java.awt.Image;
 4 import java.io.InputStream;
 5 import java.net.HttpURLConnection;
 6 import java.net.URL;
 7 
 8 import javax.swing.ImageIcon;
 9 
10 public class HttpImage {
11     private Image image;
12     private byte[]buf;
13     private static HttpImage httpImage;
14     private boolean stop=false;
15     public HttpImage()
16     {
17         buf=new byte[1024*1024*3];
18     }
19     public static HttpImage getHttpImage()
20     {
21         if(httpImage==null)
22             httpImage=new HttpImage();
23         return httpImage;
24     }
25     public Image getImage(String addr)
26     {
27         stop = false;
28         image = null;
29         HttpURLConnection conn = null;
30         InputStream in = null;
31         try {
32             URL url = new URL(addr);
33             conn = (HttpURLConnection) url.openConnection();
34             conn.setConnectTimeout(10 * 1000);      // 10秒的连接超时
35             conn.setReadTimeout(15 * 1000);       // 15秒的读取超时
36             conn.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
37             conn.setDoInput(true);
38             conn.connect();
39             in = conn.getInputStream();
40             int readlen = 0;
41             int contentlen = 0;
42             do {
43                 // 一次读取10KB,如果返回值小于0可以认为一定读取完毕
44                 contentlen += readlen;
45                 readlen = in.read(buf, contentlen, 1024 * 10);
46                 if (stop) {
47                     in.close();
48                     conn.disconnect();
49                     return null;
50                 }
51             } while (readlen > 0);
52             in.close();
53             conn.disconnect();
54         //  image = ImageIO.read(new ByteArrayInputStream(buf));
55             image=(new ImageIcon(buf)).getImage();    //利用ImageIcon获取Image对象
56         } catch (Exception e) {
57             image = null;
58             e.printStackTrace();
59             try {
60                 in.close();
61                 conn.disconnect();
62             } catch (Exception ex) {
63             }
64         }
65         return image;
66     }
67     public void stop()
68     {
69         this.stop=true;
70     }
71     
72 }

 

转载于:https://www.cnblogs.com/weisuoc/archive/2013/06/04/3116357.html

你可能感兴趣的:(ImageIo.read读取图片有一层红色解决办法)