我想从网址读取图片并将其转换为二进制数据。请帮帮我..
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());
}
答案 0 :(得分:7)
如果您正在从URL中读取图像,则它已经 以二进制格式显示。只需下载数据并忽略它是图像的事实。毕竟,参与下载的代码无关紧要。假设您要将其写入文件或类似内容,只需打开URLConnection
并打开FileOutputStream
,然后重复读取来自Web的输入流,将您读过的数据写入输出流。
如果那不是您所追求的,请澄清问题。
编辑:如果你真的想把数据作为单独的位(这对我来说有点奇怪),你应该将问题分成两部分:
ByteArrayOutputStream
)如何处理后一项任务将取决于您实际想要对这些位执行的操作。这里的真正目的是什么?
答案 1 :(得分:5)
您可以使用标准ImageIO
。 read
方法需要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://upload.wikimedia.org/wikipedia/en/2/24/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());
}
答案 2 :(得分:3)
将路径/网址中的图片加载到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)
将返回0s
或1s
。
TYPE_BYTE_BINARY
张图片的频道= 0