【问题标题】:Saving image file to a directory将图像文件保存到目录
【发布时间】:2022-01-16 19:36:40
【问题描述】:

由于库的限制,我正在接收一个图像作为字节,我想专门使用 open 命令来存储它。因此我无法使用像 opencv2 和 PIL 这样的库

mport numpy as np
import base64
import cv2
import io
from os.path import dirname, join
from com.chaquo.python import Python

def main(data):
    decoded_data = base64.b64decode(data)

    files_dir = str(Python.getPlatform().getApplication().getFilesDir())
    filename = join(dirname(files_dir), 'image.PNG')

    with open(filename, 'rb') as file:
        img = file.write(img)

    return img

我只想将图像文件保存到我所在的当前目录中。 目前,当我尝试我的代码时,它给了我以下错误:

com.chaquo.python.PyException: TypeError: write() argument must be str, not bytes

这需要我有一个字符串。我想知道如何将图像作为 .PNG 文件保存到目录中

【问题讨论】:

  • 你用opencv试过了吗,你可以用cv2.imwrite("img.png",img)代替file.write()。

标签: python python-3.x chaquopy


【解决方案1】:

试试:

out_file = open(filename, 'wb')
out_file.write(decoded_data)

【讨论】:

    【解决方案2】:

    使用with语句,处理后打开的文件会自动关闭

    with open(filename, 'wb') as file:
       file.write(decode_data)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 2015-12-05
      • 2015-07-04
      • 1970-01-01
      • 2013-03-05
      相关资源
      最近更新 更多