def exportPngThumbNail(self, coreFileName, exportDirectory, aprx, exportParams): # PNG Thumbnail. Need to create a larger image first. # If this isn't done, the thumbnail is pixelated amd doesn't look good pngTmpThumbNailFileName = "tmp-thumbnail.png" pngTmpThumbNailFileLocation = os.path.join(exportDirectory, pngTmpThumbNailFileName) Layout = aprx.listLayouts()[0] Layout.exportToPNG(pngTmpThumbNailFileLocation) pngThumbNailFileName = "thumbnail.png" pngThumbNailFileLocation = os.path.join(exportDirectory, pngThumbNailFileName) # Resize the thumbnail fd_img = open(pngTmpThumbNailFileLocation, 'r+b') img = Image.open(fd_img) img = resizeimage.resize('thumbnail', img, [140, 99]) img.save(pngThumbNailFileLocation, img.format) fd_img.close() # Remove the temporary larger thumbnail os.remove(pngTmpThumbNailFileLocation) return pngThumbNailFileLocation
def callback(ch, method, properties, body): print(" [x] %r" % body) number = redis.incr("counter") msg = json.loads(body) print(msg["url"]) print(msg["name"]) dir_path = '/tmp/' photo_filename = 'photo-' + str(number) + '.jpg' thumb_filename = 'thumb-' + str(number) + '.jpg' img_data = requests.get(msg["url"]) print(img_data) #print(img_data.content) #print(img_data.text) with open(dir_path + photo_filename, 'wb') as handler: handler.write(img_data.content) #urllib.urlretrieve(msg["url"], dir_path + photo_filename) with open(dir_path + photo_filename, 'r+b') as f: with Image.open(f) as image: thumb = resizeimage.resize('thumbnail', image, [200, 200]) thumb.save(dir_path + thumb_filename, image.format) response1 = send_file(dir_path + thumb_filename) response2 = send_file(dir_path + photo_filename) if response1["status"] and response2["status"]: redis.set('name:' + str(number), msg["name"]) redis.set('thumb:' + str(number), response1['id']) redis.set('full:' + str(number), response2['id']) redis.rpush('list-photos', str(number)) ch.basic_ack(delivery_tag=method.delivery_tag)
def resize_image(fpath, width, height=None, to=None, method="width"): """ resize an image file (dimensions) methods: width, height, cover """ with open(str(fpath), "rb") as fp: with PIL.Image.open(fp) as image: if method == "width": resized = resizeimage.resize(method, image, width) elif method == "height": resized = resizeimage.resize(method, image, height=height) else: resized = resizeimage.resize(method, image, [width, height]) kwargs = {"JPEG": {"quality": 100}} resized.save( str(to) if to is not None else fpath, image.format, **kwargs.get(image.format))
def create_image_set(path): """ Creates a set of images in different sizes for the passed image. The following images are created: Two square crops with sides of 75px and 150px, a thumbnail crops with dimensions of 100px*75px, seven original proportioned images with widths of 240px, 320px, 500px, 640px, 800px, 1024px, 1600px and 2048px, and finally the original image is saved with the same naming schema. The filenames are a UUID followed by an underscore and the suffix. Suffixes are the following: square, large_square, thumbnail, small, small_320, medium, medium_640, medium_800, large, large_1600, large_2048, original. The imageset is stored in the same directory as the passed image. The passed image musst have at least dimensions of 640px*427px. Otherwise a ImageSizeError is thrown. :param path: The path to the original image file. :return: A dictionary with suffixes as keys and paths as values. """ result = dict() unique_filename = str(uuid.uuid4()) with open(path, 'r+b') as f: with Image.open(f) as image: if image.size[0] < 600 or image.size[1] < 427: raise resizeimage.ImageSizeError('%s*%s' % (image.size[0], image.size[1]), '600*427') for size in sizes: new_path = '%s/%s_%s.jpg' % (os.path.split(path)[0], unique_filename, size[1]) try: resized_image = resizeimage.resize(size[0], image, size[2]) resized_image.save(new_path, 'jpeg') except resizeimage.ImageSizeError: pass else: result[size[1]] = new_path original_path = '%s/%s_original.jpg' % (os.path.split(path)[0], unique_filename) image.save(original_path, 'jpeg') result['original'] = original_path return result
def generate_thumbnail(image): t = img.open(image) thumbnail = resizeimage.resize('thumbnail', t, [250, 250]) t_io = BytesIO() thumbnail.save(t_io, 'JPEG', quality=60) new_thumbnail = File(t_io, name=image.name) return new_thumbnail
def resize_image(path): fd_img = open(path, 'r+b') img = Image.open(fd_img) img = resizeimage.resize('thumbnail', img, [300, 300]) img.save("images/xyz.jpg", img.format) img.save(path, img.format) fd_img.close()
def resize_image( src: Union[pathlib.Path, io.BytesIO], width: int, height: Optional[int] = None, dst: Optional[Union[pathlib.Path, io.BytesIO]] = None, method: Optional[str] = "width", allow_upscaling: Optional[bool] = True, **params: Optional[dict], ) -> None: """resize an image to requested dimensions methods: width, height, cover, thumbnail allow upscaling: upscale image first, preserving aspect ratio if required""" with PIL.Image.open(src) as image: # preserve image format as resize() does not transmit it into new object image_format = image.format image_mode = image.mode # upscale if required preserving the aspect ratio if allow_upscaling: height_width_ratio = float(image.size[1]) / float(image.size[0]) if image.size[0] < width: image = image.resize((width, int(width * height_width_ratio))) if height and image.size[1] < height: image = image.resize( (int(height / height_width_ratio), height)) # resize using the requested method if method == "width": resized = resizeimage.resize(method, image, width) elif method == "height": resized = resizeimage.resize(method, image, height) else: resized = resizeimage.resize(method, image, [width, height]) # remove alpha layer if not supported and added during resizing if resized.mode == "RGBA" and image_format in ALPHA_NOT_SUPPORTED: resized = resized.convert(image_mode) # reset src if it's a byte stream and should be resized in-place if dst is None and isinstance(src, io.BytesIO): src.seek(0) save_image(resized, dst if dst is not None else src, image_format, **params)
def photo_record(bot: telegram.Bot, update: telegram.Update): if update.message.caption and update.message.caption == "tags": photo_id = update.message.photo[0].file_id image_io = BytesIO() bot.get_file(photo_id).download(out=image_io) image = Image.open(image_io) image = resize(image, std_size) image = image.convert("RGB") img_vec = img2arr(image) tags = classifier.predict_tags(numpy.array([img_vec]))[0] update.message.reply_text("tags:" + ','.join(tags))
def resize_image(filename, new_filename, method, size): """ Opens file 'filename'. Resized with 'method' to 'size' and saves as 'new_filename'. Bad file or filename raises IOError Wrong image size raises ImageSizeError """ with open(filename, 'r+b') as f: with Image.open(f) as image: resized = resizeimage.resize(method, image, size) resized.save(new_filename, image.format)
def export(subdir, filename, size): ensure_dir(subdir) fd_img = open(__image__, 'r') img = Image.open(fd_img) img = resizeimage.resize('contain', img, [size, size]) img.save(path.join(subdir, filename), img.format) fd_img.close()
def create_thumbnails(): images = [] images += [each for each in os.listdir('.') if each.endswith(('.jpg', '.jpeg', '.png', '.JPG'))] thumbnail_folder_name = "thumbnails" if not os.path.exists(thumbnail_folder_name): os.makedirs(thumbnail_folder_name) for image in images: fd_img = open(image, 'r') img = Image.open(fd_img) img = resizeimage.resize('thumbnail', img, [160, 160]) img.save('%s/thumbnail_%s' %(thumbnail_folder_name, image), img.format) fd_img.close()
def display_image(self, master): self.image_path = self.app.get_image_path(self) image = Image.open(self.image_path) image = resizeimage.resize('thumbnail', image, [320, 200]) photo = ImageTk.PhotoImage(image) thumbnail = Label(master, image=photo, height=320, width=200, bg='black') thumbnail.image = photo thumbnail.place(x=300, y=120) self.display_geoTag(master)
def resize_image(filename, new_filename, method, size): """Resize an image according to a method and size and store it :param filename: file to resize :param new_filename: Name of the resized file :param method: resize method to use :param size: :raise IOError: Bad file or filename :raise ImageSizeError: Wrong image size """ with open(filename, 'r+b') as f: with Image.open(f) as image: resized = resizeimage.resize(method, image, size) resized.save(new_filename, image.format)
def preprocess2(filename): fd_img = open(filename) img = Image.open(fd_img) img = resizeimage.resize('thumbnail', img, [512, 512]) res = img = np.array(img) for k in range(len(img)): for j in range(len(img[0])): for i in range(3): s = sum(img[k][j]) if s == 0: continue img[k][j][i] = 255 * img[k][j][i]/s img = color.rgb2gray(img) img = exposure.equalize_adapthist(img, clip_limit=0.03) #img = exposure.equalize_hist(img) top = 0 bot = len(img) #print top,bot for i in range(len(img)): s = np.average(img[i,:]) #print s if s > 0.1 and top == 0: top = i if s < 0.1 and top != 0 and bot == len(img[0]): bot = i-1 #print "left:",top #print "right:",bot left = 0 right = len(img[0]) #print left,right for i in range(len(img[0])): s = np.average(img[:,i]) #print s if s > 0.15 and left == 0: left = i if s < 0.15 and left != 0 and right == len(img[0]): right = i-1 #print "left:",left #print "right:",right #img = img[top:bot,left:right] img = adapt(img) img = resize(img,(256,256)) return blob_dog(img, min_sigma = 7, max_sigma=23, threshold=0.2, overlap=0.5)
def __recognize(self, img): img = resizeimage.resize('thumbnail', img, [28, 28]) arr = np.array(img) print(arr) arr = arr.reshape(1, 784) print(arr.shape) arr = np.repeat(arr, 3, axis=1) print(arr.shape) to_recognize = arr.reshape(1, 28, 28, 3) print(to_recognize.shape) arch = resnet34 stats = (np.array([0.4914, 0.48216, 0.44653]), np.array([0.24703, 0.24349, 0.26159])) tfms = tfms_from_stats(stats, self.img_size, aug_tfms=[RandomFlip()], pad=self.img_size // 8) x_template = np.zeros((1, 28, 28, 3)) y_template = np.zeros((1)) data = ImageClassifierData.from_arrays(self.work_path, trn=(x_template, y_template), val=(x_template, y_template), test=to_recognize, tfms=tfms) data.trn_ds.c = 10 # num of classes learn = ConvLearner.pretrained(arch, data, precompute=False) learn.load(self.work_path / '28_all') print('loaded') log_preds, y = learn.TTA( is_test=True) # use test dataset rather than validation dataset probs = np.mean(np.exp(log_preds), 0) actual = probs[0].argmax() print('recognition result =', actual) return actual
def resize_file(in_file, out_file, size, filenamefile): with open(in_file, 'r+b') as fd: im = Image.open(fd) image = resizeimage.resize('contain', im, size) pix = image.load() out = [] for (a, b, c, d) in list(image.getdata()): out = out + [a] + [b] + [c] + [d] out = map(str, out) if len(out) == size[0] * size[1] * 4: fout = open(out_file, 'a') fout.write(','.join(out) + '\n') else: fout = open(out_file, 'a') fout.write(','.join(out) + '\n') print "Check", in_file, "- It doesn't seem to be in CYMK format." fout.close() filenamef = open(filenamefile, 'a') filenamef.write(in_file + '\n') filenamef.close()
def preprocess2(filename): fd_img = open(filename) img = Image.open(fd_img) img = resizeimage.resize('thumbnail', img, [512, 512]) img = np.array(img) for k in range(len(img)): for j in range(len(img[0])): s = np.sum(img[k][j]) for i in range(3): if s == 0: continue img[k,j,i] = 255 * img[k,j,i]/s #return img img = color.rgb2gray(img) img = exposure.equalize_adapthist(img, clip_limit=0.03) img = adapt(img) img = resize(img,(256,256)) #spoints = lbp(img,15,8) fd, hog_image = hog(img, orientations=8, pixels_per_cell=(16, 16),cells_per_block=(1, 1), visualise=True) print fd return img
def resize_images(): file_list = os.listdir(app.root_path + '/img/') # For each image set it equal to the height and width using behavior like background-size: cover for file in file_list: basewidth = IMAGE_WIDTH img = Image.open(app.root_path + '/img/' + file) wpercent = (basewidth / float(img.size[0])) hsize = int((float(img.size[1]) * float(wpercent))) img = img.resize((basewidth, hsize), Image.ANTIALIAS) img = resizeimage.resize('cover', img, [IMAGE_WIDTH, IMAGE_HEIGHT]) try: os.makedirs(os.path.dirname(app.root_path + '/img/' + file), exist_ok=True) img.save(app.root_path + '/img/' + file, img.format) except: print('Could not save file') img.close() return
def optimize_image(self, image_data, output_size, resize_method, quality): """Optimize an image that has not been saved to a file.""" img = Image.open(image_data) if img.format not in self.optimized_file_formats: raise ValidationError({self.name: [_('Image format unsupported')]}) # GIF files needs strict size validation if img.format == 'GIF' and output_size and output_size != (img.width, img.height): raise ValidationError({self.name: [_('GIF image size unsupported')]}) # Check if is a supported format for optimization if img.format not in ['JPEG', 'PNG']: return image_data # If output_size content 0. if output_size and output_size[0] == 0: output_size = (img.width, output_size[1]) elif output_size and output_size[1] == 0: output_size = (output_size[0], img.height) # If output_size is set, resize the image with the selected resize_method. if output_size and output_size != (img.width, img.height): output_image = resizeimage.resize(resize_method, img, output_size) else: output_image = img # If the file extension is JPEG, convert the output_image to RGB if img.format == 'JPEG': output_image = output_image.convert('RGB') bytes_io = BytesIO() output_image.save(bytes_io, format=img.format, optimize=True, quality=quality) image_data.seek(0) image_data.file.write(bytes_io.getvalue()) image_data.file.truncate() return image_data
def get_avatar(md5): image = None # fetch image from redis or ldap if redis_store.exists(md5): user_dn = redis_store.get(md5) dn_sha1hex = hashlib.sha1(user_dn).hexdigest() if redis_store.exists(dn_sha1hex): image = _get_image_from_redis(dn_sha1hex) else: image = _get_image_from_ldap(user_dn, dn_sha1hex) # cache image on redis if current_app.config.get('AVATAR_CACHE', True): img_ttl = current_app.config['AVATAR_TTL'] redis_store.hset(dn_sha1hex, 'raw', str(image)) redis_store.expire(dn_sha1hex, img_ttl) image = Image.open(StringIO(image)) else: current_app.logger.warning('MD5 {0} not in redis.'.format(md5)) # default image if image is None: default_args = ['d', 'default'] default_image = current_app.config['AVATAR_DEFAULT_IMAGE'] keyword = _get_argval_from_request(default_args, default_image) static_images = current_app.config['AVATAR_STATIC_IMAGES'] if keyword not in static_images or keyword == '404': abort(404) image = Image.open( url_for('static', filename=os.path.join('img', static_images[keyword])) ) # sizes default_size = int(current_app.config['AVATAR_DEFAULT_SIZE']) size = _get_argval_from_request(['s', 'size'], default_size) width = _get_argval_from_request(['w', 'width'], default_size) height = _get_argval_from_request(['h', 'height'], default_size) # resize methods default_method = current_app.config['AVATAR_DEFAULT_METHOD'] resize_method = _get_argval_from_request(['m', 'method'], default_method) if resize_method not in RESIZE_METHODS: resize_method = default_method if width == default_size and size != default_size: width = size if height == default_size and size != default_size: height = size if resize_method in ['crop', 'cover', 'contain', 'thumbnail']: size = (_max_size(width), _max_size(height)) elif resize_method == 'width': size = _max_size(width) elif resize_method == 'height': size = _max_size(height) buffer_image = StringIO() try: resized_image = resizeimage.resize(resize_method, image, size) except resizeimage.ImageSizeError: if resize_method in ['width', 'height']: resized_image = image else: size = image.height if image.height > image.width else image.width size = (size, size) resized_image = resizeimage.resize(resize_method, image, size) resized_image.save(buffer_image, image.format, quality=95) buffer_image.seek(0) mimetypes.init() mimetype = mimetypes.types_map['.' + image.format.lower()] return send_file(buffer_image, mimetype=mimetype)
fd_img = open('/home/antz/0Python/image/File.jpg', 'r') img = Image.open(fd_img) img = resizeimage.resize_thumbnail(img, [200, 200]) img.save('test-image-thumbnail.jpeg', img.format) fd_img.close() ########################################################## # Resize Image with the specified method : # ‘crop’, ‘cover’, ‘contain’, ‘width’, ‘height’ or ‘thumbnail’. ########################################################## from PIL import Image from resizeimage import resizeimage fd_img = open('/home/antz/0Python/image/File.jpg', 'r') img = Image.open(fd_img) img = resizeimage.resize('thumbnail', img, [200, 200]) img.save('test-image-thumbnail.jpeg', img.format) fd_img.close() ######## # Tests: ######## pip install -r requirements.dev.txt pip install -e . python setup.py test
##################################################################################### ###############################Debut Repres 3d####################################""" ####################image 1#############################################" depth_map = cv2.imread('dispartitytest.png') depth_map = cv2.cvtColor(depth_map, cv2.COLOR_BGR2GRAY) depth_map = np.array(depth_map) height = np.size(depth_map, 0) width = np.size(depth_map, 1) img = cv2.imread('imagetest.jpg') img = img[:, :, 1] img = im.fromarray(img) img = resizeimage.resize('contain', img, [128, 160]) #img.resize([height, width],im.ANTIALIAS) img = np.array(img) img = img[:, :, 0] def homogenous(u): v = [u[0], u[1], 1] return (v) def vortex(K, depth_map, img): vortex = list() invK = np.linalg.inv(K) for i in range(np.size(img, 0)): for j in range(np.size(img, 1)):
from skimage.transform import rescale,resize from skimage import io import numpy as np from PIL import Image from skimage import exposure,color from resizeimage import resizeimage from skimage.feature import hog from resize import adapt,preprocess2 # Blot detection from Skimage # Try this feature with sample picture fd_img = open('../sample/16_right.jpeg') img = Image.open(fd_img) img2 = resizeimage.resize('thumbnail', img, [256, 256]) #img = resizeimage.resize_cover(img, [256, 256]) img = np.array(img2)#data.hubble_deep_field()[0:500, 0:500] for k in range(len(img)): for j in range(len(img[0])): for i in range(3): s = sum(img[k][j]) if s == 0: continue img[k][j][i] = 255 * img[k][j][i]/s image_gray = rgb2gray(img) #image_gray = exposure.equalize_hist(image_gray) image_gray = exposure.equalize_adapthist(image_gray, clip_limit=0.02) blobs_log = blob_log(image_gray, max_sigma=10, num_sigma=10, threshold=.1)
d = {} for i in range(bot,top+1): d[str(i)] = 0 for a in blobs_dog: x,y,r = a d[str(int(r))] += 1 res = [] for i in range(bot,top+1): res.append(d[str(i)]) return res #images = sc.binaryFiles("hdfs:///user/hduser/train/"+filename+'.jpeg') #images = sc.binaryFiles("hdfs:///user/slic/train_ext/part-12*,hdfs:///user/slic/train_ext/part-15*,hdfs:///user/slic/train_ext/part-02*,hdfs:///user/slic/train_ext/part-05*") image_to_array = lambda rawdata: normalize(np.asarray(resizeimage.resize('thumbnail',Image.open(StringIO(rawdata)), [265, 256]))) adj = lambda rawdata: resize(adapt(exposure.equalize_adapthist(color.rgb2gray((rawdata)), clip_limit=0.03)),(128,128)) #adj = lambda rawdata: resize((exposure.equalize_adapthist(color.rgb2gray(rawdata), clip_limit=0.03)),(100,100)) ext = lambda rawdata: hog(rawdata, orientations=8, pixels_per_cell=(16, 16),cells_per_block=(1, 1), visualise=True)[0] img = images.values().map(image_to_array).map(adj).map(ext) def third(x): s = LabeledPoint(float(c[x[0].split('/')[-1].split('.')[0]]), ext((adj(image_to_array(x[1]))))) return s c = getBag('/home/xhan/trainLabels.csv') filename = getFile(c,"hdfs:///user/hduser/train/") images = sc.binaryFiles(filename) data = images.map(third) data.saveAsTextFile("hdfs:///user/slic/output")
def get_avatar(md5): image = None # fetch image from redis or ldap if redis_store.exists(md5): user_dn = redis_store.get(md5) dn_sha1hex = hashlib.sha1(user_dn).hexdigest() if redis_store.exists(dn_sha1hex): image = _get_image_from_redis(dn_sha1hex) else: image = _get_image_from_ldap(user_dn, dn_sha1hex) # cache image on redis if current_app.config.get('AVATAR_CACHE', True): img_ttl = current_app.config['AVATAR_TTL'] redis_store.hset(dn_sha1hex, 'raw', str(image)) redis_store.expire(dn_sha1hex, img_ttl) image = Image.open(StringIO(image)) else: current_app.logger.warning('MD5 {0} not in redis.'.format(md5)) # default image if image is None: default_args = ['d', 'default'] default_image = current_app.config['AVATAR_DEFAULT_IMAGE'] keyword = _get_argval_from_request(default_args, default_image) static_images = current_app.config['AVATAR_STATIC_IMAGES'] static_path = current_app.config['AVATAR_STATIC'] if keyword not in static_images or keyword == '404': abort(404) image = Image.open(os.path.join(static_path, static_images[keyword])) # sizes default_size = int(current_app.config['AVATAR_DEFAULT_SIZE']) size = _get_argval_from_request(['s', 'size'], default_size) width = _get_argval_from_request(['w', 'width'], default_size) height = _get_argval_from_request(['h', 'height'], default_size) # resize methods default_method = current_app.config['AVATAR_DEFAULT_METHOD'] resize_method = _get_argval_from_request(['m', 'method'], default_method) if resize_method not in RESIZE_METHODS: resize_method = default_method if width == default_size and size != default_size: width = size if height == default_size and size != default_size: height = size if resize_method in ['crop', 'cover', 'contain', 'thumbnail']: size = (_max_size(width), _max_size(height)) elif resize_method == 'width': size = _max_size(width) elif resize_method == 'height': size = _max_size(height) buffer_image = StringIO() try: resized_image = resizeimage.resize(resize_method, image, size) except resizeimage.ImageSizeError: if resize_method in ['width', 'height']: resized_image = image else: size = image.height if image.height > image.width else image.width size = (size, size) resized_image = resizeimage.resize(resize_method, image, size) resized_image.save(buffer_image, image.format, quality=95) buffer_image.seek(0) mimetypes.init() mimetype = mimetypes.types_map['.' + image.format.lower()] return send_file(buffer_image, mimetype=mimetype)
from PIL import Image from resizeimage import resizeimage with open('../upload/30-03-2019-1553931573.jpg', 'r+b') as f: with Image.open(f) as image: cover = resizeimage.resize_cover(image, [200, 100]) cover.save('test-image-cover.jpeg', image.format) fd_img = open('../upload/30-03-2019-1553931573.jpg', 'r+b') img = Image.open(fd_img) img = resizeimage.resize_width(img, 200) img.save('test-image-width.jpeg', img.format) fd_img.close() from PIL import Image from resizeimage import resizeimage fd_img = open('../upload/30-03-2019-1553931573.jpg', 'r+b') img = Image.open(fd_img) img = resizeimage.resize('thumbnail', img, [300, 300]) img.save('test-image-thumbnail.jpeg', img.format) fd_img.close()
def get_avatar(md5): image = None # fetch image from redis or ldap if redis_store.exists(md5): user_dn = redis_store.get(md5) dn_sha1hex = hashlib.sha1(user_dn).hexdigest() try: if redis_store.exists(dn_sha1hex): image = _get_image_from_redis(dn_sha1hex) else: image = _get_image_from_ldap(user_dn.decode(), dn_sha1hex) # cache image on redis if current_app.config.get("AVATAR_CACHE", True): img_ttl = current_app.config["AVATAR_TTL"] redis_store.hset(dn_sha1hex, "raw", image) redis_store.expire(dn_sha1hex, img_ttl) image = Image.open(BytesIO(image)) except OSError: current_app.logger.warning( "Cannot read image of {0}".format(user_dn)) else: current_app.logger.warning("MD5 {0} not in redis.".format(md5)) # default image if image is None: default_args = ["d", "default"] default_image = current_app.config["AVATAR_DEFAULT_IMAGE"] keyword = _get_argval_from_request(default_args, default_image) static_images = current_app.config["AVATAR_STATIC_IMAGES"] static_path = current_app.config["AVATAR_STATIC"] identicon_enable = current_app.config["AVATAR_IDENTICON_ENABLE"] identicon_cache = current_app.config["AVATAR_IDENTICON_CACHE"] if identicon_enable == "true" and keyword == "identicon": redis_key = md5 + "-identicon" # fetch image from redis if identicon_cache == "true" and redis_store.exists(redis_key): image = _get_image_from_redis(redis_key) else: generator = Generator( int(current_app.config["AVATAR_IDENTICON_SIZE"]), int(current_app.config["AVATAR_IDENTICON_SIZE"]), foreground=current_app. config["AVATAR_IDENTICON_FOREGROUND"], background=current_app. config["AVATAR_IDENTICON_BACKGROUND"], ) image = generator.generate( md5, int(current_app.config["AVATAR_MAX_SIZE"]), int(current_app.config["AVATAR_MAX_SIZE"]), padding=(0, -4, 0, -4), ) # cache image on redis if identicon_cache == "true": img_ttl = current_app.config["AVATAR_TTL"] redis_store.hset(redis_key, "raw", image) redis_store.expire(redis_key, img_ttl) image = Image.open(BytesIO(image)) elif keyword not in static_images or keyword == "404": abort(404) else: image = Image.open( os.path.join(static_path, static_images[keyword])) # sizes default_size = int(current_app.config["AVATAR_DEFAULT_SIZE"]) size = _get_argval_from_request(["s", "size"], default_size) width = _get_argval_from_request(["w", "width"], default_size) height = _get_argval_from_request(["h", "height"], default_size) # resize methods default_method = current_app.config["AVATAR_DEFAULT_METHOD"] resize_method = _get_argval_from_request(["m", "method"], default_method) if resize_method not in RESIZE_METHODS: resize_method = default_method if width == default_size and size != default_size: width = size if height == default_size and size != default_size: height = size if resize_method in ["crop", "cover", "contain", "thumbnail"]: size = (_max_size(width), _max_size(height)) elif resize_method == "width": size = _max_size(width) elif resize_method == "height": size = _max_size(height) buffer_image = BytesIO() try: resized_image = resizeimage.resize(resize_method, image, size) except resizeimage.ImageSizeError: if resize_method in ["width", "height"]: resized_image = image else: size = image.height if image.height > image.width else image.width size = (size, size) resized_image = resizeimage.resize(resize_method, image, size) resized_image.save(buffer_image, image.format, quality=95) buffer_image.seek(0) mimetypes.init() mimetype = mimetypes.types_map["." + image.format.lower()] return send_file(buffer_image, mimetype=mimetype)
def get_avatar(md5): image = None # fetch image from redis or ldap if redis_store.exists(md5): user_dn = redis_store.get(md5) dn_sha1hex = hashlib.sha1(user_dn).hexdigest() try: if redis_store.exists(dn_sha1hex): image = _get_image_from_redis(dn_sha1hex) else: image = _get_image_from_ldap(user_dn.decode(), dn_sha1hex) # cache image on redis if current_app.config.get('AVATAR_CACHE', True): img_ttl = current_app.config['AVATAR_TTL'] redis_store.hset(dn_sha1hex, 'raw', image) redis_store.expire(dn_sha1hex, img_ttl) image = Image.open(BytesIO(image)) except OSError: current_app.logger.warning( 'Cannot read image of {0}'.format(user_dn)) else: current_app.logger.warning('MD5 {0} not in redis.'.format(md5)) # default image if image is None: default_args = ['d', 'default'] default_image = current_app.config['AVATAR_DEFAULT_IMAGE'] keyword = _get_argval_from_request(default_args, default_image) static_images = current_app.config['AVATAR_STATIC_IMAGES'] static_path = current_app.config['AVATAR_STATIC'] identicon_enable = current_app.config['AVATAR_IDENTICON_ENABLE'] identicon_cache = current_app.config['AVATAR_IDENTICON_CACHE'] if identicon_enable == 'true' and keyword == 'identicon': redis_key = md5 + "-identicon" # fetch image from redis if identicon_cache == 'true' and redis_store.exists(redis_key): image = _get_image_from_redis(redis_key) else: generator = Generator( int(current_app.config['AVATAR_IDENTICON_SIZE']), int(current_app.config['AVATAR_IDENTICON_SIZE']), foreground=current_app. config['AVATAR_IDENTICON_FOREGROUND'], background=current_app. config['AVATAR_IDENTICON_BACKGROUND']) image = generator.generate( md5, int(current_app.config['AVATAR_MAX_SIZE']), int(current_app.config['AVATAR_MAX_SIZE']), padding=(0, -4, 0, -4)) # cache image on redis if identicon_cache == 'true': img_ttl = current_app.config['AVATAR_TTL'] redis_store.hset(redis_key, 'raw', image) redis_store.expire(redis_key, img_ttl) image = Image.open(BytesIO(image)) elif keyword not in static_images or keyword == '404': abort(404) else: image = Image.open( os.path.join(static_path, static_images[keyword])) # sizes default_size = int(current_app.config['AVATAR_DEFAULT_SIZE']) size = _get_argval_from_request(['s', 'size'], default_size) width = _get_argval_from_request(['w', 'width'], default_size) height = _get_argval_from_request(['h', 'height'], default_size) # resize methods default_method = current_app.config['AVATAR_DEFAULT_METHOD'] resize_method = _get_argval_from_request(['m', 'method'], default_method) if resize_method not in RESIZE_METHODS: resize_method = default_method if width == default_size and size != default_size: width = size if height == default_size and size != default_size: height = size if resize_method in ['crop', 'cover', 'contain', 'thumbnail']: size = (_max_size(width), _max_size(height)) elif resize_method == 'width': size = _max_size(width) elif resize_method == 'height': size = _max_size(height) buffer_image = BytesIO() try: resized_image = resizeimage.resize(resize_method, image, size) except resizeimage.ImageSizeError: if resize_method in ['width', 'height']: resized_image = image else: size = image.height if image.height > image.width else image.width size = (size, size) resized_image = resizeimage.resize(resize_method, image, size) resized_image.save(buffer_image, image.format, quality=95) buffer_image.seek(0) mimetypes.init() mimetype = mimetypes.types_map['.' + image.format.lower()] return send_file(buffer_image, mimetype=mimetype)
def simpleshitposts(): print('shitposts') reddit = praw.Reddit( client_id=os.environ['CLIENT_ID'], client_secret=os.environ['CLIENT_SECRET'], user_agent="Oasis discordbot by /u/oasis-bot-discord") print("Praw took creds") subreddit = reddit.subreddit('memes').new(limit=20) resp = [] print("Chooser chose shit") for submission in subreddit: if submission.url.startswith('https://i'): resp.append({"url": submission.url, "title": submission.title}) print("for loop ended") meme = random.choice(resp) memeurl = meme.get('url') memetitle = meme.get('title') image = requests.get(memeurl) file = open('shitpost.jpg', 'wb') file.write(image.content) file.close() programmersubreddit = reddit.subreddit('programmerhumor').new(limit=20) programmerresp = [] print("Chooser chose shit") for programmersubmission in programmersubreddit: if programmersubmission.url.startswith('https://i'): programmerresp.append({ "url": programmersubmission.url, "title": programmersubmission.title }) print("for loop ended") programmermeme = random.choice(programmerresp) programmermemeurl = programmermeme.get('url') programmermemetitle = programmermeme.get('title') image = requests.get(programmermemeurl) file = open('meme.jpg', 'wb') file.write(image.content) file.close() programmerimg = Image.open('meme.jpg', 'r') img_w, img_h = programmerimg.size programmerimg = resizeimage.resize('thumbnail', programmerimg, [600, 600]) bgcolor = (random.randint(1, 255), random.randint(1, 255), random.randint(1, 255)) background = Image.new('RGB', (750, 750), bgcolor) offset = ((50), (50)) background.paste(programmerimg, offset) if os.path.exists("meme.jpg.REMOVE_ME"): os.remove("meme.jpg.REMOVE_ME") elif os.path.exists("meme.jpg"): os.remove("meme.jpg") else: print("The file does not exist") background.save('meme.jpg') print("file got saved") print(meme) memew = open('meme.txt', "a") memew.write(f'{meme}\n') memew.close() #pil img = Image.open('shitpost.jpg', 'r') img_w, img_h = img.size if img_h >= 700: img = resizeimage.resize('thumbnail', img, [600, 600]) print('big') else: img = resizeimage.resize('thumbnail', img, [600, 600]) bgcolor = (random.randint(1, 255), random.randint(1, 255), random.randint(1, 255)) background = Image.new('RGB', (750, 750), bgcolor) offset = ((50), (50)) background.paste(img, offset) if os.path.exists("shitpost.jpg.REMOVE_ME"): os.remove("shitpost.jpg.REMOVE_ME") elif os.path.exists("shitpost.jpg"): os.remove("shitpost.jpg") else: print("The file does not exist") background.save('shitpost.jpg') print("file got saved") print(meme) memew = open('shitpost.txt', "a") memew.write(f'{meme}\n') memew.close() # instagram programmerbot = Bot() shitpostCaption = f'{memetitle}\n#shitposting #offset #shitposts #india #memes #meme' programmerCaption = f'{programmermemetitle}\n#codedatt #programmerslife #python #python3 #backenddeveloper #androiddeveloper #webdevelopment #hacking #cprogramming #programmingmemes #java #deeplearning #softwaredeveloper #programming #coding #programmer #programminglife #coder #javascript #fullstackdeveloper #codingmemes #programmers #cplusplus #programmingisfun #developer #coders #neuralnetworks #html #webdeveloper #programmer #programmingmemes #memes' programmerbot.login(username=os.environ['SHIT_USERNAME'], password=os.environ['SHIT_PASSWORD']) programmerbot.upload_photo('shitpost.jpg', caption=shitpostCaption) time.sleep(32) programmerbot.upload_photo('meme.jpg', caption=programmerCaption)