Skip to content

Instantly share code, notes, and snippets.

@sungkhum
Last active February 13, 2022 23:38
Show Gist options
  • Save sungkhum/2978be9805190e19aaec54c133c62349 to your computer and use it in GitHub Desktop.
Save sungkhum/2978be9805190e19aaec54c133c62349 to your computer and use it in GitHub Desktop.
Script to download and convert NFT images from various sources
# Script to download and convert NFT images from varies sources
import os
import csv
import requests
import shutil
from PIL import Image
# Create images directory if it doesn't exist
if not os.path.exists('./images'):
os.mkdir('./images')
# CSV file name downloaded from Google Sheet Manifest
filename = "man.csv"
# Initializing the titles and rows list
fields = []
rows = []
# Reading csv file
with open(filename, 'r') as csvfile:
# Creating a csv reader object
csvreader = csv.reader(csvfile)
# Extracting field names through first row
fields = next(csvreader)
# Extracting each data row one by one
for row in csvreader:
rows.append(row)
for row in rows:
#Check that row has image url - if not, skip it
if row[4] == "" or row[4] == "N/A":
continue
#Item Number
item_num = row[0].zfill(3)
#Item Collector
collector = str(row[1]).strip()
#Image source
url = row[4]
res = requests.get(url, stream = True)
type = res.headers['content-type'].split("/")[-1]
file_name = item_num + "-" + collector + "." + type
# Save each image to images directory and convert to jpeg if it is a webp
try:
if res.status_code == 200:
if type == "webp":
im = Image.open(res.raw).convert("RGB")
im.save("./images/" + item_num + "-" + collector + ".jpeg", "JPEG", quality=100)
print('Image sucessfully Downloaded: ',file_name)
elif type == "jpeg" or type == "png" or type == "gif":
with open("./images/" + file_name,'wb') as f:
shutil.copyfileobj(res.raw, f)
print('Image sucessfully Downloaded: ',file_name)
else:
continue
else:
print('Image Couldn\'t be retrieved')
except Exception as e:
print(e)
continue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment