在java中将图像转换为二进制数据(0和1)

我想从URL中读取图像并将其转换为二进制数据。 请帮我..

byte[] data = null; ByteArrayOutputStream bas = null; try { URL u = new URL( "http://sofzh.miximages.com/java/eso0844a.jpg"); HttpURLConnection con1 = (HttpURLConnection) u.openConnection(); con1.setAllowUserInteraction(true); con1.setRequestMethod("GET"); con1.connect(); InputStream is = con1.getInputStream(); BufferedImage imgToServe = null; if (is != null) { imgToServe = ImageIO.read(is); } bas = new ByteArrayOutputStream(); ImageIO.write(imgToServe, "jpg", bas); File f = new File("C:\\img.jpg"); ImageIO.write(imgToServe, "jpg", f); data = bas.toByteArray(); String str = ""; for (int i = 0; i < data.length; i++) { str = str + toBinary(data[i]); } System.out.println(str); } catch (HTTPException he) { } catch (IOException ioe) { } } private static String toBinary(byte b) { StringBuilder sb = new StringBuilder("00000000"); for (int bit = 0; bit > bit) & 1) > 0) { sb.setCharAt(7 - bit, '1'); } } return (sb.toString()); } 

如果您正在从URL读取图像,它将已经二进制格式。 只需下载数据并忽略它是图像的事实。 毕竟,参与下载的代码无关紧要。 假设您要将其写入文件或类似文件,只需打开URLConnection并打开FileOutputStream ,然后重复从Web输入流中读取,将您读取的数据写入输出流。

如果那不是您所追求的,请澄清问题。

编辑:如果你真的想把数据作为单独的 (这对我来说有点奇怪)你应该将问题分成两部分:

  • 下载数据(参见上文;如果您不需要它在磁盘上,请考虑写入ByteArrayOutputStream
  • 将任意二进制数据(字节数组或输入流)转换为0和1

你如何处理后一项任务将取决于你真正想要做什么。 这里的真正目的是什么?

您可以使用标准ImageIOread方法接受一个URL并将其检索到一个Image 。 然后,您可以使用write方法将其写入File或类似于ByteArrayOutputStream ,它将图像输出到内存缓冲区。

 public static void main(String[] args) throws Exception { // read "any" type of image (in this case a png file) BufferedImage image = ImageIO.read(new URL("http://sofzh.miximages.com/java/Lenna.png")); // write it to byte array in-memory (jpg format) ByteArrayOutputStream b = new ByteArrayOutputStream(); ImageIO.write(image, "jpg", b); // do whatever with the array... byte[] jpgByteArray = b.toByteArray(); // convert it to a String with 0s and 1s StringBuilder sb = new StringBuilder(); for (byte by : jpgByteArray) sb.append(Integer.toBinaryString(by & 0xFF)); System.out.println(sb.toString()); } 

将路径/ url中的图像加载到BufferedImage

 public static Raster loadImageRaster(String file_path) throws IOException { File input = new File(file_path); BufferedImage buf_image = ImageIO.read(input); buf_image = binarizeImage(buf_image); return buf_image.getData(); //return raster } 

从原始BufferedImage创建二进制类型BufferedImage

 public static BufferedImage binarizeImage(BufferedImage img_param) { BufferedImage image = new BufferedImage( img_param.getWidth(), img_param.getHeight(), BufferedImage.TYPE_BYTE_BINARY); Graphics g = image.getGraphics(); g.drawImage(img_param, 0, 0, null); g.dispose(); return image; } 

BufferedImage转换为Raster以便您可以逐个像素地操作它

 imageRaster.getSample(x, y, 0) 

Raster.getSample(x,y, channel)将返回0s1s

对于TYPE_BYTE_BINARY图像,channel = 0