【问题标题】:How to grab byte[] of an Image in java?如何在java中抓取图像的字节[]?
【发布时间】:2010-12-01 11:55:28
【问题描述】:

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

实际上该图像是验证码图像。我正在使用 deaptcher.com 来解决该验证码。要通过其 API 将该验证码图像发送到 decaptcher.com,该图像应以字节数组为单位。

这就是为什么我想让 url 上的图像以字节形式显示。

【问题讨论】:

  • 如果你只想要来自 URL 的原始数据,为什么你需要创建一个 Image?
  • 图像的实际字节数(因为它将存储在磁盘上,以特定的文件类型)?还是图片的像素数据?
  • 如果您想要像素的表示,请注意您需要决定需要哪种表示。有数百种表示像素的方法。 32 位 ARGB 很常见,例如,每个像素使用一个完整的 32 位 int,但绝不是唯一的表示。

标签: java image url


【解决方案1】:

编辑

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

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

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

【讨论】:

    【解决方案2】:

    您可能需要阅读this 来读取图像。ImageIO.Read(url) 将为您提供Buffered Image,然后您可以询问信息。我使用 BufferedReader 上的 getRGB 方法读取单个像素。

    【讨论】:

      【解决方案3】:

      如果您想要将字节字符串存储在磁盘上,只需创建一个套接字并打开图像文件。然后在它们通过网络时读取字节。

      我手头没有任何示例代码,而且我已经有一段时间没有做这个了,所以如果我的细节有误,请原谅我一定要把它直接告诉你,但基本的想法是是:

      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 ...
      

      【讨论】:

      • 这将读取 JPG 文件的内容,因此它会为您提供 JPG 格式的图像数据。也许海报需要原始像素数据 - 但问题并不清楚。
      • 非常正确,这就是为什么我开始“如果你想要字节字符串,因为它存储在磁盘上......”。在我的脑海中,我知道创建图像对象或类似对象的唯一方法是通过网络读取 JPG(或任何格式),然后通过类运行它以从磁盘读取图像。如果这是问题所在,我将不得不回顾 API 以获取详细信息,但我怀疑可能会将输入流直接吸入图像阅读器。
      猜你喜欢
      • 2014-02-13
      • 1970-01-01
      • 2014-10-16
      • 2015-04-07
      • 2012-02-20
      • 2020-06-08
      • 2012-04-21
      • 1970-01-01
      相关资源
      最近更新 更多