How to grab byte[] of an Image in java?

后端 未结 3 1470
面向向阳花
面向向阳花 2021-01-23 22:40

I have a url of an Image. Now I want to get the byte[] of that image. How can I get that image in byte form.

Actually the image is a captcha image. I am using decaptcher

相关标签:
3条回答
  • 2021-01-23 23:16

    EDIT

    From this SO question I've got how to read an input stream into a byte array.

    Here's the revised program.

    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);
            }
        }
    }
    

    This may work for very small images. For larger ones, ask/search about "read input stream into byte array"

    Now the code I posted works for larger images too.

    0 讨论(0)
  • 2021-01-23 23:28

    If you want the byte string as it is stored on disk, just create a socket and open the image file. Then read the bytes as they come down the wire.

    I don't have any sample code handy and it's been a while since I've done this, so excuse me if I've got the details wrong to be sure I give this to you straight, but the basic idea would be:

    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 ...
    
    0 讨论(0)
  • 2021-01-23 23:31

    You may want to read this for reading an image in. ImageIO.Read(url) will give you a Buffered Image Which you can then ask for information. I use the getRGB method on BufferedReader to read individual pixels.

    0 讨论(0)
提交回复
热议问题