def image_to_pdf(self, img, pdf_path=None, **kwargs): """ Converts an input image file to a PDF file. :param img: image file opened with the PIL library. :param pdf_path: optional parameter indicating file path of the to-be-generated PDF file. A temporary file is created if no value is provided. :param kwargs: any parameter accepted by Image.save i.e. quality :return: """ processor = ResizeToFit(width=self.max_size_in_pixels[0], height=self.max_size_in_pixels[1]) img = processor.process(img) # Create a white canvas and paste the image final_img_width = min(img.size[0], self.max_size_in_pixels[0]) final_img_height = min(img.size[1], self.max_size_in_pixels[1]) tmp_image = Image.new("RGB", (final_img_width, final_img_height), "white") margin_left = 0 margin_top = 0 tmp_image.paste( img, (margin_left, margin_top, final_img_width, final_img_height)) tmp_image = self.compress_img(tmp_image, quality=70) # Save the image as .pdf file if not pdf_path: f = NamedTemporaryFile(delete=False) pdf_path = f.name tmp_image.save(pdf_path, "PDF", resolution=100.0, **kwargs) return pdf_path
def _gen_resized_image_with_width_limited(cls, image, fit_width): o_width, o_height = image.size if o_width <= fit_width: return image fit_height = o_height * fit_width / o_width + 1 processor = ResizeToFit(fit_width, fit_height) new_image = processor.process(image) return new_image
def upload(request): """ 이미지를 전송받고 리사이징 및 초보적인 투명화를 진행 유저에거 컨펌 받기 위해 사진 두 장(원본 리사이즈드, 투명화)의 참조 경로를 리턴함 """ if 'image' in request.FILES: userfile = request.FILES['image'] filename = userfile._name # 디렉토리가 없으면 생성 if not os.path.exists(settings.CLOTHES_ROOT): os.makedirs(settings.CLOTHES_ROOT) if not os.path.exists(settings.CLOTHES_ROOT_TMP): os.makedirs(settings.CLOTHES_ROOT_TMP) # 임시 파일명 생성 uuid_list = str(uuid.uuid4()).split('-') prefix = uuid_list[0] + '-' + uuid_list[4] temp_file = prefix + filename[filename.rindex('.') - 1:] temp_file_png = \ temp_file[0:temp_file.rindex('.')] + '-resized.png' # 원본 저장 fp = open(os.path.join(settings.CLOTHES_ROOT_TMP, temp_file), 'wb') for chunk in userfile.chunks(): fp.write(chunk) fp.close() # 스마트폰 카메라로 찍은 경우 특정 orientation 에서 이미지가 돌아가는 문제 수정 source = Image.open(os.path.join(settings.CLOTHES_ROOT_TMP, temp_file)) if source._getexif() != None: exif = dict((ExifTags.TAGS[k], v) \ for k, v in source._getexif().items() if k in ExifTags.TAGS) if 'Orientation' in list(exif.keys()): source = source.rotate(-90, expand=True) \ if exif['Orientation'] == 6 \ else source # 임시 리사이즈 및 저장 processor = ResizeToFit(width=250, height=250) target = processor.process(source) target.save(os.path.join(settings.CLOTHES_ROOT_TMP, temp_file_png)) # 초보적 배경 제거 if source.mode == "RGBA" or "transparency" in source.info: mod_file_png = temp_file_png else: mod_file_png = removebg(settings.CLOTHES_ROOT_TMP, temp_file_png) json_data = json.dumps({'org': temp_file_png, 'mod': mod_file_png}) # processor = Thumbnail(width=150, height=150) # source = Image.open(os.path.join(settings.CLOTHES_ROOT_TMP, temp_file)) # target = processor.process(source) return HttpResponse(json_data, content_type="application/json") return HttpResponse('Failed to Upload File')
def generate_image_thumbnail(source, width, height, image_format='JPEG'): """ Generates a thumbnail of the provided image that has the specified maximum dimensions. """ image = Image.open(source) processor = ResizeToFit(width=width, height=height) resized = processor.process(image).convert('RGB') resized_image = io.BytesIO() resized.save(resized_image, format=image_format) return resized_image
def add_artwork(image_uri, file_path, processor='SmartResize'): size = (300, 300) try: if 'http' in image_uri: # Remote image file h = requests.head(image_uri) content_type = h.headers.get('content-type') r = requests.get(image_uri) image_data = r.content print(content_type) else: # Local image file mime = MimeTypes() content_type, a = mime.guess_type(filename) with open(image_uri, 'rb') as file: image_data = file.read() except Exception as e: print("Coult not open {0}".format(image_uri)) return False # Try to embed picture try: fd = mutagen.File(file_path) image = Image.open(BytesIO(image_data)) if 'resizetofit' in processor.lower(): color_thief = ColorThief(BytesIO(image_data)) # get the dominant color # dominant_color = color_thief.get_color(quality=10) dominant_color = color_thief.get_palette()[0] processor = ResizeToFit(size[0], size[1]) else: processor = SmartResize(size[0], size[1]) dominant_color = (255, 255, 255) print(dominant_color) new_img = processor.process(image) background = Image.new("RGB", size, dominant_color) background.paste(new_img, mask=new_img.split()[3]) # 3 is the alpha channel temp = BytesIO() background.save(temp, format="JPEG") fd.tags.add( APIC(encoding=3, mime=content_type, type=3, desc=u'Album', data=temp.getvalue())) fd.save() return True except Exception as e: print(e) print('Could not set album art') return False
def load_data(num=2000, resize=256, crop=(224, 224), folder='catdog_data/train'): files = os.listdir(folder) chosen = np.random.choice(files, num) data = [] # processors w, h = crop cropper = SmartCrop(width=w, height=h) def get_new_dimensions(im): w, h = im.size if w < h: orientation = 'v' small, big = w, h else: orientation = 'h' small, big = h, w small_size = resize big_size = int(big * float(small_size) / small) if orientation == 'v': return small_size, big_size else: return big_size, small_size labels = [] for i, fname in enumerate(chosen): print i path = os.path.join(folder, fname) im = Image.open(path) # first resize w, h = get_new_dimensions(im) resizer = ResizeToFit(width=w, height=h, upscale=True) im = resizer.process(im) # then crop im = cropper.process(im) # then to numpy and rescale to [0, 1] im = np.float32(np.mean(np.asarray(im), axis=-1)) / 255. data.append(im.ravel()) # don't forget labels if 'cat' in fname: labels.append(0) else: labels.append(1) return np.vstack(data), np.hstack(labels)
def process(image_url, processor = None, width=None, height=None, resolution=None, quality=100): conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) bucket = conn.get_bucket(settings.AWS_STORAGE_BUCKET_NAME) if image_url[0] =='/': image_url = image_url[1:] r = requests.get(image_url.replace('https', 'http')) img = Image.open(StringIO(r.content)) processor = ResizeToFit(width, height) new_img = processor.process(img) new_file = StringIO() save_image(new_img, new_file, 'JPEG') new_k = Key(bucket) parts = urlparse(image_url) img_name = os.path.splitext(os.path.basename(parts.path))[0] new_k.key = 'il/{}x{}/{}.jpeg'.format(width, height, img_name) new_k.content_type = 'image/jpeg' new_k.set_contents_from_file(new_file, policy='public-read') new_image_url = new_k.generate_url(0, query_auth=False, force_http=True) processed_image,_ = ProcessedImage.objects.update_or_create(source_image = image_url, processed_image = new_image_url) return processed_image
def resize(image, *size): """ size is a pair like 600, 600 """ processor = ResizeToFit(*size) return processor.process(image)
def generate_image(inpath, outpath, width=None, height=None, format=JPEG, fill=False, upscale=True, anchor=None, quality=80, bgcolor=None, progressive=True, force_cache=False, placeholder_reason=None, placeholder_image_path=None): """Generate an image with the passed in settings This is used by :func:`resize` and is run outside of the Flask context. Args: inpath (str): Path to the image to generate a new image out of. outpath (str): Where the new image will end up. width (Optional[:class:`int`]): The width to use for the generated image. height (Optional[:class:`str`]): The height to use for the generated image. format (str): Format to convert into. Defaults to "JPEG". fill (bool): Fill the entire width and height that was specified if True, otherwise keep the original image dimensions. Defaults to False. upscale (bool): Whether or not to allow the image to become bigger than the original if the request width and/or height is bigger than its dimensions. Defaults to True. anchor (str): Deprecated since Flask-Resize 0.6. quality (int): Quality of the output image, if the format is JPEG. Defaults to 80. bgcolor (Optional[:class:`str`]): If specified this color will be used as background. progressive (bool): Whether to use progressive encoding or not when JPEG is the output format. force_cache (bool): Whether to force the function to always use the image cache. If false, will reaise a :class:`exc.StopImageGeneration` if the generated image would be the same as the original. Defaults to False. placeholder_reason (Optional[:class:`str`]): A text to show the user if the image path could not be found. placeholder_image_path (Optional[:class:`str`]): The path to the image to use as the background of the placeholder. Raises: :class:`exc.ImageNotFoundError`: If the source image cannot be found or is not a file. :class:`exc.StopImageGeneration`: If force_cache is False and if the image transformation would result in the same image as the original. Returns: PIL.Image: The generated image. """ if anchor: warnings.warn( "anchor has been deprecated in Flask-Resize 0.6 and doesn't do anything to the image. Will be removed in 1.0.", DeprecationWarning ) if not os.path.isfile(inpath): if placeholder_reason: img = create_placeholder_img(width, height, placeholder_reason, placeholder_image_path) else: raise exc.ImageNotFoundError(inpath) else: img = Image.open(inpath) original_width, original_height = img.size w = width or original_width h = height or original_height if not force_cache and format == _parse_format(inpath) and fill is False: if (w == original_width and h == original_height) or \ (upscale is False and \ (w >= original_width or h >= original_height)): if not placeholder_reason: raise exc.StopImageGeneration() processor_kwargs = dict(width=width, height=height, upscale=upscale) _mkdir_p(outpath.replace('\\','/').rpartition('/')[0]) if fill: if bgcolor: mat_color = ImageColor.getrgb(parse_rgb(bgcolor)) elif format == JPEG: mat_color = (255, 255, 255, 255) # White else: mat_color = (0, 0, 0, 0) # Transparent processor_kwargs['mat_color'] = mat_color # Transparent processor = ResizeToFit(**processor_kwargs) img = processor.process(img) assert (not os.path.exists(outpath)), 'Path to save to already exists' options = {} if format == JPEG: options.update({'quality': int(quality), 'progressive': progressive}) if bgcolor is not None: img = make_opaque(img, bgcolor) with open(outpath, 'wb') as outfile: save_image(img, outfile, format=format, options=options) return img