在java中将图像转换为二进制数据(0和1) [英] Convert an image to binary data (0s and 1s) in java
问题描述
我想从网址读取图片并将其转换为二进制数据。请帮帮我..
I want to read an image from a url and convert it into binary data. Please help me..
byte[] data = null;
ByteArrayOutputStream bas = null;
try {
URL u = new URL(
"http://www.eso.org/public/archives/images/screen/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 < 8; bit++) {
if (((b >> bit) & 1) > 0) {
sb.setCharAt(7 - bit, '1');
}
}
return (sb.toString());
}
推荐答案
如果您正在阅读来自URL的图像,它已经 以二进制格式。只需下载数据并忽略它是图像的事实。毕竟,参与下载的代码无关紧要。假设您要将其写入文件或类似内容,只需打开 URLConnection
并打开 FileOutputStream
,并重复从Web输入流中读取,将您读取的数据写入输出流。
If you're reading the image from a URL, it will already be in a binary format. Just download the data and ignore the fact that it's an image. The code which is involved in download it won't care, after all. Assuming you want to write it to a file or something similar, just open the URLConnection
and open the FileOutputStream
, and repeatedly read from the input stream from the web, writing the data you've read to the output stream.
如果不是您所追求的,请澄清问题。
If that's not what you were after, please clarify the question.
编辑:如果你真的想把数据作为单独的位(这对我来说有点奇怪),你应该将问题分成两部分:
If you really want to get the data as individual bits (which seems somewhat odd to me) you should separate the problem in two:
- 下载数据(见上文;如果您不需要它在磁盘上,请考虑写入
ByteArrayOutputStream
) - 将任意二进制数据(字节数组或输入流)转换为0和1
如何处理后一项任务将取决于您实际想要对这些位做什么。这里的真正目的是什么?
How you tackle the latter task will depend on what you actually want to do with the bits. What's the real aim here?
这篇关于在java中将图像转换为二进制数据(0和1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!