Guest User

Script for Google Images

a guest
Aug 8th, 2019
639
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.25 KB | None | 0 0
  1. import requests
  2. from PIL import Image
  3. from pathlib import Path
  4. import io
  5.  
  6. pathlist = Path(".\\assets\\").glob('**/*.png') # This gets all of the files ending in .png in the pack.
  7.  
  8. for file in pathlist: # Loops over the files
  9.     try: # This makes sure the program doesn't exit if there's an error
  10.            
  11.         print("Processing file:", file)
  12.        
  13.         toreplace=Image.open(".\\"+file) # Opens the iumage
  14.        
  15.         w, h = toreplace.size # Puts the width of the image into w and the height into h
  16.        
  17.         dividea = w/h # Works out the ratio of the height and width (aspect ratio)
  18.        
  19.         print("Old dimensions:",w,"by",h)
  20.        
  21.         toreplace.close() # Closes the file
  22.        
  23.         name=file.split('\\')[::-1][0].split('.')[0] # Splits the file path at every \ (although in Python there need to be two slashes to escape the slash), reverses the list with [::-1] and gets the first element, which is the last part of the path.
  24.        
  25.         print("Search term:", name.replace("_"," "), "-minecraft") # The Minecraft file names include underscores, so those are repla
  26.         response=requests.get('https://www.google.co.uk/search?q='+name.replace("_","+")+'+-minecraft&tbm=isch')
  27.         response=response.content.decode('utf-8', 'ignore')
  28.         print(response)
  29.         r=requests.get(response[response.find('src="',response.find('<img ')):].split('"')[1])
  30.         image = Image.open(io.BytesIO(r.content))
  31.         w, h = image.size
  32.         divide=w/h
  33.  
  34.         if dividea>divide:
  35.             newh=int(h/(dividea/divide))
  36.             box=(0, (h-newh)/2, w, h-((h-newh)/2))
  37.             image.crop(box).save(".\\"+file)
  38.             print("Saved with new dimensions:",w,"by",newh)
  39.         elif divide>dividea:
  40.             neww=int(w*(dividea/divide))
  41.             box=((w-neww)/2, 0, w-((w-neww)/2), h)
  42.             image.crop(box).save(".\\"+file)
  43.             print("Saved with new dimensions:",neww,"by",h)
  44.         elif divide == dividea:
  45.             image.save(".\\"+file)
  46.             print("Saved with new dimensions:",w,"by",h,"(not croppped)")
  47.         #open('google.jpeg', 'wb').write(r.content)
  48.         r=0
  49.         print("Done")
  50.         print()
  51.     except:
  52.         pass
  53.  
  54. print("Error list:",errors)
Add Comment
Please, Sign In to add comment