在新窗口中打开 base64 格式的图片

 const img = new Image();
 img.src = this.base64String;
 const newWin = window.open("", "_blank");
 newWin.document.write(img.outerHTML);
 newWin.document.title = "流程图"
 newWin.document.close();

原理是找到 window.open 返回的 window 对象并操作里面的 document 对象。img.outerHTML 是一串字符串形式的标签,说明可以在新窗口中操作 dom 元素。

stackoverflow链接

当你接收到一个通过Base64编码过的字符串表示的图片时,你需要将其解码回原始的二进制形式,并保存为图片文件。以下是详细步骤以及对应的Python代码示例来完成这一任务: ### 步骤说明 1. **导入所需库** 需要引入`base64`标准库来进行解码工作,同时如果想要显示或进一步处理这张图片的话还可以选择性地加载`PIL.Image`(来自Pillow包)或其他图像处理相关的库。 2. **准备Base64编码的字符串** 确保你已经有了代表一张图片Base64编码后的字符串。通常这样的字符串会以某种前缀开头(例如"data:image/png;base64,"),这是为了指明数据的内容类型及编码方式,但在实际操作中我们可以忽略这部分内容仅保留纯编码部分。 3. **去除Base64字符串中的非编码字符** 如果你的Base64字符串包含了前面提到的那种描述性的头部信息,则需要先把它们去掉,只留下真实的Base64编码部分。 4. **解码Base64字符串得到byte数组** 利用`base64.decodebytes()`或者`base64.b64decode()`函数可以将Base64编码转换回原本的字节流(byte array)。 5. **创建并保存图片文件** 把上述获得的字节数组写入一个新的文件即生成了相应的图片文件。 6. (可选)使用PIL展示图片 若你想立即查看结果而不必手动打开图片文件夹找到新建立好的文件,那么利用Pillow库可以帮助你在程序内部显示出该图片预览窗口。 ### 示例代码 这里给出一段简单的Python脚本来演示以上流程: ```python import base64 from PIL import Image from io import BytesIO def base64_to_image(base64_str, output_path=None): """ Convert a base64 string to an image file. :param base64_str: The input base64 encoded string representing the image content without prefix like 'data:image/jpeg;base64,'. :param output_path: Path where you want to save the decoded image. If None, it won't be saved but returned as PIL Image object instead. :return: A Pillow Image instance if no path provided for saving; otherwise returns nothing. """ # Remove any data URI scheme prefixes and decode clean_base64 = ','.join(base64_str.split(',')[1:]) if ',' in base64_str else base64_str img_bytes = base64.b64decode(clean_base64) # Create an IO stream from bytes byte_stream = BytesIO(img_bytes) # Open image using PIL/Pillow library img = Image.open(byte_stream).convert("RGB") if output_path: img.save(output_path) else: return img if __name__ == "__main__": # Example usage - replace this with your actual Base64-encoded string example_base64_jpg = "YOUR_BASE_64_ENCODED_IMAGE_STRING_HERE" result_img = base64_to_image(example_base64_jpg) result_img.show() # Display the resulting image directly # Or alternatively specify a filepath to write out the image there # base64_to_image(example_base64_jpg, "./output.jpg") ``` 这段脚本展示了怎样接收一个Base64编码过且可能含有MIME类型的头信息的字符串输入,对其进行清理和解码之后最终恢复出原图,并可以选择是否直接存储下来或是即时显示出来供开发者确认效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值