简体   繁体   English

图片到字节数组不一致

[英]Image to byte array inconsistent

I'm currently trying to convert a JPEG image from the local java project directory to a byte array to send over a tcp connection. 我目前正在尝试将JPEG图像从本地Java项目目录转换为字节数组,以通过tcp连接发送。

This is currently how I'm converting my file to a byte array: 当前,这是我将文件转换为字节数组的方式:

BufferedImage imageBuff = ImageIO.read(new File("res/image.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(imageBuff, "JPEG", baos);
byte[] res = baos.toByteArray();
System.out.println(baos.toByteArray());

I can't seem to find a solid answer as to why this is happening, but every-time I convert it the data is not consistent: 我似乎无法找到关于为什么发生这种情况的可靠答案,但是每次我转换它时,数据都是不一致的:

System output: 系统输出:

[B@23f23303
[B@6299504b
[B@417f69df

What exactly is the byte array supposed to look like? 字节数组应该看起来到底是什么? It's clearly not working on the other side of the TCP connection for me unfortunately. 不幸的是,它显然无法在TCP连接的另一端工作。 I would think the output would have the same output each time it tries to convert it, no? 我认为每次尝试将其转换时,输出将具有相同的输出,不是吗?

You're calling toString on a byte[] . 您要在byte[]上调用toString Arrays don't override toString() , so you're seeing the implementation in Object : 数组不会覆盖toString() ,因此您可以Object看到实现

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. Object类的toString方法返回一个字符串,该字符串包括该对象是其实例的类的名称,符号字符“ @”以及该对象的哈希码的无符号十六进制表示形式。 In other words, this method returns a string equal to the value of: 换句话说,此方法返回的字符串等于:

 getClass().getName() + '@' + Integer.toHexString(hashCode()) 

So in other words, that has nothing to do with the data within the byte array. 因此,换句话说,这与字节数组中的数据无关。 Use Arrays.toString(byte[]) to get a string representation which actually looks reasonable - although you may find a hex conversion easier to read. 使用Arrays.toString(byte[])获得实际上看起来合理的字符串表示形式-尽管您可能会发现十六进制转换更容易阅读。

[B@23f23303 is the String representation of the array object, not the content of the array. [B@23f23303是数组对象的String表示形式,而不是数组的内容。

You can use System.out.println(Arrays.toString(baos.toByteArray())); 您可以使用System.out.println(Arrays.toString(baos.toByteArray()));

You're printing out information on the array itself (specifically, the array type [B for byte[] , and then the pointer to the array contents). 您正在打印关于数组本身的信息(特别是数组类型[Bbyte[] ,然后是指向数组内容的指针)。 You probably want to print Arrays.toString(res) . 您可能要打印Arrays.toString(res)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM