def compress_core(inputFile, outputFile, img_width): source = tinify.from_file(inputFile) if img_width is not -1: resized = source.resize(method = "scale", width = img_width) resized.to_file(outputFile) else: source.to_file(outputFile)
def tiny(self, f, cwd): try: tinify.from_file(f).to_file(f) append_compressed_file(f, cwd) print "tinypng " , f except AccountError, e: print "\nAccountError .. " + e.message, threading.currentThread().name self.accountManager.setAccountUnavailable(tinify.key) newKey = self.accountManager.getAvailableAccount() if (None == newKey): print "\nAll counts tried , finish" exit(0) return False else: tinify.key = newKey self.tiny(f, cwd)
def convert(image_file): done = False message = '' try: log('Compressing {} ...'.format(image_file)) source_file = tinify.from_file(image_file) source_file.to_file(image_file) except tinify.AccountError: message = 'ERROR: Verify your API key and your account limit.' except tinify.ClientError: message = 'ERROR: Problem with your request options or your image.' except tinify.ServerError: message = 'ERROR: Temporary issue on Tinify API.' except tinify.ConnectionError: message = 'ERROR: Network connection problem.' except Exception: message = 'ERROR: Something goes wrong and I do not know why.' else: done = True return done, message
def compress(source, target): filepath = dirpath + source cp_filepath = dirpath + target # print("[%s]" % os.path.split(source)[1]), data = tinify.from_file(filepath) data.to_file(cp_filepath) scale = get_file_size(cp_filepath) / get_file_size(filepath)
def tinifyPic(targetPath): for filename in os.listdir(targetPath): filepath = os.path.join(targetPath, filename) if os.path.isdir(filepath): tinifyPic(filepath) else: if isSupportedFile(filepath): print("Compressing: ", filepath) compressed_file = tinify.from_file(filepath) compressed_file.to_file(filepath)
def compress_core(inputFile, outputFile, img_width): # 判断图片大小,过小的文件不需要压缩 size = os.path.getsize(inputFile) if not limitSize(size): source = tinify.from_file(inputFile) if img_width is not None: resized = source.resize(method="scale", width=img_width) resized.to_file(outputFile) else: source.to_file(outputFile)
def compressimg(file): m5 = compressedfiles_data.get(file) print('before compress', m5) if m5 != None and filemd5(file) == m5: return sourcefile = tinify.from_file(file) sourcefile.to_file(file) m5 = filemd5(file) print(m5) compressedfiles_data[file] = m5 pass
def local_images(): for filename in images_list: try: input_path = str(input_dir + '\\' + filename) output_path = str(output_dir + '\\' + filename) source = tinify.from_file(input_path) source.to_file(output_path) print(filename + "转换完成") except tinify.Error: print(filename + "转换异常") pass
def minImg(src_dir, des_dir): ''' 将路径转换为绝对路径 ''' src_path = os.path.abspath(src_dir) des_path = os.path.abspath(des_dir) ''' 调用tinypng的api压缩目录下面的所有的png ''' tinify.key = KEY arr_png = glob.glob(f'{src_path}/*.png') for src in arr_png: basename = os.path.basename(src) source = tinify.from_file(src) source.to_file(f'{des_path}/{basename}')
def zip_pic(loc_p): o_img = loc_p + '.ori' # 原始未压缩的图片 try: if not os.path.isfile(o_img) or not imghdr.what(o_img): # 如果没有的话,那就需要进行压缩处理 print('压缩图片 :', loc_p) s_img = tinify.from_file(loc_p) s_img.to_file(loc_p + '.z') os.rename(loc_p, loc_p + '.ori') os.rename(loc_p + '.z', loc_p) except Exception as e: print('#warning: tinypng压缩出问题了,图片未压缩。')
def compress(self, image_path, replace=True, save_path=None): try: source = tinify.from_file(image_path) if replace: source.to_file(image_path) else: source.to_file(save_path) except tinify.errors.AccountError as err: print(err) except Exception as e: print(e)
def main(): errors = [] for abs_path in tqdm(list(get_file_paths(ASSETS_DIR))): logger.debug(abs_path.replace(ASSETS_DIR, './')) try: source = tinify.from_file(abs_path) source.to_file(abs_path) except Exception: logger.exception(f"Failed {abs_path.replace(ASSETS_DIR, './')}") errors.append(abs_path.replace(ASSETS_DIR, './')) for e in errors: print(e)
def compress(path): count = 0 for root, dirs, files in os.walk(path): for name in files: sizeKB = os.path.getsize(os.path.join(root, name)) / 1024 if sizeKB > 0 and (name.endswith(".png") or name.endswith(".jpg")): pngSrc = os.path.join(root, name) prGreen("compress++ %s" % (pngSrc)) source = tinify.from_file(pngSrc) source.to_file(pngSrc) count = count + 1 prLightPurple("压缩文件总数: %d" % count)
def tryOptimizeImg(fromName,toName): global keyList global keyListIndex try: source = tinify.from_file(fromName) source.to_file(toName) except tinify.AccountError, e: print "The error message is: %s" % e.message changeKeyRes = changeKey() if changeKeyRes != 0: return changeKeyRes return tryOptimizeImg(fromName,toName)
def compress_image(image_path, out_path, key): """ Compress the local image, return saved_image (local path) """ tinify.key = key try: source = tinify.from_file(image_path) source.to_file(out_path) return out_path except: traceback.print_exc() return False
def compress_and_save(abs_image_path, ct): only_image_path, image_info = os.path.split(abs_image_path) image_name, image_type = image_info.split('.') optimized_filename = f'{image_name}_optimized.{image_type}' if not os.path.isfile(optimized_filename): print("Image " + str(ct) + f': Compressing {image_name}') source = tinify.from_file(abs_image_path) print("Image " + str(ct) + f': Saving {optimized_filename}\n') source.to_file(optimized_filename)
def transform(source_path, target_parth): issuccess = True try: source = tinify.from_file(source_path) source.to_file(target_parth) print(f"transform success: {source_path} >> {target_parth} ") except Exception as e: issuccess = False print(f"transform fail: {e} ") finally: count_num = tinify.compression_count if tinify.compression_count else 0 return issuccess, count_num
def compress_core(inputFile, outputFile, img_width): try: source = tinify.from_file(inputFile) if img_width is not -1: resized = source.resize(method="scale", width=img_width) resized.to_file(outputFile) else: source.to_file(outputFile) return 0 except tinify.AccountError, e: print "the error msg is: %s" % e.message return 1
def compress_and_save(abs_image_path): (only_image_path, image_info) = os.path.split(abs_image_path) index = image_info.rindex('.') (image_name, image_type) = (image_info[:index], image_info[index + 1:]) optimized_filename = '{}_optimized.{}'.format(image_name, image_type) if not os.path.isfile(optimized_filename): source = tinify.from_file(abs_image_path) source.to_file(optimized_filename)
def post(self): article_form = ArticleForm() end_day = datetime.datetime.strptime(article_form.end_day.data, '%d-%m-%Y') if article_form.validate_on_submit(): current_user = User.query.filter_by(username=session.get('username')).first() f = article_form.article_image.data name = current_user.username + "__" + f.filename name = secure_filename(name) tinify.key = os.environ['TINIFY'] if request.headers['Host'] == '127.0.0.1:5000': tinify.from_file(f).to_file(os.path.join("./static/article_images/", name)) else: tinify.from_file(f).to_file(os.path.join(os.curdir, 'static', 'article_images', name)) new_article = Article(name=article_form.name.data, category=article_form.category.data, town=article_form.town.data, minimal_price=article_form.minimal_price.data, article_image=name, end_day=end_day, end_time=article_form.end_time.data, description=article_form.description.data, user_id=current_user.id) db.session.add(new_article) db.session.commit() return redirect(url_for('article', article_id=Article.query.order_by(Article.id.desc()).first().id)) else: return redirect(url_for('create_article'))
def CompressByTinypng(fromFile, out_dir): print("do CompressByTinypng..") try: for root, dir, files in os.walk(fromFile): print( "****************************************************************************************" ) print("root dir:" + root) print("dir:" + str(dir)) for file in files: current_file = os.path.join(root, file) dirName = os.path.basename(root) # 如果没有指定输出路径,则默认覆盖当前文件 if not out_dir: out_dir = fromFile targetDir = os.path.join(out_dir, dirName) if not os.path.exists(targetDir): os.makedirs(targetDir) # 如果是.9图片或者非图片文件不做处理,直接做拷贝 if not file.endswith(".9.png") and (file.endswith(".png") or file.endswith(".jpg")): print( "--------------------------------------------------------------------------------------------" ) # for key in tinify_keys: # 验证当前API key是否可以用,不可以用就切换下一个账号 tinify.key = tinify_keys[0] try: valid = tinify.validate() if valid: print("currrent file:" + current_file) origin_size = os.path.getsize(current_file) source = tinify.from_file(current_file) target_file = os.path.join(targetDir, file) source.to_file(target_file) compress_size = os.path.getsize(target_file) print( '%.2f' % ((origin_size - compress_size) / origin_size)) else: continue except Exception as e: # Something else went wrong, unrelated to the Tinify API. print("error while compressing png image:" + e.message) continue else: if not out_dir or out_dir == fromFile: continue shutil.copy(current_file, os.path.join(targetDir, file)) except Exception as e: print(e.message)
def compress_file(src, dst): if not os.path.exists(src): raise Exception('{} not exists'.format(src)) try: source = tinify.from_file(src) dir_name = os.path.dirname(dst) if not os.path.exists(dir_name): os.makedirs(dir_name) source.to_file(dst) except Exception: print('error.message: ', traceback.format_exc()) sys.exit(1)
def post(self): user = User.query.filter_by(username=session.get('username')).first() articles = Article.query.filter_by(user_id=user.id).all() file = request.files['fileToSave'] name = user.username + "_" + file.filename name = secure_filename(name) tinify.key = os.environ['TINIFY'] # Compression of image if request.headers['Host'] == '127.0.0.1:5000': tinify.from_file(file).to_file( os.path.join("./static/profile_images/", name)) else: tinify.from_file(file).to_file( os.path.join(os.curdir, 'static', 'profile_images', name)) user.profile_image = name db.session.commit() return redirect(url_for('profile', user=user, articles=articles))
def doProcessFile(srcDir, srcFile, dstDir, dstFile): if FLAG=="COMPRESS": print pCount, srcFile, getsize(srcFile), "=>" if not os.path.exists(dstDir): os.makedirs(dstDir) tinify.key = API_KEYS[pKeyIndex] tinify.from_file(srcFile).to_file(dstFile) print "=>", dstFile, getsize(dstFile), "[PROCESSED BY]", API_KEYS[pKeyIndex] elif FLAG=="COPY": print pCount, srcFile, getsize(srcFile), "=>" if not os.path.exists(dstDir): os.makedirs(dstDir) open(dstFile, "wb").write(open(srcFile, "rb").read()) print "=>", dstFile, getsize(dstFile), "[PROCESSED BY]", API_KEYS[pKeyIndex] else: print pCount, srcFile, getsize(srcFile), "[WILL BE PROCESSED]"
def compactar(): tinify.key = 'ddDiKafu3pSnpCHuqWObb7eoAfD6NZFW' print('Digite o endereço onde estão as imagens') diretorio = input('Digite o endereço: ') os.chdir(r'''{}'''.format(diretorio)) sequenciaInicial = 0 for arquivos in os.listdir(): if arquivos.endswith('.jpg') or arquivos.endswith( '.png'): #verifica se os arquivos são png ou jpg sequenciaInicial += 1 origem = tinify.from_file(arquivos) origem.to_file('minificadas-{}'.format(arquivos)) print('imagens Compactadas!!')
def make_sheet(matrix, sheet): path = 'static/data/flairs-' + sheet + '.png' # make new spritesheet size = (config_data['config']['flair_size'], config_data['config']['flair_size']) spritesheet_size = (len(matrix) * size[0], len(matrix) * size[1]) spritesheet = Image.new('RGBA', spritesheet_size) # make spritesheet image for row in matrix: for flair in row: if not flair: continue # open image if not os.path.isfile('static/data/flair_images/' + flair.short_name + '.png'): continue image = Image.open('static/data/flair_images/' + flair.short_name + '.png') image = image.convert('RGBA') image.thumbnail(size, Image.ANTIALIAS) imageSize = image.size # calculate row, column row = int(flair.row) - 1 col = int(flair.col) - 1 # calculate offset offsetX = ((size[0] - imageSize[0]) / 2) + col * size[0] offsetY = ((size[1] - imageSize[1]) / 2) + row * size[1] offset = (int(offsetX), int(offsetY)) # faded flair if not flair.is_active: image = fade_image(image) # insert image spritesheet.paste(image, offset) # output spritesheet spritesheet.save(path, quality=95, optimize=True) # optimize if os.path.getsize(path) > 500000: tinify.from_file(path).to_file(path) return spritesheet_size
def uploadfile(self): filename = tkinter.filedialog.askopenfilename( filetypes=[("JPEG File", "jpg"), ("PNG File", "png")]) if not filename: pass else: source = tinify.from_file(filename) strlen = len(filename) source.to_file(filename[0:strlen - 4] + "_tiny" + filename[strlen - 4:strlen]) self.cont.set(str(tinify.compression_count)) tkinter.messagebox.showinfo("Success", "File location: %s" % filename)
def png_compress(*path): """传入可变参数""" # 1.遍历文件夹下所有图片 s_paths = path[0] t_paths = path[1] i = 0 for s_path in s_paths: print(s_path) # print("s:", i, n) # print("n:", t_names[i]) source = tinify.from_file(s_path) source.to_file(t_paths[i]) i += 1 print("一共:" + str(len(s_paths)) + "; 完成:" + str(i))
def compress(src, dest): try: print '-------------------------------------------------' print 'compress', src source = tinify.from_file(src) print 'save to', dest source.to_file(dest) src_size = float(os.path.getsize(src)) dest_size = float(os.path.getsize(dest)) print 'compression ratio: %f' % (dest_size / src_size) except tinify.AccountError, e: print 'error', e global current_key_index if tinify.compression_count >= MAX_COMPRESSION_COUNT and init_tiny(current_key_index + 1): compress(src, dest)
def compress(params): global keys, key_index file_path = params['file_path'] result_path = params['result_path'] tinify.key = keys[key_index] source = tinify.from_file(file_path) source.to_file(result_path) global index, count lock.acquire() try: index += 1 current = index print(">{:3}/{}: {:50s}".format(current, count, params['file'])) finally: lock.release()
def compress(): if not os.path.exists(DIR + 'thumbs/'): os.makedirs(DIR + 'thumbs/') for i in range(1, countFiles() + 1): if os.path.isfile(DIR + "thumbs/" + str(i) + "_thumb" + EXT): print 'skipping ' + str(i) + EXT continue print 'compressing ' + str(i) + EXT source = tinify.from_file(DIR + str(i) + EXT) resized = source.resize(method="scale", width=350) resized.to_file(DIR + "thumbs/" + str(i) + "_thumb" + EXT) print 'done'
def conv(self, response): tmpIm = io.BytesIO(response.body) tmpImres = io.BytesIO() img = Image.open(io.BytesIO(response.body)) picfmt = img.format if picfmt != 'GIF': source = tinify.from_file(tmpIm) source.to_file(tmpImres) path = self.get_argument('url0') res = r.set(path, tmpImres.getvalue()) res = r.get(path) else: res = tmpIm.getvalue() self.set_header("Content-type", "image/" + picfmt) self.finish(res)
def compress_image_tinify(cls, image): """ uses tinify library to compress images pip install tinify returns the compressed image link with <image>_small.<ext> """ obj = cls() path = obj.BASE_DIR + image.url image_name_split = image.name.rsplit('.', 1) obj.image_name = image_name_split[0] + '_small.' + image_name_split[1] image_full_path = obj.MEDIA_ROOT + "/" + obj.image_name tinify.key = obj.TINIFY_API_KEY source = tinify.from_file(path) source.to_file(image_full_path) return obj.MEDIA_URL + obj.image_name
def compress(sourcepath,compresspath): files = os.listdir(sourcepath) for fi in files: fi_d = os.path.join(sourcepath, fi) if os.path.isdir(fi_d): compress_d = os.path.join(compresspath, fi) os.makedirs(compress_d) compress(fi_d,compress_d) else: #print os.path.join(compresspath,fi) path = os.path.join(sourcepath,fi) compress_path = os.path.join(compresspath,fi) if path.endswith('.png'): source = tinify.from_file(os.path.join(os.path.join(sourcepath, fi))) source.to_file(os.path.join(os.path.join(compresspath, fi)))
def upload_and_compress_images(paths, suffix): for index, path in enumerate(paths): name = os.path.basename(path) valid = check_img_is_valid(name) if valid: # do upload dz.determinate(False) progress = "(" + repr(index + 1) + "/" + repr(len(paths)) + ") " dz.begin(progress + "Compressing: " + name + " ...") source_img = tinify.from_file(path) if suffix: path = rename(path, suffix) source_img.to_file(path) compressed_name = os.path.basename(path) dz.finish("Image: " + name + " Compressed -> " + compressed_name) dz.url(False)
def tinify_pict(file): """ Tinify the giving file (replacing the original file) :param file: full path of the input/output file """ try: if os.path.isfile(file): import tinify tinify.key = settings.TINIFY_KEY try: source = tinify.from_file(file) source.to_file(file) except tinify.Error as e: Functions.logger.error("Unable to tinify the picture {0}: {1}".format(file, e.message)) else: Functions.logger.error("Unable to tinify the picture {0}: file not found".format(file)) except ImportError: Functions.logger.error("Unable to tinify the picture {0}: tinify module not installed".format(file))
def optimize(self): fh = storage.open(self.photo.name) from_file = tinify.from_file(fh) image_path = str(os.path.splitext(str(fh))[0]) extentions = str(os.path.splitext(str(fh))[1]) if self.auto_delete == True: from_file.to_file(image_path+"_optimized_"+extentions) #to optimize os.rename(str(self.photo.file.name), image_path+"_origin_"+extentions) #rename original photo os.rename(image_path+"_optimized_"+extentions, str(self.photo.file.name)) #rename optimized to original str(self.photo.file.name). os.remove(image_path+"_origin_"+extentions) #removing original photo else: from_file.to_file(image_path+"_optimized_"+extentions) #to optimize fh.close() return True
out_wdith = 300 out_height = 200 if not os.path.isdir(compress_dir): os.makedirs(compress_dir) if not os.path.isdir(thumbnail_dir): os.makedirs(thumbnail_dir) def resize(target,out_dir): """return: Image instance,or None if open fail. """ try: im = Image.open(target) except IOError: return None im = im.resize((out_wdith, out_height)) split_name = list(os.path.splitext(os.path.basename(target))) split_name.insert(-1, "_m") filename = "".join(split_name) im.save(os.path.join(out_dir,filename)) return im if __name__ == "__main__": for img in os.listdir(input_dir): print(img) tinify.from_file(os.path.join(input_dir, img)).to_file(os.path.join(compress_dir, img)) for img in os.listdir(compress_dir): resize(os.path.join(compress_dir, img), thumbnail_dir)
def compress(source, target): print "compressing image %s, save to %s" % (source, target) data = tinify.from_file(source) data.to_file(target) scale = get_file_size(target) / get_file_size(source) return (1 - scale) * 100
import time import tinify tinify.key = "oPSvm22wJdim-Q2b3XXfhh7RIXMp815S" compress = "compress/" original = "original/" from os import listdir from os.path import isfile, join onlyfiles = [f for f in listdir(original) if isfile(join(original, f)) and (f.endswith('.jpg') or f.endswith('.png'))] listaErro = [] for f in onlyfiles: continuar = True count = 0 while continuar and count < 5: try: print(f) source = tinify.from_file(original+f) source.to_file(compress+f) time.sleep(0.5) continuar = False except Exception as e: print(e) count +=1 time.sleep(2) if count == 5: listaErro.append(f) print(listaErro)
import sys import os ''' 参数配置很简单:https://tinypng.com/developers/reference/python 1:注册获取 key 填入 xxxx 中 2:pip install --upgrade tinify ''' # you need get yours msg here tinify.key = "xxxx" if __name__ == '__main__': # drop and handle imgs = sys.argv[1:] for img in imgs: source = tinify.from_file(img) # what size you nedd resized = source.resize( method="fit", width=200, height=300 ) # delete original img os.remove(img) # generate new img resized.to_file(img)
def compress_image(filename): tinify.key = "YOUR_API_KEY" source = tinify.from_file(filename) source.to_file(filename)
def cli(input): """ Tiny PNG CLI Tool \n takes single or multiple files and/or folders and minifies all png's and jpg's respectively """ def update_progress(progress): barLength = 10 status = "" if isinstance(progress, int): progress = float(progress) if progress >= 1: progress = 1 status = "✔ Done\r\n" block = int(round(barLength*progress)) text = "\rSatus: [{0}] {1}% {2}".format( "#"*block + "-"*(barLength-block), progress*100, status) sys.stdout.write(text) sys.stdout.flush() click.echo("") if not input: input = (".") for folder in input: if os.path.isdir(folder): for root, dirs, files in os.walk(folder): for file in files: if (file.lower().endswith(".png")) or (file.lower().endswith(".jpg")) or (file.lower().endswith(".jpeg")): click.echo("Image: %s" % file) update_progress(0) try: img_path = os.path.join(root, file) size = os.path.getsize(img_path) new_img = tinify.from_file(img_path) update_progress(.5) new_img.to_file(img_path) new_size = os.path.getsize(img_path) one = size / 100 saved = size - new_size percent = saved / one update_progress(1) click.echo("Saved: %s%% \n" % round(percent)) pass except(tinify.AccountError): click.echo("✘ Verify your API key and account limit. \n") except(tinify.ClientError): click.echo("✘ File could not be processed \n") pass except(tinify.ServerError): click.echo("✘ Temporary issue with the Tinify API. \n") pass except(tinify.ConnectionError): click.echo("✘ A network connection error occurred. \n") pass except(Exception): click.echo("✘ Something went wrong \n") pass elif os.path.isfile(folder): if (folder.lower().endswith(".png")) or (folder.lower().endswith(".jpg")) or (folder.lower().endswith(".jpeg")): click.echo(folder) update_progress(0) try: size = os.path.getsize(folder) new_img = tinify.from_file(folder) update_progress(.5) new_img.to_file(folder) new_size = os.path.getsize(folder) one = size / 100 saved = size - new_size percent = saved / one update_progress(1) click.echo("Saved: %s%% \n" % round(percent)) pass except(tinify.AccountError): click.echo("✘ Verify your API key and account limit. \n") except(tinify.ClientError): click.echo("✘ File could not be processed \n") pass except(tinify.ServerError): click.echo("✘ Temporary issue with the Tinify API. \n") pass except(tinify.ConnectionError): click.echo("✘ A network connection error occurred. \n") pass except(Exception): click.echo("✘ Something went wrong \n") pass else: click.echo("%s is not a file or folder.\n" % folder)
import tinify import os import os.path tinify.key = "your AppKey" # AppKey fromFilePath = "/Users/tangjr/Desktop/test1" # 源路径 toFilePath = "/Users/tangjr/Desktop/test2" # 输出路径 for root, dirs, files in os.walk(fromFilePath): for name in files: fileName, fileSuffix = os.path.splitext(name) if fileSuffix == '.png' or fileSuffix == '.jpg': toFullPath = toFilePath + root[len(fromFilePath):] toFullName = toFullPath + '/' + name if os.path.isdir(toFullPath): pass else: os.mkdir(toFullPath) source = tinify.from_file(root + '/' + name) source.to_file(toFullName) with open(toFullName, 'rb') as source: source_data = source.read() result_data = tinify.from_buffer(source_data).to_buffer()
#import the package and the assign the API-KEY import tinify tinify.key = "" #store the list of files in a list path_to_dir = os.getcwd() print(path_to_dir) files = os.listdir(path_to_dir) for file in files: if file == "tinifyrun.py": files.remove(file) else: file = sys.path[0] + '\\' + file #work on each file? print('Working...') for file in files: try: source = tinify.from_file(file) source.to_file(file) print(str(file) + ' DONE!') except: print(str(file) + ' not found...')
def compress_local_file(src_file, dest_file): try: source = tinify.from_file(src_file) source.to_file(dest_file) except Exception as e: logging.exception(e.message)
def test_should_return_source(self): httpretty.register_uri(httpretty.POST, 'https://api.tinify.com/shrink', location='https://api.tinify.com/some/location') tinify.key = 'valid' self.assertIsInstance(tinify.from_file(dummy_file), tinify.Source)
def compress_image(images): for image in images: source = tinify.from_file(image) source.to_file(image) print (image)