我有一个图片网址。现在我想获得该图像的byte []。如何以字节形式获取该图像。
实际上图像是验证码图像。我正在使用decaptcher.com来解决验证密码。要通过API将该验证码图像发送到decaptcher.com,图像应以字节为单位。
这就是为什么我想让网址上的图像以字节为单位。
答案 0 :(得分:8)
修改强>
从这个SO question我得到了如何将输入流读入字节数组。
这是修订后的计划。
import java.io.*;
import java.net.*;
public class ReadBytes {
public static void main( String [] args ) throws IOException {
URL url = new URL("http://sstatic.net/so/img/logo.png");
// Read the image ...
InputStream inputStream = url.openStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte [] buffer = new byte[ 1024 ];
int n = 0;
while (-1 != (n = inputStream.read(buffer))) {
output.write(buffer, 0, n);
}
inputStream.close();
// Here's the content of the image...
byte [] data = output.toByteArray();
// Write it to a file just to compare...
OutputStream out = new FileOutputStream("data.png");
out.write( data );
out.close();
// Print it to stdout
for( byte b : data ) {
System.out.printf("0x%x ", b);
}
}
}
这可能适用于非常小的图像。对于较大的,请询问/搜索“将输入流读入字节数组”
现在我发布的代码也可以用于更大的图像。
答案 1 :(得分:0)
您可能需要阅读this来阅读图片.ImageIO.Read(url)会给您一个Buffered Image然后您可以询问相关信息。我在BufferedReader上使用getRGB方法来读取单个像素。
答案 2 :(得分:0)
如果您想要存储在磁盘上的字节字符串,只需创建一个套接字并打开图像文件即可。然后在线路上读取字节。
我没有任何示例代码,因为我已经做了一段时间了,所以请原谅我,如果我的细节错了,请确保我直接给你,但基本的想法是是:
URL imageUrl=new URL("http://someserver.com/somedir/image.jpg");
URLConnection imageConnect=imageUrl.openConnection();
imageConnect.connect();
InputStream is=imageConnect.getInputStream();
... read from the input stream ...