Python3 Transforms bytes Image to jpg Format

  • 2021-09-20 21:01:13
  • OfStack

Requirements:

The picture I crawled is in bytes format and needs to be saved directly to the local area.


import urllib3
import os
#PIL Image processing standard library 
from PIL import Image
from io import BytesIO
http = urllib3.PoolManager()
response = http.request('GET','f.hiphotos.baidu.com/image/pic/item/8d5494eef01f3a29f863534d9725bc315d607c8e.jpg')
result = response.data
# Will bytes The result is converted to a byte stream 
bytes_stream = BytesIO(result)
# Read to Picture 
roiimg = Image.open(bytes_stream)
# roiimg.show() # Show pictures 
#print(type(result))
#print(response.status)
imgByteArr = BytesIO() # Initialization 1 Null byte stream 
roiimg.save(imgByteArr,format('PNG'))  # Put our pictures as' PNG' Save to an empty byte stream 
imgByteArr = imgByteArr.getvalue() # Ignoring the pointer, get all the contents, and the type is defined io Flow transformation bytes . 
# dir_name = os.mkdir('baiduimg')
img_name = '1.jpg'
with open(os.path.join('baiduimg',img_name),'wb') as f:
 f.write(imgByteArr)

Supplement: python3 Saves the byte picture stream in the request to the local


def getImage():
 datestr = getTimeStamp()
 imageUrl = "xxxxxurl"
 verifyText = requests.get(imageUrl,verify=False).content
 print(verifyText)
 return verifyText 
def getTimeStamp():
 TimeStamp = str(time.time())
 TimeStamp = TimeStamp.replace(".", "")[0:13]
 return int(TimeStamp) 
def startEbLoginSystem(username,password): 
 for i in range(1,100):
  result = getImage()
  img_name = str(i)+'.jpg'
  path = "E:/yzmimages/" + img_name
  with open(path, 'wb') as f:
   f.write(result)

Method 1, using urllib. urlretrieve ()


import urllib 
#  Address of pictures on the network 
img_src = 'https://www.baidu.com/img/bd_logo1.png?where=super'
#  Download pictures locally 
urllib.urlretrieve(img_src,'D:/images/1.jpg')

Method 2, using PIL+requests:


import requests
from PIL import Image
from io import BytesIO 
response = requests.get(img_src)
image = Image.open(BytesIO(response.content))
image.save('D:/images/1.jpg')

Related articles: