[109]图片和base64相互转化,图片转字节数组

图片和base64相互转化

# -*- coding: utf-8 -*-
import urllib2 as ulb
import base64


#用urllib2库链接网络图像
response=ulb.Request('http://s14.sinaimg.cn/mw690/5562b044tx6BkMgSR09ad&690')
fp=ulb.urlopen(response).read()        #打开网络图像文件句柄
#把图片转化为base64形式
a=base64.b64encode(fp)
print(a)

#把base64形式的图片转化为图片
imgData = base64.b64decode(a)
leniyimg = open('imgout.png','wb')
leniyimg.write(imgData)
leniyimg.close()

#转化本地图片为base64
f=open(r'c:\jb51.gif','rb') #二进制方式打开图文件
ls_f=base64.b64encode(f.read()) #读取文件内容,转换为base64编码
f.close()

图片转字节数组

# -*- coding:utf-8 -*-
from PIL import Image
import io


# 打开图片文件
image = Image.open('./img.png')
# 创建一个BytesIO对象
byte_stream = io.BytesIO()
# 保存图像到BytesIO中
image.save(byte_stream, format='PNG')
# 获取字节数组
bytes_array = byte_stream.getvalue()

print('bytes_array:',type(bytes_array))
print(bytes_array)

bytes_array_2 =bytearray(bytes_array)
print('bytes_array_2:',type(bytes_array_2))
print(bytes_array_2)

# =============================================================
from PIL import Image

# 打开图片文件
image = Image.open('image.jpg')
# 将图片读入内存
image_data = image.read()
# 转换为byte数组
byte_array = bytearray(image_data)
# 打印byte数组的长度
print(len(byte_array))

# =============================================================
with open("./img.png", "rb") as image:
    f = image.read()
    b = bytearray(f)
    print(type(b),b)

参考:https://www.python100.com/html/902EWP136AGW.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

周小董

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值