如何在java中抓取Image的byte []?

Yat*_*oel 1 java url image

我有一个图像的网址.现在我想获得该图像的byte [].如何以字节形式获取该图像.

实际上图像是验证码图像.我正在使用decaptcher.com来解决验证密码.要通过API将该验证码图像发送到decaptcher.com,图像应以字节数组形式显示.

这就是为什么我想让url上的图像以字节为单位.

Osc*_*Ryz 8

编辑

从这个问题我得到了如何将输入流读入字节数组.

这是修订后的计划.

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这可能适用于非常小的图像.对于较大的,请询问/搜索"将输入流读入字节数组"

现在我发布的代码也适用于更大的图像.