简体   繁体   English

解码(通过python类型转换将类型转换为字符串的Base64编码数据)转换为JAVA中的字节数组

[英]Decoding (Base64 encoded data with type conversion to string by python type casting) to byte array in JAVA

Hi I have some problem with type conversion. 嗨,我在类型转换方面遇到了一些问题。 First, with python3.7, I read data from imagefile and encoded it as base64 which is then bytes type. 首先,使用python3.7,我从imagefile中读取数据并将其编码为base64,然后是字节类型。 Then, I converted the bytes data to string with type conversion Python codes are below. 然后,我使用类型转换将字节数据转换为字符串,下面是Python代码。

f = open("monitor-1.png", "rb")
    data = f.read()
    encoded_string = str(base64.b64encode(data))

Then I sent it to java program using socket 然后我使用套接字将其发送到Java程序

To view image from java program, need to get byte array from the received data. 要从Java程序查看图像,需要从接收到的数据中获取字节数组。 But what should I do? 但是我该怎么办? Type conversion of python makes me confused.. python的类型转换使我感到困惑。

Maybe you should provide a snippet which can be used to reproduce your issue. 也许您应该提供一个可用于重现问题的代码段。

Following snippets are working 以下片段正在运行

import base64
f = open("monitor-1.png", "rb")
data = f.read()
encoded_string = str(base64.b64encode(data))
print(encoded_string)
f.close()

output 产量

b'iVBORw0KGgoAAAANSUhEUgAAAAIAAAABAQMAAADO7O3JAAAABlBMVEUAAAD///+l2Z/dAAAACklEQVQI12NoAAAAggCB3UNq9AAAAABJRU5ErkJggg=='

using the Base64 encoded string in Java jshell 在Java jshell使用Base64编码的字符串

jshell> byte[] bytes = Base64.getDecoder().decode("iVBORw0KGgoAAAANSUhEUgAAAAIAAAABAQMAAADO7O3JAAAABlBMVEUAAAD///+l2Z/dAAAACklEQVQI12NoAAAAggCB3UNq9AAAAABJRU5ErkJggg==")
bytes ==> byte[85] { -119, 80, 78, 71, 13, 10, 26, 10, 0, 0 ... 8, 68, -82, 66, 96, -126 }

jshell> Files.write(Paths.get("out.png"), bytes)
$2 ==> out.png

creates the file out.png 创建文件out.png

The file monitor-1.png and out.png are equal 文件monitor-1.pngout.png相等

$ md5sum monitor-1.png out.png 
49b0cecce3c3ce0966afd6c13b03a4b5  monitor-1.png
49b0cecce3c3ce0966afd6c13b03a4b5  out.png

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

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