def shrunkImage(picture, filename): api_key = settings.TINYPNG_API_KEY if not api_key or not filename.endswith('.png'): return picture img_shrunked = NamedTemporaryFile(delete=False) shrink_info = shrink_file(picture.name, api_key=api_key, out_filepath=img_shrunked.name) img_shrunked.flush() return ImageFile(img_shrunked)
def shrunkImage(picture, filename): api_key = django_settings.TINYPNG_API_KEY if not api_key or not filename.endswith('.png'): return picture img_shrunked = NamedTemporaryFile(delete=False) shrink_info = shrink_file( picture.name, api_key=api_key, out_filepath=img_shrunked.name ) img_shrunked.flush() return ImageFile(img_shrunked)
from os import path import time import PIL from PIL import Image from tinypng import shrink_file start_time = time.time() KEY = 'XXXXXXXX' maxwidth = 1000 files = [f for f in os.listdir("XXXXXXXX")] for f in files: img = Image.open(f) if img.size[0] > maxwidth: print("Resizing %s" % f) percent = (maxwidth / float(img.size[0])) size = int(float(img.size[1] * float(percent))) img = img.resize((maxwidth, size), PIL.Image.ANTIALIAS) img.save(f) print("Optimizing %s" % f) shrink_info = shrink_file(f, KEY, f) img.save(f) print("Savings: {:.2%}".format(1 - shrink_info["output"]["ratio"])) print ("---%s minutes---" % ((time.time()-start_time)/60))
from bs4 import BeautifulSoup requests.packages.urllib3.disable_warnings() response=requests.get("your url here") soup = BeautifulSoup(response.text, 'html.parser') images = soup.find_all("img") counter = 1 api_key = "tinypng key here" for image in images: image_source = image.get("src") if image_source.endswith (".png"): response=requests.get(image_source, stream=True) image_name = "results/" + str(counter) + ".png" with open(image_name, "wb") as f: response.raw.decode_contet = True shutil.copyfileobj(response.raw, f) print image_source print image_name compressed_image_name = "compressed/"+ str(counter) + ".png" shrink_info = shrink_file( image_name, api_key=api_key, out_filepath=compressed_image_name) counter = counter + 1
directory = arg # We have to make sure that all of the arguments were passed. if directory == '': print('Invalid command line argument. -d [directory] is required') # If an argument is missing exit the application. exit() # Iterate through every image given in the directory argument and resize it. for image in os.listdir(directory): print('Processing image ' + image) imgPath = os.path.join(directory, image) # Open the image file. img = Image.open(imgPath) # Add watermark watermark = add_watermark(img, WATERMARK) # Resize the imae img = resize(watermark) # Save it back to disk. img.save(os.path.join(directory, image), quality=95) # Compress image using tinypng.com shrink_info = shrink_file(imgPath, api_key, imgPath) print("Savings: {:.2%}".format(1 - shrink_info["output"]["ratio"])) print('Batch processing complete.')