base64 URI到PNG-Python

时间:2015-07-14 15:11:17

标签: python image image-processing python-imaging-library reportlab

我正在尝试使用" ReportLab"通过Python生成PDF。我想为它添加一个图像。我必须使用的图像是PNG,但它具有以下格式:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA+gAAAH0CAYAAACuKActAAAgAEf (and it continues)

我不太清楚要做什么,首先我认为我需要将URI转换为图像,但我不知道该怎么做,然后使用类似的东西:

import Image
im = Image.open("infile.png")
im.save("outfile.jpg")

为了将.PNG转换为.JPG。有人能帮助我吗?

2 个答案:

答案 0 :(得分:5)

试试这个(修改:感谢njzk2指出要剪切标题):

import Image, io, base64

data = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="

im = Image.open(io.BytesIO(base64.b64decode(data.split(',')[1])))
im.save("image.jpg")

添加了一个真实的base64字符串,用于从here进行测试,这会产生一个小红点的图像:red dot

答案 1 :(得分:0)

from base64 import b64decode
from io import BytesIO
from PIL import Image

img_data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBwgHBgkIBwgKCgkLDRYPDQwMDRsUFRAWIB0iIiAdHx8kKDQsJCYxJx8fLT0tMTU3Ojo6Iys/RD84QzQ5OjcBCgoKDQwNGg8PGjclHyU3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3N//AABEIAG8AbwMBIgACEQEDEQH/xAAbAAACAwEBAQAAAAAAAAAAAAAFBgMEBwIBAP/EADwQAAIBAwIDBQYEBAQHAAAAAAECAwAEEQUSITFRBhNBYXEiMoGRofAUQlKxI8HR4SQzYvEHFRZDgpKi/8QAGAEAAwEBAAAAAAAAAAAAAAAAAQIDBAD/xAAfEQACAgMAAwEBAAAAAAAAAAAAAQIRAyExEiJ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zJE54ghgM/P+VP8F0COdZLpEzQ3sVwOUZ9rzFaQsDd/GYzhX/apZ41IvhfqGY5nkbZEpZv2q3baZISXIG9uZxV3SbVEjUAAUcjgULyrowBKYuHTZxzIIribTIpVxKoJPUUySKAKpyqM0XGgeVixPpQhBeE8PFSMg/OqJ0i0kfNvmyuOfeRcFb4cqaZ48rQjUIMoCuM5xjwNJw5q0f/2Q'

file_or_path = 'testing_image.jpg'
img_data += '=='

image = Image.open(BytesIO(b64decode(img_data.split(',')[1])))
image.save(file_or_path)