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

bd96500e110b49cbb3cd949968f18be7.png

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

}

解决方案

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.

EDIT: If you really want to get the data as individual bits (which seems somewhat odd to me) you should separate the problem in two:

Downloading the data (see above; if you don't need it on disk, consider writing to a ByteArrayOutputStream)

Converting arbitrary binary data (a byte array or an input stream) into 0s and 1s

How you tackle the latter task will depend on what you actually want to do with the bits. What's the real aim here?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值