【问题标题】:How to convert base64 string to image? [duplicate]如何将base64字符串转换为图像? [复制]
【发布时间】:2013-04-19 07:32:57
【问题描述】:

我正在将图像转换为 base64 字符串并将其从 android 设备发送到服务器。现在,我需要将该字符串改回图像并将其保存在数据库中。

有什么帮助吗?

【问题讨论】:

    标签: python base64


    【解决方案1】:

    这应该可以解决问题:

    image = open("image.png", "wb")
    image.write(base64string.decode('base64'))
    image.close()
    

    【讨论】:

    • 我用了这个方法。我喜欢它,因为它几乎是最简单且最接近我想要的结果 - 基本上是将字符串转换为磁盘上的图像文件。
    【解决方案2】:

    试试这个:

    import base64
    imgdata = base64.b64decode(imgstring)
    filename = 'some_image.jpg'  # I assume you have a way of picking unique filenames
    with open(filename, 'wb') as f:
        f.write(imgdata)
    # f gets closed when you exit the with statement
    # Now save the value of filename to your database
    

    【讨论】:

    • @rmunn...'wb' 指的是什么?!
    • @omarsafwany 意思是“写”和“写”stackoverflow.com/questions/2665866/…
    • 这为我创建了一个损坏的图像。
    • @JoshUsre - 如果您从这个示例代码中得到一个损坏的图像,可能是因为您正在解码的 base64 数据不是有效的 JPEG。它可能是一种不同类型的图像——例如 PNG 或 GIF——并且弄清楚你拥有什么样的图像超出了这个答案的范围。但是尝试为您拥有的图像类型创建一个具有正确扩展名的文件,看看是否有效。如果您仍然有问题,请提出一个真正的问题,而不是在两年前的帖子中放弃一句话评论。一个真正的问题会得到 FAR 更多的关注和更好的答案。
    • @JumabekAlikhanov - 您应该就此提出一个新问题。在我的答案中添加评论只会通知一个人(我),但是成千上万的人会看到一个新问题,他们可能会比我更了解 opencv。根据我对opencv文档的了解,我只知道如何从文件中打开图像,因此您的“不将其保存到任何文件”需要由其他人来回答。所以提出一个新问题并提供足够的细节,希望有人知道如何做你想做的事。
    【解决方案3】:

    只要使用.decode('base64')的方法就可以快乐起来。

    您还需要检测图像的 mimetype/扩展名,因为您可以正确保存它,在一个简短的示例中,您可以使用下面的代码进行 django 视图:

    def receive_image(req):
        image_filename = req.REQUEST["image_filename"] # A field from the Android device
        image_data = req.REQUEST["image_data"].decode("base64") # The data image
        handler = open(image_filename, "wb+")
        handler.write(image_data)
        handler.close()
    

    然后,根据需要使用保存的文件。

    简单。很简单。 ;)

    【讨论】:

      【解决方案4】:

      返回转换后的图像而不保存:

      from PIL import Image
      import cv2
      
      # Take in base64 string and return cv image
      def stringToRGB(base64_string):
          imgdata = base64.b64decode(str(base64_string))
          image = Image.open(io.BytesIO(imgdata))
          return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)
      

      【讨论】:

      • @AbhishekSharma 不鼓励仅链接 cmets,因为内容可能会更改或完全消失。请添加您的方法作为下次的答案。
      【解决方案5】:

      您可以尝试使用 open-cv 来保存文件,因为它有助于在内部进行图像类型转换。示例代码:

      import cv2
      import numpy as np
      
      def save(encoded_data, filename):
          nparr = np.fromstring(encoded_data.decode('base64'), np.uint8)
          img = cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR)
          return cv2.imwrite(filename, img)
      

      然后在你的代码中的某个地方你可以像这样使用它:

      save(base_64_string, 'testfile.png');
      save(base_64_string, 'testfile.jpg');
      save(base_64_string, 'testfile.bmp');
      

      【讨论】:

        猜你喜欢
        • 2013-02-15
        • 2016-07-29
        • 2011-06-17
        • 1970-01-01
        • 2018-09-07
        • 2014-07-21
        • 1970-01-01
        • 2020-12-22
        相关资源
        最近更新 更多