当前页面: 开发资料首页 → J2SE 专题 → URL读取远程图片!
URL读取远程图片!
摘要: URL读取远程图片!
String str = -#34;http://location/temp/mapimage/img_1157169390174.gif-#34;;
URL url = new URL( str );
这是一个URL的连接,怎么把这个图片读成一个流,并把这个流保存在一个byte[]中,传输给另一个终端,另一个终端解析这个字节数组,保存或显示。
不保存到一个byte[]中也行,但要有一个中间量,来传输.
我需要代码,急用,谢谢各位高手.
String str = -#34;http://location/temp/mapimage/img_1157169390174.gif-#34;;
URL url = new URL( str );
InputStream in = url.openStream();
然后读取in
如何读啊,再如何写啊,给个例子,我现在有点晕,晕了两天了,文件的问题我已经解决了,就事图片,我没怎么搞好。
String str = -#34;http://location/temp/mapimage/img_1157169390174.gif-#34;;
URL url = new URL( str );
InputStream in = url.openStream();
以流的方式读出来,然后写入到一个后缀为.gif文件
怎么写,怎么写,同志们那,我能读出 来了,写给 个 代码测试下,没搞定呢。
String str = -#34;http://location/temp/mapimage/img_1157169390174.gif-#34;;
URL url = new URL( str );
InputStream in = url.openStream();
FileOutputStream fos = new FileOutputStream(-#34;c:/test.gif-#34;);
URL url = new URL(-#34;http://location/temp/mapimage/img_1157169390174.gif-#34;);
InputStream is = url.openStream();
byte b[] = new byte[4096];
while(true)
{
int i = is.read(b);
if(i==-1) break;
fos.write(b);
}
fos.close();
import java.io.*;
import java.net.*;
class a{
public static void main(String sp[])
{
try
{
FileOutputStream fos = new FileOutputStream(-#34;c:/test.gif-#34;);
URL url = new URL(-#34;http://community.csdn.net/expert/images/rank/user1.gif-#34;);
InputStream is = url.openStream();
byte b[] = new byte[4096];
while(true)
{
int i = is.read(b);
if(i==-1) break;
fos.write(b);
}
fos.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
一度,不成啊,连test.gif文件都不生成,我改成c://test.gif也不行啊。
String str = -#34;http://location/temp/mapimage/img_1157169390174.gif-#34;;
URL url = new URL(str);
URLConnection urlConn = url.openConnection();
int contLen = urlConn.getContentLength();
InputStream in = urlConn.getInputStream();
int readLen = 0;
byte[] tmpb = new byte[1024*8];
int totalReadLen = 0;
byte[] fileContent = new byte[contLen];//保存图片数据
while((readLen=in.read(tmpb, 0, tmpb.length))-#62;0 -#38;-#38; totalReadLen-#60;contLen) {
System.arraycopy(tmpb, 0, fileContent, totalReadLen, readLen);
totalReadLen += readLen;
}
//接下来可以进行针对fileContent的操作
...
------
注:以上代码未经测试,仅供参考
用ImageIO也可以
直接可以生成一个图像的引用
BufferedImage bi=javax.imageio.ImageIO.read(url);
然后就方便了
hegaofei(huohe) ( ) 信誉:100 Blog 2006-9-2 23:01:40 得分: 0
一度,不成啊,连test.gif文件都不生成,我改成c://test.gif也不行啊。
===================
我这都成功了啊
up
真的不行,我试了很多次了。。。。
好了,调好了,谢谢一度。