Example #1
0
def transform_upload(destination0, destination1, destination2, destination3,
                     destination4, filename1, filename2, filename3, filename4,
                     s3):
    img = Image(filename=destination0)
    transformed1 = img.clone()
    transformed2 = img.clone()
    transformed3 = img.clone()
    transformed4 = img.clone()

    transformed1.resize(1280, 720)
    transformed2.rotate(180)

    library.MagickSepiaToneImage.argtypes = [ctypes.c_void_p, ctypes.c_double]
    library.MagickSepiaToneImage.restype = None
    threshold = transformed3.quantum_range * 0.8
    library.MagickSepiaToneImage(transformed3.wand, threshold)

    transformed4.type = 'grayscale'

    transformed1.save(filename=destination1)
    s3.upload_file(destination1, 'ece1779-bucket-1', filename1)
    os.remove(destination1)

    transformed2.save(filename=destination2)
    s3.upload_file(destination2, 'ece1779-bucket-1', filename2)
    os.remove(destination2)

    transformed3.save(filename=destination3)
    s3.upload_file(destination3, 'ece1779-bucket-1', filename3)
    os.remove(destination3)

    transformed4.save(filename=destination4)
    s3.upload_file(destination4, 'ece1779-bucket-1', filename4)
    os.remove(destination4)
Example #2
0
def image_transform(id,FileName):
    UserId = id
    bucket_name = s3_config
    file_name = os.path.join('app/static',FileName)
    img = Image(filename = file_name)
    transform_1 =img.clone()
    transform_1.rotate(90)
    transform_name_1 = os.path.join('app/static',  'FirstTransform_' + FileName)
    transform_1.save(filename = transform_name_1)
    s3_upload = boto3.client('s3')
    s3_upload.upload_file(transform_name_1, bucket_name, str(UserId) + '/FirstTransform_' + FileName)

    transform_2 =img.clone()
    transform_2.rotate(180)
    transform_name_2 = os.path.join('app/static','SecondTransform_' + FileName)
    transform_2.save(filename = transform_name_2)
    s3_upload.upload_file(transform_name_2, bucket_name, str(UserId) + '/SecondTransform_' + FileName)

    transform_3 =img.clone()
    transform_3.rotate(300)
    transform_name_3 = os.path.join('app/static','ThirdTransform_' + FileName)
    transform_3.save(filename = transform_name_3)
    s3_upload.upload_file(transform_name_3, bucket_name, str(UserId) + '/ThirdTransform_' + FileName)
    return render_template("Image/view.html", f1 = file_name[4:],
                                             f2 = transform_name_1[4:],
                                             f3 = transform_name_2[4:],
                                             f4 = transform_name_3[4:])
Example #3
0
    def validate_avatar(self, field):
        if not field.data:
            return

        file = field.data

        image = Image(file=file)
        xsize = image.width
        ysize = image.height
        extension = field.data.filename.split(".")[-1]

        if xsize > 200 or ysize > 200:
            resize_measure = min(200.0 / float(xsize), 200.0 / float(ysize))
            self.avatar_image = image.clone()
            self.avatar_image.resize(int(round(xsize * resize_measure)),
                                     int(round(ysize * resize_measure)))
        else:
            self.avatar_image = image

        resized_avatar = self.avatar_image.clone()
        resized_avatar_bin = self.avatar_image.make_blob()
        avvie_size = len(resized_avatar_bin)
        if avvie_size > 512 * 1024:
            raise validators.ValidationError(
                "Your avatar filesize (even after being resized) is too large. Resize to less than 512kb."
            )

        crop_off_bottom = False
        crop_off_right = False
        if ysize > xsize:
            crop_off_bottom = True
            pixels_to_crop = ysize - xsize
        elif xsize > ysize:
            crop_off_right = True
            pixels_to_crop = xsize - ysize

        self.fourty_image = image.clone()
        if crop_off_bottom == True:
            self.fourty_image.crop(height=(ysize - pixels_to_crop))
        if crop_off_right == True:
            self.fourty_image.crop(width=(xsize - pixels_to_crop),
                                   gravity='center',
                                   height=ysize)

        self.fourty_image.resize(int(round(40)), int(round(40)))

        self.sixty_image = image.clone()
        if crop_off_bottom == True:
            self.sixty_image.crop(height=(ysize - pixels_to_crop))
        if crop_off_right == True:
            self.sixty_image.crop(width=(xsize - pixels_to_crop),
                                  gravity='center',
                                  height=ysize)

        self.sixty_image.resize(int(round(60)), int(round((60))))
def image_transform():

    # check if the post request has the file part
    if 'image_file' not in request.files:
        return "Missing uploaded file"

    new_file = request.files['image_file']

    # if user does not select file, browser also
    # submit a empty part without filename
    if new_file.filename == '':
        return "Missing file name"

    tempdir = tempfile.gettempdir()

    fname = os.path.join('app/static', new_file.filename)

    new_file.save(fname)
    #print (fname)
    img = Image(filename=fname)
    i = img.clone()
    i.rotate(90)

    fname_rotated = os.path.join('app/static', 'rotated_' + new_file.filename)

    i.save(filename=fname_rotated)

    return render_template("/imagetransform/view.html",
                           f1=fname[4:],
                           f2=fname_rotated[4:])
Example #5
0
	def make_image_to_post(self, job_string, image, image_format):
		font_size_to_width_ratio = 0.061
		font_location = './Gotham-Bold.otf'
		fontColors = ['white', 'black']

		logging.info(str(datetime.now()) + ': Begin image compositing.')

		try:
			im = Image(blob=image)
		except MissingDelegateError as e:
			raise
		except:
			raise

		font_size = im.width * font_size_to_width_ratio

		im_clone = im.clone()
		im_clone.resize(1,1)
		
		for row in im_clone:
			for col in row:
				assert isinstance(col, Color)
				if (col.red + col.green + col.blue) / 3.0 >= 0.5:
					fontColors.reverse()

		font = Font(font_location, size=font_size, color=Color(fontColors[1]))
		im.caption(job_string, left=7, top=7, width=im.width-10, height=im.height-10, font=font)
		font = Font(font_location, size=font_size, color=Color(fontColors[0]))
		im.caption(job_string, left=5, top=5, width=im.width-10, height=im.height-10, font=font)

		im.format = image_format
		return im
Example #6
0
def apply_to_image(image: BaseImage, *, color: str, radius: float,
                   sigma: float, xoffset: float, yoffset: float) -> Image:
    xoffset = round(xoffset * image.width)
    yoffset = round(yoffset * image.height)
    new_width = image.width + 3 * xoffset
    new_height = image.height + 3 * yoffset

    opacity = Image(width=new_width, height=new_height, pseudo='xc:white')
    opacity.composite(image.channel_images['opacity'],
                      left=xoffset,
                      top=yoffset)
    opacity.gaussian_blur(radius * image.width, sigma * image.width)
    opacity.negate()
    opacity.modulate(50)

    shadow = Image(width=new_width, height=new_height, pseudo='xc:' + color)
    shadow.composite(opacity, operator='copy_opacity')

    result = Image(width=new_width, height=new_height, pseudo='xc:transparent')
    result.composite(image)
    result.composite(shadow, operator='difference')

    trimmed = result.clone()
    trimmed.trim(color=Color('transparent'))
    result.crop(width=max(image.width, trimmed.width),
                height=max(image.height, trimmed.height))
    return result
Example #7
0
def savefile(imagefile, username):
    """Upload Procedure:"""
    cnx = connect_DB()
    cursor = cnx.cursor()
    query = '''select * from images where username=%s order by imageid DESC'''
    cursor.execute(query, (username, ))
    rownum = cursor.rowcount
    filename = rownum + 1
    # filename = secure_filename(imagefile.filename)
    filename = username + '_' + str(filename)
    imagefile.save(os.path.join(webapp.config['UPLOAD_FOLDER'], filename))
    # with open(os.path.join(webapp.config['UPLOAD_FOLDER'], filename)) as f:
    #     image_binary = f.read()
    # with Image(filename='./images_uploaded/'+filename) as img:
    # with Image(blob=image_binary) as img:
    fname = os.path.join(webapp.config['UPLOAD_FOLDER'], filename)
    img = Image(filename=fname)
    # with open(fname, "rb") as image0:
    with img.clone() as flipped:
        flipped.flip()
        newname1 = os.path.join(webapp.config['UPLOAD_FOLDER'],
                                'trans1_' + filename)
        # flipped.save(os.path.join(webapp.config['UPLOAD_FOLDER'], newname1))
        flipped.save(filename=newname1)
    with img.clone() as cropped:
        frequency = 3
        phase_shift = -90
        amplitude = 0.2
        bias = 0.7
        cropped.function('sinusoid', [frequency, phase_shift, amplitude, bias])
        cropped.save(
            filename=os.path.join(webapp.config['UPLOAD_FOLDER'], "trans2_" +
                                  filename))
    with img.clone() as colored:
        colored.evaluate(operator='rightshift', value=1, channel='blue')
        colored.evaluate(operator='leftshift', value=1, channel='red')
        colored.save(
            filename=os.path.join(webapp.config['UPLOAD_FOLDER'], "trans3_" +
                                  filename))
    query = '''INSERT INTO images (username, image0, image1, image2, image3) VALUES (%s,%s,%s,%s, %s)'''
    # username = session['username']
    cursor.execute(query, (username, filename, 'trans1_' + filename,
                           'trans2_' + filename, 'trans3_' + filename))
    cnx.commit()
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()
Example #8
0
def _save_page_image(pdf_filename, image, thumb_filename,
        make_thumb, thumb_size, thread_number, verbose=False):

    success = False
    image_filename = ''
    if True:
    #try:

        if verbose == True:
            print "{0}: Saving off PDF image ...".format(thread_number)

        try:
          image_filename = '{0}.tiff'.format(pdf_filename)
          bg = WandImage(width=image.width, height=image.height, background=Color("white"))
          bg.composite(image, 0, 0)
          bg.clone().save(
            filename = image_filename,
          )
        except Exception, ex:
          print ex
        #image.clone().save(
        #    filename=image_filename
        #)

        if verbose == True:
            print "{0}: Done saving off PDF image.".format(thread_number)

        if make_thumb == True:

            if verbose == True:
                print "{0}: Making thumb nail image: '{1}' ...".format(thread_number, thumb_filename)

            FNULL = open(os.devnull, 'w')
            cli_call = [
                'convert',
                '-resize',
                '{0}x{0}'.format(thumb_size),
                image_filename,
                thumb_filename,
            ]
            subprocess.call(
                cli_call,
                stdout=FNULL,
                stderr=subprocess.STDOUT
            )

        success = True
Example #9
0
def main():
    funky_img = Image(filename="../images/funky_illustration.png")
    funky_img = resize_to_percent(funky_img, 60)

    cropped_img = funky_img.clone()
    cropped_img.crop(top=0, left=275, width=340, height=486)

    display(funky_img)
    display(cropped_img)
 def resize(self, img, resize_width, resize_height, save_name=None):
     if type(img) == 'str':
         img = Image(filename=img)
     print('original size', img.size)
     img_clone = img.clone()
     img_clone.resize(resize_width, resize_height)
     if save_name is not None:
         img_clone.save(filename=save_name)
     return img_clone
Example #11
0
def clone_downscale_save(input_file, output_file, pixels=3000000,
                         width=None, height=None, compression_quality=92):
  orig = Image(filename=input_file)
  img = orig.clone()
  img = downscale(img, pixels, width, height, compression_quality)

  # Make sure output directory exists
  dirname, _basename = os.path.split(output_file)
  mkdir_p(dirname) # Noop if dir already exists
  img.save(filename=output_def)
Example #12
0
    def set_image(self, binary):
        self.binary = binary
        with Image(blob=self.binary, resolution=150) as img:
            self.extension = img.format.lower()
            flattened = Image(background=Color("white"),
                height=img.height, width=img.width)
            flattened.composite(img, left=0, top=0)
            flattened.format = "jpeg"
            flattened.compression_quality = 50

            thumbnail = flattened.clone()
            thumbnail.transform(resize='150x200>')
            self.thumbnail = thumbnail.make_blob()

            preview = flattened.clone()
            preview.gaussian_blur(radius=1, sigma=0.5)
            preview.transform(resize='612x792>')
            self.preview = preview.make_blob()
        self.save()
Example #13
0
 def save(self, create_thumbnails=True, *args, **kwargs):
     super(Image, self).save(*args, **kwargs)
     from wand.color import Color
     if create_thumbnails:
         thumbnails = {}
         original_image = WImage(filename=self.image.path)
         splitted_path = self.image.path.rsplit('.', 1)
         image_url_part = self.image.url.rsplit('/', 1)
         white_color = Color('white')
         watermark = settings.WATERMARK
         if watermark:
             watermark_img = WImage(filename=watermark.get('path'))
             image_width, image_height = original_image.size
             wm_width, wm_height = watermark_img.size
             wm_left_pos, wm_top_pos = self.watermark_position(
                 settings.WATERMARK_POSITION,
                 image_width, image_height, wm_width, wm_height)
             watermarked_original_image = original_image.clone()
             watermarked_original_image.watermark(
                 watermark_img,
                 settings.WATERMARK_TRANSPARENCY,
                 wm_left_pos,
                 wm_top_pos
             )
             original_image = watermarked_original_image
         for name, size in settings.KONKORD_IMAGE_SIZES.items():
             thumb = original_image.clone()
             thumb.transform(resize='%sx%s' % size)
             thumb.gravity = 'center'
             background = WImage().blank(background=white_color, *size)
             background.composite(
                 thumb,
                 int((background.width - thumb.width) / 2),
                 int((background.height - thumb.height) / 2),
             )
             resized_path = splitted_path.copy()
             resized_path.insert(1, 'x'.join(map(str, size)))
             joined_path = '.'.join(resized_path)
             background.save(filename=joined_path)
             image_url_part[1] = joined_path.rsplit('/', 1)[-1]
             thumbnails[name] = '/'.join(image_url_part)
         self.thumbnails = thumbnails
         self.save(create_thumbnails=False)
Example #14
0
def convert_image(pngfile, pf, outdir=".",
                  resize=1000, format="jpeg", rotate=0,
                  rows=':', cols=':', labelrows=None, labelcols=None):
    resizefile = op.join(outdir, pf + ".resize.jpg")
    mainfile = op.join(outdir, pf + ".main.jpg")
    labelfile = op.join(outdir, pf + ".label.jpg")
    img = Image(filename=pngfile)
    exif = dict((k, v) for k, v in img.metadata.items() if k.startswith('exif:'))

    # Rotation, slicing and cropping of main image
    if rotate:
        img.rotate(rotate)
    if resize:
        w, h = img.size
        if min(w, h) > resize:
            if w < h:
                nw, nh = resize, resize * h / w
            else:
                nw, nh = resize * w / h, resize
            img.resize(nw, nh)
            logging.debug("Image `{0}` resized from {1}px:{2}px to {3}px:{4}px".\
                            format(pngfile, w, h, nw, nh))
    img.format = format
    img.save(filename=resizefile)

    rimg = img.clone()
    if rows != ':' or cols != ':':
        w, h = img.size
        ra, rb = slice(rows, h)
        ca, cb = slice(cols, w)
        # left, top, right, bottom
        logging.debug("Crop image to {0}:{1} {2}:{3}".format(ra, rb, ca, cb))
        img.crop(ca, ra, cb, rb)
        img.format = format
        img.save(filename=mainfile)
    else:
        mainfile = resizefile

    # Extract text labels from image
    if labelrows or labelcols:
        w, h = rimg.size
        if labelrows and not labelcols:
            labelcols = ':'
        if labelcols and not labelrows:
            labelrows = ':'
        ra, rb = slice(labelrows, h)
        ca, cb = slice(labelcols, w)
        logging.debug("Extract label from {0}:{1} {2}:{3}".format(ra, rb, ca, cb))
        rimg.crop(ca, ra, cb, rb)
        rimg.format = format
        rimg.save(filename=labelfile)
    else:
        labelfile = None

    return resizefile, mainfile, labelfile, exif
Example #15
0
def convert_image(pngfile, pf, outdir=".",
                  resize=1000, format="jpeg", rotate=0,
                  rows=':', cols=':', labelrows=None, labelcols=None):
    resizefile = op.join(outdir, pf + ".resize.jpg")
    mainfile = op.join(outdir, pf + ".main.jpg")
    labelfile = op.join(outdir, pf + ".label.jpg")
    img = Image(filename=pngfile)
    exif = dict((k, v) for k, v in img.metadata.items() if k.startswith('exif:'))

    # Rotation, slicing and cropping of main image
    if rotate:
        img.rotate(rotate)
    if resize:
        w, h = img.size
        if min(w, h) > resize:
            if w < h:
                nw, nh = resize, resize * h / w
            else:
                nw, nh = resize * w / h, resize
            img.resize(nw, nh)
            logging.debug("Image `{0}` resized from {1}px:{2}px to {3}px:{4}px".\
                            format(pngfile, w, h, nw, nh))
    img.format = format
    img.save(filename=resizefile)

    rimg = img.clone()
    if rows != ':' or cols != ':':
        w, h = img.size
        ra, rb = slice(rows, h)
        ca, cb = slice(cols, w)
        # left, top, right, bottom
        logging.debug("Crop image to {0}:{1} {2}:{3}".format(ra, rb, ca, cb))
        img.crop(ca, ra, cb, rb)
        img.format = format
        img.save(filename=mainfile)
    else:
        mainfile = resizefile

    # Extract text labels from image
    if labelrows or labelcols:
        w, h = rimg.size
        if labelrows and not labelcols:
            labelcols = ':'
        if labelcols and not labelrows:
            labelrows = ':'
        ra, rb = slice(labelrows, h)
        ca, cb = slice(labelcols, w)
        logging.debug("Extract label from {0}:{1} {2}:{3}".format(ra, rb, ca, cb))
        rimg.crop(ca, ra, cb, rb)
        rimg.format = format
        rimg.save(filename=labelfile)
    else:
        labelfile = None

    return resizefile, mainfile, labelfile, exif
def main():
    args = parseArguments()

    px = args.pixels
    out = args.out
    filename_out = os.path.splitext(ntpath.basename(args.input))[0] + ".png"

    img = Image(filename=args.input, resolution=(72, 72))
    img.clone().convert('png').save(filename="xxx.png")
    if args.mode is 'android' or args.mode is 'all':
        convertImage(img, px,       join(out, "drawable-mdpi"), filename_out)
        convertImage(img, int(px * 1.5), join(out, "drawable-hdpi"), filename_out)
        convertImage(img, px * 2,   join(out, "drawable-xhdpi"), filename_out)
        convertImage(img, px * 3,   join(out, "drawable-xxhdpi"), filename_out)
        convertImage(img, px * 4,   join(out, "drawable-xxxhdpi"), filename_out)
    elif args.mode is 'ios' or args.mode is 'all':
        convertImage(img, px * 2,   join(out, "ios-2x"), filename_out)
        convertImage(img, px,       join(out, "ios-1x"), filename_out)
        convertImage(img, px * 3,   join(out, "ios-3x"), filename_out)
    img.close()
Example #17
0
def barcode_decoder(file):
    store_base = "B" + datetime.now().strftime(
        '%Y-%m-%d-%H-%M-%S') + '-' + str(uuid.uuid4())
    store_ext = filename_extension(file.filename)
    const_file_name = store_base + "_barcode" + "." + store_ext
    img = cv2.imdecode(numpy.fromstring(file.read(), numpy.uint8),
                       cv2.IMREAD_UNCHANGED)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    barcodes = pyzbar.decode(gray)
    # loop over the detected barcodes
    barcodeData = []
    for barcode in barcodes:
        print("checking barcode")
        # extract the bounding box location of the barcode and draw the bounding box surrounding the barcode on the image
        (x, y, w, h) = barcode.rect
        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 20)
        barcode_data = barcode.data.decode("utf-8")
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(img, barcode_data, (x, y), font, 1.2, (0, 0, 0), 5,
                    cv2.LINE_AA)
        # the barcode data is a bytes object so if we want to draw it on our output image we need to convert it to a string first
        barcodeData.append(barcode_data)
    #check if any barcode found
    if len(barcodeData) > 0:
        store_ext_dot = '.' + store_ext
        r, outputImage = cv2.imencode(store_ext_dot, img)
        #storing in S3
        i_byte = io.BytesIO()
        i_byte.write(outputImage)
        i_byte.seek(0)
        #creating thumbnail
        with i_byte as new_file_b:
            img = Image(file=new_file_b)  # response
            i = img.clone()
            i.resize(240, 180)
        b_byte = io.BytesIO()
        i.save(file=b_byte)
        b_byte.seek(0)
        with b_byte as new_file_b:
            s3 = boto3.client('s3')
            s3.upload_fileobj(new_file_b,
                              BUCKET_NAME,
                              const_file_name,
                              ExtraArgs={'ACL': 'public-read'})
        # print the barcode type and data to the terminal
        print("[INFO] Found barcode: {}".format(barcodeData))
        # store barcode data on dynamoDB [To Do]
        dynamo.update_append_user_barcode_attribute(current_user.username,
                                                    barcodeData,
                                                    const_file_name)
    else:
        raise Exception('Error encoding barcode')
    return barcodeData, const_file_name
Example #18
0
def orient_and_resize(image_filename):
    resized_images = {}
    
    img = Image(filename=image_filename)
    img.auto_orient()

    (w,h) = img.size
    w = int(w)
    h = int(h)

    filename_base = image_filename
    filename_base = filename_base.replace("/", "-")
    filename_base = filename_base.replace(" ", "_")

    with img.clone() as img_clone:
        img_clone.resize(1280, int((1280.0/w)*h))
        fname = "Resized/" + filename_base + "_1280.jpg"
        resized_images['1280'] = fname
        img_clone.save(filename=PREFIX_DIR + fname)

    with img.clone() as img_clone:
        img_clone.resize(640, int((640.0/w)*h))
        fname = "Resized/" + filename_base + "_640.jpg"
        resized_images['640'] = fname
        img_clone.save(filename=PREFIX_DIR + fname)

    with img.clone() as img_clone:
        img_clone.resize(320, int((320.0/w)*h))
        fname = "Resized/" + filename_base + "_320.jpg"
        resized_images['320'] = fname
        img_clone.save(filename=PREFIX_DIR + fname)

    with img.clone() as img_clone:
        img_clone.resize(160, int((160.0/w)*h))
        fname = "Resized/" + filename_base + "_160.jpg"
        resized_images['160'] = fname
        img_clone.save(filename=PREFIX_DIR + fname)

    img.close()
    return ((w, h), resized_images)
Example #19
0
def process_file(user_id, new_file):
    store_base = "I" + datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + '-' + str(uuid.uuid4())
    store_ext = filename_extension(new_file.filename)
    original_store_path = os.path.join('app/static/user_images', store_base + "." + store_ext)
    new_file.save(original_store_path)
    try:
        cnx = get_db()
        cursor = cnx.cursor()

        # create a new tuple for the photo and store the
        query = "INSERT INTO photo (user_id) VALUES (%s)"
        cursor.execute(query, (user_id,))

        # get id of newly created tuple
        query = "SELECT LAST_INSERT_ID()"
        cursor.execute(query)

        row = cursor.fetchone()

        photo_id = row[0]

        # store the path to the original image
        query = "INSERT INTO storedphoto (filename,type_id,photo_id) VALUES (%s,%s,%s)"

        cursor.execute(query, (original_store_path[4:], TYPE_ORIGINAL, photo_id))

        # create thumbnail
        img = Image(filename=original_store_path)
        i = img.clone()
        i.resize(80, 80)
        thumbnail_store_path = os.path.join('app/static/user_images', store_base + "_thumb." + store_ext)
        i.save(filename=thumbnail_store_path)

        # store path to thumbnail
        query = "INSERT INTO storedphoto (filename,type_id,photo_id) VALUES (%s,%s,%s)"
        cursor.execute(query, (thumbnail_store_path[4:], TYPE_THUMBNAIL, photo_id))

        with open(original_store_path, 'rb') as f:
            image_bytes = f.read()
        image_bytes_np = numpy.asarray(image_bytes)
        df_store_path = os.path.join('app/static/user_images', store_base + "_df." + store_ext)
        detect_faces_and_save(image_bytes_np, df_store_path)

        query = "INSERT INTO storedphoto (filename,type_id,photo_id) VALUES (%s,%s,%s)"
        cursor.execute(query, (df_store_path[4:], TYPE_FACE_DETECTED, photo_id))

        cursor.close()

        cnx.commit()

    except Exception as e:
        raise e
Example #20
0
def transform(filename, fname):
    img = Image(filename=fname)
    flopped = img.clone()
    flopped.flop()
    fname_flopped = filename.split('.', 1)[0] + '_flopped.' + filename.split(
        '.', 1)[1]
    flopped.save(
        filename=os.path.join(app.config['UPLOAD_FOLDER'], fname_flopped))
    rotated = img.clone()
    rotated.rotate(45)
    fname_rotated = filename.split('.', 1)[0] + '_rotated.' + filename.split(
        '.', 1)[1]
    rotated.save(
        filename=os.path.join(app.config['UPLOAD_FOLDER'], fname_rotated))
    enhanced = img.clone()
    enhanced.evaluate(operator='rightshift', value=1, channel='blue')
    enhanced.evaluate(operator='leftshift', value=1, channel='red')
    fname_enhanced = filename.split('.', 1)[0] + '_enhanced.' + filename.split(
        '.', 1)[1]
    enhanced.save(
        filename=os.path.join(app.config['UPLOAD_FOLDER'], fname_enhanced))
    return [fname_flopped, fname_rotated, fname_enhanced]
    def make_variant(self, base_img: Image, size):
        """Make image variant to handle responsive images.

        base_img: large reference image, that needs to be
                  adjusted for desired resolution

        Function can return only one variant.
        If you need to form plenty of images, use make_variants instead.
        """
        with base_img.clone() as variant:
            self.resize(variant, size)
            new_path = self.get_new_filepath(size)
            variant.save(filename=new_path)
            return new_path
Example #22
0
def image_transform(image_binary, degree, fname):

    #image_binary = f.read()

    img = Image(blob=image_binary)
    i = img.clone()

    i.rotate(degree)
    i.format = "jpeg"
    i.save(filename=fname)

    newfile = open(fname, "rb")

    return newfile
Example #23
0
 def create_circular_image(self, img, radius=50):
     img = img if hasattr(img, "read") else open(img, "rb")
     imgsize = radius * 2
     img.seek(0)
     img = Image(file=img)
     self._instance_bin.add(img)
     img.resize(imgsize, imgsize)
     with img.clone() as mask:
         mask.threshold(-1)
         mask.negate()
         with Drawing() as draw:
             draw.fill_color = Color("white")
             draw.circle((radius, radius), (radius, 1))
             draw(mask)
         mask.alpha_channel = False
         img.composite(mask, operator="copy_opacity")
     return img
Example #24
0
def img_display(UserId):
    all_file = file_list(UserId)
    s3_client = boto3.client ('s3')
    bucket_name = s3_config
    file_path = []
    if not all_file:
        error_msg = "No image, please upload first!"
        return render_template("Image/upload.html",error_msg=error_msg, UserId = UserId)
    for FileName in all_file:
        file_name = os.path.join('app/static',FileName)
        s3_client.download_file(bucket_name, str(UserId) + '/'  + FileName, file_name)
        img = Image(filename = file_name)
        thumb_nail = img.clone()
        thumb_nail_name = os.path.join('app/static','thumb_nail_' + FileName)
        thumb_nail.resize(150,150)
        thumb_nail.save(filename = thumb_nail_name)
        file_path.append(thumb_nail_name[4:])
    return render_template("Image/OriginalView.html", file = file_path, UserId = UserId)
def Test_2():
    from wand.image import Image, COMPOSITE_OPERATORS
    from wand.drawing import Drawing
    from wand.display import display
    from wand.api import library

    wizard = Image(filename='wizard:')
    rose = Image(filename='rose:')

    # for o in COMPOSITE_OPERATORS:
    # 	w=wizard.clone()
    # 	r=rose.clone()
    # 	with Drawing() as draw:
    # 		draw.composite(operator=o, left=175, top=250,width=r.width, height=r.height, image=r)
    # 		draw(w)
    # 		display(w)

    w = wizard.clone()
Example #26
0
def picture_save_api(request_file,
                     original_file_size=(0, 0),
                     original_file_type='jpeg',
                     compress_file_size=(0, 0),
                     compress_file_type='jpeg'):
    pic = Picture()
    pic.save()

    original_image = Image(file=urlopen(request_file))
    compress_image = original_image.clone()

    original_image.format = original_file_type
    compress_image.format = compress_file_type
    w, h = original_image.size

    original_width = w
    compress_width = w
    original_height = h
    compress_height = h

    if original_file_size[0] > 0:
        original_width = original_file_size[0]
    if original_file_size[1] > 0:
        original_height = original_file_size[1]

    if compress_file_size[0] > 0:
        compress_width = compress_file_size[0]
    if compress_file_size[1] > 0:
        compress_height = compress_file_size[1]

    original_image.resize(original_width, original_height)
    original_image.compression_quality = 60

    compress_image.resize(compress_width, compress_height)
    compress_image.compression_quality = 60

    pic.original_image.save(
        str(pic.id) + u'_o.' + original_file_type,
        ContentFile(original_image.make_blob()))
    pic.compress_image.save(
        str(pic.id) + u'_c.' + compress_file_type,
        ContentFile(compress_image.make_blob()))

    return pic
Example #27
0
def process_image(source_image: Image,
                  operations_string: str) -> Optional[Image]:
    operations = operations_string.split('/')
    image = source_image.clone()

    while len(operations) > 1:
        operation = operations.pop(0)
        params = operations.pop(0)

        if operation == 'crop':
            handle_crop(image, params)

        if operation == 'resize':
            image.transform(resize=params)

        if operation == 'rotate':
            image.rotate(int(params))

    return image
Example #28
0
def get_transformations(fname):
    #print ("!!!!!!!!!!!!!!!!!!!!!!!enter transformation!!!!!!!!!!!!!!!!!!!!!!!!!!")
    img = Image(filename=fname)
    #print ("!!!!!!!!!!!!!!!!!filename=%s!!!!!!!!!!!!!!!!!!!!!!!!!!!"%fname)
    photos = []
    for type in PhotoType:
        i = img.clone()
        if type == PhotoType.THUMBNAIL:
            #print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!thumbnail!!!!!!!!!!!!!!!!!!!!")
            height = 200
            width = int (img.width * height / img.height)
            i.resize(width, height)
        elif type == PhotoType.BLACKWHITE:
            i.type = 'bilevel'
        elif type == PhotoType.FLIPPED:
            i.flip()
        photos.append(i)
    #print ("!!!!!!!!!!!!!!!!!!!!!!!finish transform!!!!!!!!!!!!!!!!!!!!!!!!!")
    return photos,fname
Example #29
0
def kekify(kek_param, filename, extension, file):
    if kek_param == "-m":
        result = multikek(filename, extension)
        return None, None, result
    if file == None:
        source = Image(filename=path + filename + extension)
    else:
        source = file
    w = source.width
    h = source.height
    c, p1, p2, f = get_values(kek_param, w, h)
    with source.clone() as part1:
        part1.crop(c[0], c[1], c[2], c[3])
        with part1.clone() as part2:
            getattr(part2, f)()
            new_canvas = Image()
            new_canvas.blank(w, h)
            new_canvas.composite(part1, p1[0], p1[1])
            new_canvas.composite(part2, p2[0], p2[1])
    source.close()
    return w, h, new_canvas
Example #30
0
def create_and_store_transformation(trans_id, filename, photo_id, url0):
    # create transformation
    cnx = get_db()
    cursor = cnx.cursor()
    fp = urlopen(url0)
    img = Image(file=fp)
    i = img.clone()
    i.rotate(90 * trans_id)
    fname_transformation = os.path.join(
        'app/static/temp', 'transformation_' + str(trans_id) + "_" + filename)
    i.save(filename=fname_transformation)
    s3 = boto3.client('s3')
    s3.upload_file(fname_transformation, 'ece1779fall2017photo',
                   'transformation_' + str(trans_id) + "_" + filename)
    url = 'https://s3.amazonaws.com/ece1779fall2017photo/' + 'transformation_' + str(
        trans_id) + "_" + filename
    # store path
    query = "INSERT INTO transformation (filename,type_id,photo_id) VALUES (%s,%s,%s)"
    cursor.execute(query, (url, trans_id, photo_id))
    cnx.commit()
    return
Example #31
0
def test_wand():
    image_data = Image(blob=s)
    image_data.compression_quality = 70
    is_gallery_card = False
    image_data_size = (image_data.width, image_data.height)

    image_size = (720, 720)
    if is_gallery_card:
        image_size = (720, 1120)

    if image_size != image_data_size:
        result = image_data.resize(image_size[0], image_size[1])

    with image_data.clone() as img:
        result = img = crop_image(img, (720, 472))

        # 공감전용 카드의 경우 댓글용 이미지를 생성하지 않는다.
        if not is_gallery_card:
            result = img.resize(460, 310)

    result = image_data.resize(360, 360)
    result = image_data.resize(132, 132)
    return result
Example #32
0
def main():
    req_width = 595
    req_height = 486
    baby_img = Image(filename="baby_cc_sh.png")
    baby_img = resize_to_height(baby_img, req_height)

    temp_img = new_blank_png(req_width, req_height)
    temp_img.composite(baby_img, 0, 0)
    baby_img = temp_img

    mask_img = new_blank_png(req_width, req_height, color=Color('rgb(32,32,32)'))
    mask_img.save(filename="mask_img.png")

    print "DEBUG baby_img", baby_img.alpha_channel
    print "DEBUG mask_img", mask_img.alpha_channel

    baby_img_masked = baby_img.clone()
    baby_img_masked.composite_channel(channel='all_channels', image=mask_img, operator='copy_opacity')

    display(baby_img)
    display(baby_img_masked)

    baby_img.save(filename="baby_img.png")
    baby_img_masked.save(filename="baby_img_masked.png")
Example #33
0
def picture_save_api(request_file, original_file_size=(0, 0), original_file_type='jpeg', compress_file_size=(0, 0), compress_file_type='jpeg'):
    pic = Picture()
    pic.save()

    original_image = Image(file=urlopen(request_file))
    compress_image = original_image.clone()

    original_image.format = original_file_type
    compress_image.format = compress_file_type
    w, h = original_image.size

    original_width = w
    compress_width = w
    original_height = h
    compress_height = h

    if original_file_size[0] > 0:
        original_width = original_file_size[0]
    if original_file_size[1] > 0:
        original_height = original_file_size[1]

    if compress_file_size[0] > 0:
        compress_width = compress_file_size[0]
    if compress_file_size[1] > 0:
        compress_height = compress_file_size[1]

    original_image.resize(original_width, original_height)
    original_image.compression_quality = 60

    compress_image.resize(compress_width, compress_height)
    compress_image.compression_quality = 60

    pic.original_image.save(str(pic.id) + u'_o.' + original_file_type, ContentFile(original_image.make_blob()))
    pic.compress_image.save(str(pic.id) + u'_c.' + compress_file_type, ContentFile(compress_image.make_blob()))

    return pic
def file_upload():
    login = request.form.get("userID")
    password = request.form.get("password")

    error = False

    if login == "" or password == "":
        return "Missing username or password"

    cnx = get_db()
    cursor = cnx.cursor()
    query = ''' SELECT * FROM users WHERE login = %s '''
    cursor.execute(query, (login, ))

    row = cursor.fetchone()

    if row == None:
        return "User not existed"

    id = row[0]
    _login = row[1]
    _password = row[2]

    if _password != password:
        return "Wrong password"

    #---------------------------------------------------------

    # check if the post request has the file part
    if 'uploadedfile' not in request.files:
        return "Missing uploaded file"

    new_image = request.files['uploadedfile']

    # if user does not select file, browser also
    # submit a empty part without filename
    if new_image.filename == '':
        return 'Missing file name'

    fname = os.path.join('app/static', new_image.filename)
    new_image.save(fname)

    img = Image(filename=fname)
    i1 = img.clone()
    i1.modulate(33, 67, 50)
    fname_tr1 = os.path.join('app/static', "TR1_" + new_image.filename)
    i1.save(filename=fname_tr1)
    i2 = img.clone()
    i2.flop()
    fname_tr2 = os.path.join('app/static', "TR2_" + new_image.filename)
    i2.save(filename=fname_tr2)
    i3 = img.clone()
    i3.transform('300*300', '200%')
    fname_tr3 = os.path.join('app/static', "TR3_" + new_image.filename)
    i3.save(filename=fname_tr3)

    s3 = boto3.client('s3')
    with open(fname, "rb") as image1:
        s3.upload_fileobj(image1, "ece1779",
                          str(id) + "_ORI_" + new_image.filename)
    with open(fname_tr1, "rb") as image2:
        s3.upload_fileobj(image2, "ece1779",
                          str(id) + "_TR1_" + new_image.filename)
    with open(fname_tr2, "rb") as image3:
        s3.upload_fileobj(image3, "ece1779",
                          str(id) + "_TR2_" + new_image.filename)
    with open(fname_tr3, "rb") as image4:
        s3.upload_fileobj(image4, "ece1779",
                          str(id) + "_TR3_" + new_image.filename)

    os.remove(fname)
    os.remove(fname_tr1)
    os.remove(fname_tr2)
    os.remove(fname_tr3)

    query = ''' INSERT INTO images (userId,key1,key2,key3,key4) VALUES (%s,%s,%s,%s,%s)'''
    cursor.execute(query,
                   (id, new_image.filename, "TR1_" + new_image.filename,
                    "TR2_" + new_image.filename, "TR3_" + new_image.filename))
    cnx.commit()

    return "Success"
Example #35
0
    async def maps(self, ctx, zoom, *country):
        """Search at openstreetmap.org\n
        zoom: upclose, street, city, country, world
        Type: 'none' to skip"""
        user = ctx.message.author
        channel = ctx.message.channel
        country = "+".join(country)

        longitude = 0.0
        latitude = 0.0
        adressNum = 1
        limitResult  = 0    

        #Set tile zoom
        if zoom == 'upclose':
            zoomMap = 18  
        elif zoom == 'street':
            zoomMap = 16
        elif zoom == 'city':
            zoomMap = 11
        elif zoom == 'country':
            zoomMap = 8
        elif zoom == 'world':
            zoomMap = 2   
        else:
            zoomMap = 16

        #Get input data
        search = country
        await self.bot.say("` What city?`")
        response = await self.bot.wait_for_message(author=ctx.message.author)
        response = response.content.lower().strip().replace(" ", "+")
        if response == "none":
            pass
        else:
            search = search+","+response
        #http://wiki.openstreetmap.org/wiki/Nominatim
        await self.bot.say("` Enter your search term for the given location (building, company, address...)`")
        response = await self.bot.wait_for_message(author=ctx.message.author)
        response = response.content.lower().strip().replace(" ", "+")
        if response == "none":
            pass
        else:        
            search = search+","+response
        #print (search)

        #Get xml result from openstreetmap.org
        try:
            domain = "nominatim.openstreetmap.org"
            search = "/search?q={}&format=xml&polygon=1&addressdetails=1".format(search)
            #print(domain+search)
            conn = http.client.HTTPConnection(domain)
            conn.request("GET", search)
            r1 = conn.getresponse()
            data = r1.read()
            conn.close()
        except Exception as e:
            await self.bot.say("` Error getting GPS data.`")
            print("Error getting GPS data.")
            print(e)
            return  
        try:
            display_name = "-"
            soup = BeautifulSoup(data, 'html.parser')
            links = soup.findAll('place', lon=True)        
            results = len(links)
            if results == 0:
                await self.bot.say("`No results, try to rephrase`")  
                return
            #print("results:\n"+str(results))
            #print("display_name:\n"+display_name)
            #print("longitude/latitude:\n"+str(longitude)+","+str(latitude))
        except Exception as e:
            await self.bot.say("`Something went wrong while parsing xml data...`")
            print('parse XML failed')
            print(e)
            return
        await self.bot.send_typing(channel)
        if results > 1:
            list = "```erlang\nResults\n-\n"
            index = 0
            for link in links:
                index += 1
                list = list + "(" +str(index) + "): "+ link["display_name"] + "\n"
            list = list +"```` Enter result number...`"
            await self.bot.say(list)
            response = await self.bot.wait_for_message(author=ctx.message.author)
            input = response.content.lower().strip()
            #Set values for geotiler
            input = int(input)-1
            place_id = (links[input]["place_id"])
            display_name = (links[input]["display_name"])
            longitude = (links[input]['lon'])
            latitude = (links[input]['lat'])
        else:
            #Set values for geotiler        
            place_id = (links[0]["place_id"])
            display_name = (links[0]["display_name"])
            longitude = (links[0]['lon'])
            latitude = (links[0]['lat'])

        await self.bot.send_typing(channel)
        #print([latitude, longitude, zoomMap])

        map = geotiler.Map(center=(float(longitude), float(latitude)), zoom=zoomMap, size=(720, 720))
        map.extent
        image = await geotiler.render_map_async(map)
        image.save(MAP)
        await self.bot.send_typing(channel)
        #Add pointer and text.
        savedMap = Image(filename=MAP)
        pointer = Image(filename=POINTER)
        for o in COMPOSITE_OPERATORS:
            w = savedMap.clone()
            r = pointer.clone()
        with Drawing() as draw:
            draw.composite(operator='atop', left=311, top=311, width=90, height=90, image=r)
            draw(w)
            #Text
            draw.fill_color = Color("#7289DA")
            draw.stroke_color = Color("#5370D7")
            draw.stroke_width = 0.2
            draw.font_style = 'oblique'
            draw.font_size = 32
            splitDisplayName = display_name.split(',')
            #Object name/number
            draw.text(x=20, y=35, body=splitDisplayName[0])
            draw(w)
            del splitDisplayName[0]
            #Print location info on map.
            line0 = ""
            line1 = ""
            draw.font_size = 18
            for i in splitDisplayName:
                if len(str(line0)) > 30:
                    line1 = line1 + i + ","
                else:
                    line0 = line0 + i  + ","
            #line 0
            if len(str(line0)) > 2:            
                draw.text(x=15, y=60, body=line0)
                draw(w)
            #line 1
            if len(str(line1)) > 2:
                draw.text(x=15, y=80, body=line1)
                draw(w)
            w.save(filename=MAP)
        await self.bot.send_file(channel, MAP)
Example #36
0
def FileUpload():
    if 'uploadedfile' not in request.files:
        error_msg = 'Error: Missing Image!'
        return render_template('test.html',
                               title='Test Page',
                               error_msg=error_msg)

    image = request.files['uploadedfile']
    userID = request.form.get('userID',"")
    password = request.form.get('password',"")


    if userID =="" or password == "" or image.filename == "":
        error_msg = 'Error: All fields are required!'
        return render_template('test.html',
                               title='Test Page',
                               error_msg=error_msg)

    s3 = boto3.client('s3')

    imgname = os.path.join(tmp_path, image.filename)
    image.save(imgname)

    key1 = 'load_test/'+ userID + '/' + image.filename
    s3.upload_file(imgname, mybucket, key1)


    img = Image(filename=imgname)


    thumbnail_img = img.clone()
    thumbnail_img.resize(160, 200)
    thumbnail_imgname = os.path.join(tmp_path, 'thumbnail_'+image.filename)    
    thumbnail_img.save(filename=thumbnail_imgname)

    key_thm = 'load_test/'+ userID + '/' + 'thumbnail_'+image.filename
    s3.upload_file(thumbnail_imgname, mybucket, key_thm)


    flopped_img = img.clone()
    flopped_img.flop()
    flopped_imgname = os.path.join(tmp_path, 'flopped_'+image.filename)
    flopped_img.save(filename=flopped_imgname)

    key2 = 'load_test/'+ userID + '/' + 'flopped_'+image.filename
    s3.upload_file(flopped_imgname, mybucket, key2)



    flipped_img = img.clone()
    flipped_img.flip()
    flipped_imgname = os.path.join(tmp_path, 'flipped_'+image.filename)
    flipped_img.save(filename=flipped_imgname)

    key3 = 'load_test/'+ userID + '/' + 'flipped_'+image.filename
    s3.upload_file(flipped_imgname, mybucket, key3)


    rotated_img = img.clone()
    rotated_img.rotate(25, background=Color('green'))
    rotated_imgname = os.path.join(tmp_path, 'rotated_'+image.filename)
    rotated_img.save(filename=rotated_imgname)

    key4 = 'load_test/'+ userID + '/' + 'rotated_'+image.filename
    s3.upload_file(rotated_imgname, mybucket, key4)

    return redirect('/test')
med_path = img_path+"medium/"
small_path = img_path+"small/"

#Get list of files in directory
img_files = [ f for f in listdir(orig_path) if isfile(join(orig_path,f)) ]
print "Looking for images in: " + img_path
print "Found the following: " + str(img_files)

for f in img_files:
    if f.startswith("."):
        print "Not an image file: " + str(f)
    else:
        print "Processing image: "+f
        #Create image objects for small and medium using original large
        li = Image(filename=join(orig_path,f))
        mi = li.clone()
        si = mi.clone()

        print 'Original: '+str(mi.width)+'x'+str(mi.height)

        #Resize to med and small maintaining aspect ratio
        mi.transform(resize=str(med_size)+'x'+str(med_size)+'>')
        print 'Medium: '+str(mi.width)+'x'+str(mi.height)
        si.transform(resize=str(small_size)+'x'+str(small_size)+'>')
        print 'Small: '+str(si.width)+'x'+str(si.height)

        #Convert to JPEG if necessary and save as new file
        lf = join(large_path,f)
        if li.format != 'JPEG':
            li = li.convert('jpeg')
        li.save(filename=lf[:-3]+'jpg')
Example #38
0
def slice02():
    # Resize image to height (but do not change the aspect ratio)
    #
    req_width = 595
    req_height = 486
    baby_img = Image(filename=IMAGE_PATH + "baby_cc_sh.png")
    baby_img = resize_to_height(baby_img, req_height)

    # For this particular image, reflect image along vertical
    # axis to have face directed towards right of page.
    #
    baby_img.flop()

    # Create the the gradient transition that will later be used
    # in the opacity mask.
    #
    gradient_blob = create_gradient_blob(req_height, 75, gradient([
        (1.0, (0x00, 0x00, 0x00), (0xFF, 0xFF, 0xFF)), # top
    ]))
    gradient_img = Image(blob=gradient_blob)
    gradient_img.rotate(90.0)

    # When building the opacity mask, must start with an image
    # having a solid colour (i.e., begin as a "matte" image).
    # Without this, the later "composite_channel" operations
    # will simply not work.
    #
    opacity_mask = new_blank_png(req_width, req_height, color=Color('white'))
    left_field = new_blank_png(230, req_height, Color('white'))
    right_field = new_blank_png(290, req_height, Color('black'))
    opacity_mask.composite(left_field, 0, 0)
    opacity_mask.composite(right_field, 230+75, 0)
    opacity_mask.composite(gradient_img, 230, 0)

    # Now take the resized baby image and have it fade to the right
    # (in order to blend with later operations).
    #
    face_img = new_blank_png(req_width, req_height)
    face_img.composite(baby_img, 0, 0)
    face_img.composite_channel(channel='all_channels', image=opacity_mask, 
        operator='copy_opacity')

    # Bring in the illustrative image that will eventually be blended in
    # with the child's face.
    #
    accent_img = Image(filename = IMAGE_PATH + "funky_illustration.png")
    accent_img = resize_to_percent(accent_img, 60)
    accent_img = resize_to_height(accent_img, 486)

    cropped_img = accent_img.clone()
    cropped_img.crop(top=0, left=275, width=340, height=486)
    screen_img = new_blank_png(340, 486, color=Color('rgb(150,150,150)'))
    cropped_img.composite_channel(channel='all_channels', image=screen_img, 
        operator='screen')

    accent_img = new_blank_png(req_width, req_height)
    accent_img.composite_channel(channel='all_channels', image=cropped_img, 
        operator='over', left=255, top=0)
    accent_img.gaussian_blur(3.0, 1.0)

    opacity_mask = new_blank_png(req_width, req_height, color=Color('white'))
    left_field = new_blank_png(260, req_height, Color('black'))
    right_field = new_blank_png(290, req_height, Color('white'))
    opacity_mask.composite(left_field, 0, 0)
    opacity_mask.composite(right_field, 260+75, 0)
    gradient_img.rotate(180)
    opacity_mask.composite(gradient_img, 260, 0)
    accent_img.composite_channel(channel='all_channels', image=opacity_mask, 
        operator='copy_opacity')

    # Now layer the accent image with the child's face
    #
    accent_img.composite_channel(channel='all_channels', image=face_img,
        operator='over')
    full_slice = accent_img 

    # Finally, add the text field on the right of the image.
    #
    text_field = new_blank_png(212, req_height, color=Color('rgb(190,30,45)'))
    text_field_mask = new_blank_png(212, req_height, color=Color('rgb(220,220,220)'))
    text_field.composite_channel(channel='all_channels', image=text_field_mask, 
        operator='copy_opacity')
    full_slice.composite(text_field, 384, 0)

    draw = Drawing()
    draw.font = FONT_BOLD
    draw.font_size = 24
    draw.fill_color = Color('white')
    draw.text(395, 175, "Liam Mulcahy")
    draw.font = FONT_REGULAR
    draw.font_size = 20
    draw.text(395, 200, "Eyes to the Future")
    draw.font = FONT_ITALIC
    draw.font_size = 20
    draw.text(395, 250, 'How dreams of')
    draw.text(395, 275, 'future enterprise')
    draw.text(395, 300, 'success are')
    draw.text(395, 325, 'starting while still')
    draw.text(395, 350, 'in nappies!')
    draw(full_slice)
   
    # Done.
    # 
    return full_slice
def benchmark(source):
    """
    run through all tests, timing along the way

    timeit gets mentioned many times:
    http://docs.python.org/3.4/library/timeit.html
    """

    print("Testing moments: ") 
    start_time = time.time()

    print("making path:")
    step_time = time.time()    
    pic = Path(source)
    print(time.time() - step_time, "seconds")
    print("")

    
    print("loading path:")
    step_time = time.time()    
    img = pic.load()
    print(time.time() - step_time, "seconds")
    print("")

    #13.3232491016 seconds:
    ## print "make thumbs: (all)"
    ## step_time = time.time()    
    ## img.make_thumbs()
    ## print time.time() - step_time, "seconds"
    ## print ""

    ## print "removing thumbs: (all)"
    ## step_time = time.time()    
    ## shutil.rmtree("sized")
    ## print time.time() - step_time, "seconds"
    ## print ""

    #3.2377550602 seconds:
    ## print "make thumbs: (tiny)"
    ## step_time = time.time()    
    ## img.make_thumbs(["tiny"])
    ## print time.time() - step_time, "seconds"
    ## print ""

    ## print "removing thumbs: (tiny)"
    ## step_time = time.time()    
    ## shutil.rmtree("sized")
    ## print time.time() - step_time, "seconds"
    ## print ""

    #now break it down to steps:

    #0.000612020492554 seconds
    ## print "make thumbs dirs()"
    ## step_time = time.time()    
    ## img.make_thumb_dirs()
    ## print time.time() - step_time, "seconds"
    ## print ""

    ## print "removing thumbs dirs"
    ## step_time = time.time()    
    ## shutil.rmtree("sized")
    ## print time.time() - step_time, "seconds"
    ## print ""

    #0.00586199760437 seconds
    print("Open image with PIL: ") 
    step_time = time.time()
    image = PILImage.open(source)
    print(time.time() - step_time, "seconds")
    print("")

    print("show sizes: ") 
    step_time = time.time()
    print(image.size)
    print(time.time() - step_time, "seconds")
    print("")

    #0.56491112709 seconds
    print("Copy image buffer in PIL: ") 
    step_time = time.time()
    square = image.copy()
    print(time.time() - step_time, "seconds")
    print("")

    print("resize max: ") 
    step_time = time.time()
    pre_crop = resize_max(400, image.size[0], image.size[1])
    print(pre_crop)
    print(time.time() - step_time, "seconds")
    print("")
    
    #0.108213186264 seconds
    print("Square image (includes copy)") 
    step_time = time.time()
    square = img._square_image(square)    
    print(time.time() - step_time, "seconds")
    print("")

    #xl = 2880
    #3.53499007225 seconds
    print("thumbnail image (2880, ANTIALIAS)") 
    step_time = time.time()
    #image.thumbnail((xl,xl), PILImage.ANTIALIAS)                
    square.thumbnail((400,400), PILImage.ANTIALIAS)                
    print(time.time() - step_time, "seconds")
    print("")

    print("After thumbnail: ", image.size)
    print("")
    
    print("save thumb") 
    step_time = time.time()
    #image.save("test.jpg", "JPEG")
    square.save("test1.jpg", "JPEG")
    print(time.time() - step_time, "seconds")
    print("")

    print("PIL alternative (total)") 
    step_time = time.time()
    #img = resize_pil_orig(image, (400, 400))
    img = resize_pil(image, 400)
    print(time.time() - step_time, "seconds")
    print("")

    img.save("test.jpg", "JPEG")
    
    #shutil.rmtree("sized")

    #os.remove("test.jpg")

    from wand.image import Image

    #0.572014093399 seconds
    print("wand open file") 
    step_time = time.time()
    img = Image(filename=source) 
    print(time.time() - step_time, "seconds")
    print("")

    print("wand clone image") 
    step_time = time.time()
    clone = img.clone()
    print(time.time() - step_time, "seconds")
    print("")
    
    print("wand get dimensions") 
    step_time = time.time()
    width = img.width
    height = img.height
    ## with Image(filename=source) as img:
    ##     width = img.width
    ##     height = img.height
    print(width, height)
    print(time.time() - step_time, "seconds")
    print("")
        
    print("wand crop image") 
    step_time = time.time()
    box = calculate_box(img.width, img.height)
    img.crop(*box)
    print(time.time() - step_time, "seconds")
    print("")

    print("wand save image") 
    step_time = time.time()
    img.save(filename='temp3.jpg')
    print(time.time() - step_time, "seconds")
    print("")

    #THIS TAKES A *LONG* TIME!!!!
    #273.595574856 seconds
    #and will only make a difference for certain types of images
    #made no difference for one test image
    ## print "wand liquid rescale" 
    ## step_time = time.time()
    ## liquid = clone.liquid_rescale(400, 400)
    ## print time.time() - step_time, "seconds"
    ## print ""

    ## print "wand save liquid" 
    ## step_time = time.time()
    ## img.save(filename='temp-liquid.jpg')
    ## print time.time() - step_time, "seconds"
    ## print ""

    #0.238882064819 seconds
    print("epeg resize") 
    step_time = time.time()
    #TODO
    #consider using subprocess...
    #any benefits?
    #os.system("jhead -cmd \"jpegtran -progressive -rotate %s &i > &o\" %s" % (degrees, self.path))
    os.system("epeg -m %s %s temp-epeg.jpg" % (pre_crop, source)) 
    print(time.time() - step_time, "seconds")
    print("")


    ## print "Testing: " 
    ## step_time = time.time()    
    ## print source
    ## print time.time() - step_time, "seconds"
    ## print ""

    print("TOTAL TIME:") 
    print(time.time() - start_time, "seconds")
Example #40
0
		# Parse the box entry.
		boxFields = boxes[boxIndex].split()
		boxOctal = int(boxFields[0])
		boxLeft = int(boxFields[1])
		boxBottom = backgroundHeight -1 - int(boxFields[2])
		boxRight = int(boxFields[3])
		boxTop = backgroundHeight - 1 - int(boxFields[4])
		boxWidth = boxRight + 1 - boxLeft
		boxHeight = boxBottom + 1 - boxTop
		
		if characters[characterIndex] != '@':
			digitIndex = int(characters[characterIndex])
			#print boxFields[0], ' ', characters[characterIndex]
			if specialOne and characters[characterIndex] == '1':
				#print "here"
				digit = oneSpecialDigit.clone() 
				operator = 'difference'
			elif specialThree and characters[characterIndex] == '3':
				#print "here"
				digit = threeSpecialDigit.clone() 
				operator = 'multiply'
			elif specialFive and characters[characterIndex] == '5':
				digit = fiveSpecialDigit.clone()
				operator = 'difference'
			elif boxOctal == digitIndex and not (characters[characterIndex] in blatant) and not (boxFields[0] in blatant):
				digit = images[digitIndex].clone()
				operator = 'darken'
			else:
				digit = imagesColored[digitIndex].clone()
				operator = 'darken'
			fontWidth = digit.width
Example #41
0
def photowall(name):
  output_final = None

  previous_filename = None
  #for all the rows, 
  for row in xrange(LINES):
    print "Row ", row
    output_row = None
    row_width = 0
    #concatenate until the image width is reached
    img_count = 0
    while row_width < WIDTH:
      filename = get_next_file() if previous_filename is None else previous_filename
      previous_filename = None
      
      print img_count,
      if mime is not None:
	mimetype = mime.from_file(filename)
	if "symbolic link" in mimetype:
	  filename = os.readlink(filename)
	  mimetype = mime.from_file(filename)
	
	if not "image" in mimetype:
	  continue
	
	print "%s: %s" % (filename, mimetype)
	
      else:
	try:
	  print os.readlink(filename)
	except OSError:
	  print filename
	  
      img_count += 1
      image = Image(filename=filename)
      with image.clone() as clone:
	factor = float(LINE_HEIGHT)/clone.height
	clone.resize(height=LINE_HEIGHT, width=int(clone.width*factor))
	#if the new image makes an overflow
	if row_width + clone.width  > WIDTH:
	  #compute how many pixels will overflow
	  overflow = row_width + clone.width - WIDTH
	  will_fit = clone.width - overflow
	  
	  if DO_POLAROID and will_fit < MIN_CROP:
	    row_width = WIDTH
	    continue
	  
	  if DO_WRAP:
	    with clone.clone() as next_img:
	      next_img.crop(will_fit+1, 0, width=overflow, height=LINE_HEIGHT)
	      tmp = tempfile.NamedTemporaryFile(delete=False, suffix=IMG_FORMAT_SUFFIX)
	      tmp.close()
	      next_img.save(filename=tmp.name)
	      previous_filename = tmp.name
	  clone.crop(0, 0, width=will_fit, height=LINE_HEIGHT)
	
	if DO_POLAROID:
	  details = get_file_details(filename)
	  clone = do_polaroid(clone, details)
	
	tmp = tempfile.NamedTemporaryFile(delete=False, suffix=IMG_FORMAT_SUFFIX)
	tmp.close()
	clone.save(filename=tmp.name)
	
	row_width += clone.width
	if output_row is not None:
	  do_append(output_row.name, tmp.name)
	  os.unlink(tmp.name)
	else:
	  output_row = tmp
	
    if output_final is not None:
      do_append(output_final.name, output_row.name, underneath=True)
      os.unlink(output_row.name)
    else:
      output_final = output_row
  final_name = tempfile.gettempdir()+"/"+name+IMG_FORMAT_SUFFIX
  os.rename(output_final.name, final_name)
  
  return final_name 
Example #42
0
#sendtweet = True
if sendtweet:
    print 'Updating ' + tmpfile
    writetmpfile(printpercent)
    print 'Message length: ' + str(len(status_msg))
    print 'Sending tweet!'
    print '---------------------'
    print status_msg
    print '---------------------'
    api = TwitterAPI(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
    #Grab picture from web cam
    r = requests.get('http://' + host + ':8080/?action=snapshot')
    picdata = r.content
    img = Image(blob=picdata)
    s = img.clone()
    l = logo.clone()
    t = thermo.clone()
    l.transparentize(0.30)
    with Drawing() as draw:
	#Draw Octoprint logo in the upper left corner
	draw.composite(operator='dissolve', left=525, top=395,
               width=l.width, height=l.height, image=l)
	#Draw transparent black rectangle on the bottom of picture
	draw.fill_color = Color('rgba(0, 0, 0, 0.5)')
	draw.rectangle(left=0, top=400, right=500, bottom=480, radius=5)
	#Insert thermometer pic over transparent rectangle
	draw.composite(operator='dissolve', left=7, top=409,
               width=t.width, height=t.height, image=t)
	draw.fill_color = Color('rgba(100, 100, 100, 0.8)')
	draw.rectangle(left=55, top=413, right=57, bottom=467)
Example #43
0
def photowall(name):
  output_final = None

  previous_filename = None
  #for all the rows,
  row = -1
  done = False
  while not done:
    row += 1
    if PARAMS["LINES"] and row >= PARAMS["LINES"]: break
    
    output_row = None
    row_width = 0
    img_count = 0
    
    #concatenate until the image width is reached
    while not done and row_width < PARAMS["WIDTH"]:
      # get a new file, or the end of the previous one, if it was split
      filename = get_next_file() if previous_filename is None else previous_filename
      
      if filename is None:
        print("All photos have been consumed.")
        done = True
        continue
      
      mimetype = None
      previous_filename = None
      
      # get a real image
      if mime is not None:
        mimetype = mime.from_file(filename)
        if "symbolic link" in str(mimetype):
          filename = os.readlink(filename)
          mimetype = mime.from_file(filename)
        
        if not "image" in str(mimetype):
          continue
      else:
        try:
          filename = os.readlink(filename)
        except OSError:
          pass
      
      updateCB.newImage(row, img_count, filename)
      img_count += 1
      # resize the image
      image = Image(filename=filename)
      with image.clone() as clone:
        factor = float(PARAMS["LINE_HEIGHT"]) / clone.height

        print("Resize image {} of a factor {:.2f}".format(filename, factor))
        clone.resize(height=PARAMS["LINE_HEIGHT"], width=int(clone.width*factor))
        
        #if the new image makes an overflow
        if row_width + clone.width > PARAMS["WIDTH"]:
          print("Doesn't fit.")
          #compute how many pixels will overflow
          overflow = row_width + clone.width - PARAMS["WIDTH"]
          will_fit = clone.width - overflow
          
          if will_fit < PARAMS["CROP_SIZE"]:
            row_width = PARAMS["WIDTH"]
            previous_filename = filename
            continue
          
          if PARAMS["DO_WRAP"]:
            with clone.clone() as next_img:
              next_img.crop(will_fit+1, 0, width=overflow, height=PARAMS["LINE_HEIGHT"])
              tmp = tempfile.NamedTemporaryFile(delete=False, suffix=PARAMS["IMG_FORMAT_SUFFIX"])
              tmp.close()
              next_img.save(filename=tmp.name)
              previous_filename = tmp.name
          clone.crop(0, 0, width=will_fit, height=PARAMS["LINE_HEIGHT"])
        
        if PARAMS["DO_POLAROID"]:
          clone = do_polaroid(clone, filename)
        
        tmp = tempfile.NamedTemporaryFile(delete=False, suffix=PARAMS["IMG_FORMAT_SUFFIX"])
        tmp.close()
        clone.save(filename=tmp.name)
        
        row_width += clone.width
        if output_row is not None:
          do_append(output_row.name, tmp.name)
          os.unlink(tmp.name)
        else:
          output_row = tmp
        
        updateCB.updLine(row, output_row.name)
        updateCB.checkPause()
        
        if updateCB.stopRequested():
          break
    else:
      if output_final is not None:
        do_append(output_final.name, output_row.name, underneath=True)
        os.unlink(output_row.name)
      else:
        output_final = output_row
      updateCB.newFinal(output_final.name)
  
  if output_final is not None:
    shutil.move(output_final.name, name)
    updateCB.finished(name)
  else:
    updateCB.finished(None)
    
  return name 
Example #44
0
from wand.image import Image

fileName = input("Input a file name with its extension: ")
img = Image(filename=fileName)

height = img.height
width = img.width

with img.clone() as resize:
    resize.resize(int(width * 0.05), int(height * 0.05), 'box', 1)
    resize.resize(width, height, 'box', 1)
    resize.save(filename='pixalated.jpg')
    print("Completed.")
Example #45
0
class TestImageRoute(FlaskTestCase):
    bucket = "wtf"

    def setUp(self):
        super(TestImageRoute, self).setUp()
        with Color('red') as bg:
            self.image = Image(width=1920, height=1080, background=bg)

        # let's clear the cache
        params = OrderedDict()
        params['w'] = 100
        params['h'] = 100
        giraffe.get_file_or_404.invalidate(self.bucket, "redbull.jpg")
        giraffe.get_file_with_params_or_404.invalidate(self.bucket,
                                                       "redbull.jpg",
                                                       "{}/redbull_w100_h100.jpg".format(giraffe.CACHE_DIR),
                                                       params,
                                                       False)

    @mock.patch('giraffe.s3')
    def test_image_doesnt_exist(self, s3):
        s3.get.side_effect = make_httperror(404)
        r = self.app.get("/{}/redbull.jpg".format(self.bucket))
        self.assertEqual(r.status_code, 404)

    @mock.patch('giraffe.s3')
    def test_image_resize_original_doesnt_exist(self, s3):
        s3.get.side_effect = make_httperror(404)
        r = self.app.get("/{}/redbull.jpg?w=100&h=100".format(self.bucket))
        self.assertEqual(r.status_code, 404)

    def test_image_has_no_extension(self):
        r = self.app.get("/{}/foo".format(self.bucket))
        self.assertEqual(r.status_code, 404)

    def test_bucket_only(self):
        r = self.app.get("/{}".format(self.bucket))
        self.assertEqual(r.status_code, 404)

    # original image as jpeg:
    @mock.patch('giraffe.s3')
    def test_jpeg_exists(self, s3):
        obj = mock.Mock()
        obj.content = self.image.make_blob("jpeg")
        obj.headers = {'content-type': 'image/jpeg'}
        s3.get.return_value = obj

        r = self.app.get("/{}/redbull.jpg".format(self.bucket))
        self.assertEqual(r.status_code, 200)
        content_type = r.headers.get("content-type")
        self.assertEqual(content_type, "image/jpeg")
        self.assertEqual(Image(blob=r.data).format, 'JPEG')

    @mock.patch('giraffe.s3')
    def test_jpeg_exists_but_format_as_png(self, s3):
        obj = mock.Mock()
        obj.content = self.image.make_blob("jpeg")
        obj.headers = {'content-type': 'image/jpeg'}

        s3.get.side_effect = [obj, make_httperror(404)]
        r = self.app.get("/{}/redbull.jpg?fm=png".format(self.bucket))
        self.assertEqual(r.status_code, 200)
        content_type = r.headers.get("content-type")
        self.assertEqual(content_type, "image/png")
        args, kwargs = s3.upload.call_args
        self.assertEqual(args[0], "giraffe/redbull.png")
        self.assertEqual(kwargs['content_type'], "image/png")
        self.assertEqual(Image(blob=r.data).format, 'PNG')

    @mock.patch('giraffe.s3')
    def test_image_exists_but_needs_to_be_resized(self, s3):
        obj = mock.Mock()
        obj.content = self.image.make_blob("jpeg")
        # we'll call s3.get twice, the first time we'll get the original file, the second time
        # we'll be calling to check for the specific version of the object.
        s3.get.side_effect = [obj, make_httperror(404)]
        r = self.app.get("/{}/redbull.jpg?w=100&h=100".format(self.bucket))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(Image(blob=r.data).size, (100, 100))

    @mock.patch('giraffe.s3')
    def test_image_exists_but_user_wants_unnecessary_resize(self, s3):
        obj = mock.Mock()
        obj.content = self.image.make_blob("jpeg")
        # we'll call s3.get twice, the first time we'll get the original file, the second time
        # we'll be calling to check for the specific version of the object.
        s3.get.side_effect = [obj, make_httperror(404)]
        r = self.app.get("/{}/redbull.jpg?w=1920&h=1080".format(self.bucket))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(Image(blob=r.data).size, (1920, 1080))

    @mock.patch('giraffe.s3')
    def test_image_exists_and_has_already_been_resized(self, s3):
        obj = mock.Mock()
        obj.content = self.image.make_blob("jpeg")
        obj2 = mock.Mock()
        with self.image.clone() as img:
            img.resize(100, 100)
            obj2.content = img.make_blob("jpeg")
        # we'll call s3.get twice, the first time we'll get the original file, the second time
        # we'll be calling to check for the specific version of the object.
        s3.get.side_effect = [obj, obj2]
        r = self.app.get("/{}/redbull.jpg?w=100&h=100".format(self.bucket))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(Image(blob=r.data).size, (100, 100))

    # original image as png:
    @mock.patch('giraffe.s3')
    def test_png_exists(self, s3):
        obj = mock.Mock()
        obj.content = self.image.make_blob("png")
        obj.headers = {'content-type': 'image/png'}
        s3.get.return_value = obj
        r = self.app.get("/{}/redbull.png".format(self.bucket))
        self.assertEqual(r.status_code, 200)
        content_type = r.headers.get("content-type")
        self.assertEqual(content_type, "image/png")
        self.assertEqual(Image(blob=r.data).format, 'PNG')

    @mock.patch('giraffe.s3')
    def test_png_exists_but_needs_format_as_jpg(self, s3):
        obj = mock.Mock()
        obj.content = self.image.make_blob("png")
        s3.get.side_effect = [obj, make_httperror(404)]
        r = self.app.get("/{}/redbull.png?fm=jpg".format(self.bucket))
        self.assertEqual(r.status_code, 200)
        content_type = r.headers.get("content-type")
        self.assertEqual(content_type, "image/jpeg")
        args, kwargs = s3.upload.call_args
        self.assertEqual(args[0], "giraffe/redbull.jpg")
        self.assertEqual(kwargs['content_type'], "image/jpeg")
        self.assertEqual(Image(blob=r.data).format, 'JPEG')

    @mock.patch('giraffe.s3')
    def test_png_exists_but_needs_format_as_jpeg(self, s3):
        # yep, if someone uses "fm=jpeg" instead of "fm=jpg" it should still work
        obj = mock.Mock()
        obj.content = self.image.make_blob("png")
        s3.get.side_effect = [obj, make_httperror(404)]
        r = self.app.get("/{}/redbull.png?fm=jpeg".format(self.bucket))
        self.assertEqual(r.status_code, 200)
        content_type = r.headers.get("content-type")
        self.assertEqual(content_type, "image/jpeg")
        self.assertEqual(Image(blob=r.data).format, 'JPEG')

    @mock.patch('giraffe.s3')
    def test_png_exists_but_needs_to_be_resized(self, s3):
        obj = mock.Mock()
        obj.content = self.image.make_blob("png")
        # we'll call s3.get twice, the first time we'll get the original file, the second time
        # we'll be calling to check for the specific version of the object.
        s3.get.side_effect = [obj, make_httperror(404)]
        r = self.app.get("/{}/redbull.png?w=100&h=100".format(self.bucket))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(Image(blob=r.data).size, (100, 100))

    @mock.patch('giraffe.s3')
    def test_png_exists_but_user_wants_unnecessary_resize(self, s3):
        obj = mock.Mock()
        obj.content = self.image.make_blob("png")
        # we'll call s3.get twice, the first time we'll get the original file, the second time
        # we'll be calling to check for the specific version of the object.
        s3.get.side_effect = [obj, make_httperror(404)]
        r = self.app.get("/{}/redbull.png?w=1920&h=1080".format(self.bucket))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(Image(blob=r.data).size, (1920, 1080))

    @mock.patch('giraffe.s3')
    def test_png_exists_and_has_already_been_resized(self, s3):
        obj = mock.Mock()
        obj.content = self.image.make_blob("png")
        obj2 = mock.Mock()
        with self.image.clone() as img:
            img.resize(100, 100)
            obj2.content = img.make_blob("png")
        # we'll call s3.get twice, the first time we'll get the original file, the second time
        # we'll be calling to check for the specific version of the object.
        s3.get.side_effect = [obj, obj2]
        r = self.app.get("/{}/redbull.jpg?w=100&h=100".format(self.bucket))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(Image(blob=r.data).size, (100, 100))

    # original image as bmp:
    @mock.patch('giraffe.s3')
    def test_bmp_exists(self, s3):
        obj = mock.Mock()
        obj.content = self.image.make_blob("bmp")
        obj.headers = {'content-type': 'image/bmp'}
        s3.get.return_value = obj
        r = self.app.get("/{}/redbull.bmp".format(self.bucket))
        self.assertEqual(r.status_code, 200)
        content_type = r.headers.get("content-type")
        self.assertEqual(content_type, "image/bmp")
        self.assertEqual(Image(blob=r.data).format, 'BMP')

    @mock.patch('giraffe.s3')
    def test_masquerading_gif_converted_to_jpeg(self, s3):
        """
        Assuming that a user uploads a gif file but it is named "foo.jpg"
        that gif can be resized but it won't resize correctly if we don't
        convert the format of the file from gif to jpg.

        """
        obj = mock.Mock()
        self.image = Image(width=160, height=120)
        obj.content = self.image.make_blob("gif")
        obj.headers = {'content-type': 'image/jpeg'}
        s3.get.side_effect = [obj, make_httperror(404)]
        r = self.app.get("/{}/masquerading_gif.jpg?w=120&h=120".format(self.bucket))
        self.assertEqual(r.status_code, 200)
        content_type = r.headers.get("content-type")
        self.assertEqual(content_type, "image/jpeg")
        self.assertEqual(Image(blob=r.data).format, 'JPEG')
        self.assertEqual(Image(blob=r.data).size, (120, 120))

    @mock.patch('giraffe.s3')
    def test_giant_image_resize(self, s3):
        obj = mock.Mock()
        self.image = Image(width=12402, height=8770)
        obj.content = self.image.make_blob("jpg")
        obj.headers = {'content-type': 'image/jpeg'}
        s3.get.side_effect = [obj, make_httperror(404)]
        r = self.app.get("/{}/giant.jpg?w=120&h=120".format(self.bucket))
        self.assertEqual(r.status_code, 200)
        content_type = r.headers.get("content-type")
        self.assertEqual(content_type, "image/jpeg")
        self.assertEqual(Image(blob=r.data).size, (120, 120))

    @mock.patch('giraffe.s3')
    def test_ico_masquerading_as_jpg(self, s3):
        obj = mock.Mock()
        image = Image(width=16, height=16)
        obj.content = image.make_blob('ico')
        obj.headers = {'content-type': 'image/jpeg'} # this is what S3 tells us =(
        s3.get.side_effect = [obj, make_httperror(404)]
        r = self.app.get("/{}/giant.jpg?w=64&h=64".format(self.bucket))
        self.assertEqual(r.status_code, 200)
        content_type = r.headers.get("content-type")
        self.assertEqual(content_type, "image/jpeg")
        self.assertEqual(Image(blob=r.data, format='jpeg').size, (64, 64))

    @mock.patch('giraffe.s3')
    def test_ico_masquerading_as_jpg_big(self, s3):
        obj = mock.Mock()
        image = Image(width=16, height=16)
        obj.content = image.make_blob('ico')
        obj.headers = {'content-type': 'image/jpeg'} # this is what S3 tells us =(
        s3.get.side_effect = [obj, make_httperror(404)]
        r = self.app.get("/{}/giant.jpg?w=400&h=400".format(self.bucket))
        self.assertEqual(r.status_code, 200)
        content_type = r.headers.get("content-type")
        self.assertEqual(content_type, "image/jpeg")
        self.assertEqual(Image(blob=r.data, format='jpeg').size, (400, 400))
Example #46
0
    # make text image
    textimg = Image(width=w, height=h)
    draw.gravity = 'center'
    draw.fill_color = Color('white')
    draw.text(0, 0, text)
    draw(textimg)

    # make text with gradient
    textimg.composite_channel(channel, gradient, 'in')

    # curve it
    textimg.distort('arc', [120], True)

    # add shadow
    shadowimg = textimg.clone()
    shadowimg.background_color = Color('black')
    shadow(shadowimg, 100, 2, 4, 4)

    # composite all
    canvas = Image(width=textimg.width, height=textimg.height,
                   background=Color('white'))
    canvas.composite(shadowimg, 0, 0)
    canvas.composite(textimg, 0, 0)
    canvas.save(filename='sample39.png')

    gradient.destroy()
    textimg.destroy()
    shadowimg.destroy()
    canvas.destroy()
Example #47
0
source_to_augmented = {'/mnt/mass_2x_padding_dataset_train': '/mnt/2x_augmented_train',
                       '/mnt/mass_2x_padding_dataset_test': '/mnt/2x_augmented_test',
                       '/mnt/mass_2x_padding_dataset_val': '/mnt/2x_augmented_val'}


# In[198]:

for directory in source_to_augmented:
    files = listdir(directory)
    N = len(files)
    for i, filepath in enumerate(files):
        img = Image(filename=directory+'/'+filepath)
        [name, ext] = filepath.split('.')
        for t in range(5):
            z = img.clone()
            if t != 0:
                rotate(z)
            resize_shortest(z)
            for tt in range(5):
                new_path = '%s/%s_%i_%i.%s' % (source_to_augmented[directory], name, t, tt, ext)
                n = z.clone()
                random_crop(n)
                n.save(filename=new_path)
        print 'Done %i/%i' % (i,N)


# In[ ]:


def sliceImage(source_name,
               slice_size,
               slice_name,
               slice_format,
               binary,
               chunk_size,
               output_directory=".",
               generate_index_file=True,
               compression_quality=100):

    if not os.path.exists(output_directory):
        os.makedirs(output_directory)
    else:
        #Delete all existing files
        for files in os.listdir(output_directory):
            if files.startswith(slice_name):
                os.remove(os.path.join(output_directory, files))

    output_name = '{name}_{x}_{y}.{format}'.format(
        name=slice_name,
        format=slice_format,
        x='{x}',
        y='{y}')




    info_name = '{name}.slice'.format(name=slice_name)
    print('Opening image')

    image = Image(filename=source_name)
    slice_size = int(slice_size)
    width = int(image.width)
    height = int(image.height)

    vertical_slices = int(math.ceil(height / slice_size))
    horizontal_slices = int(math.ceil(width / slice_size))

    slices = []

    for x in range(0, horizontal_slices):
        for y in range(0, vertical_slices):
            slice = Slice(x * slice_size,
                          y * slice_size,
                          min(width - x * slice_size, slice_size),
                          min(height - y * slice_size, slice_size))
            slice.output_name = output_name.format(x=x, y=y)
            slices.append(slice)

    f = open(os.path.join(output_directory, info_name), 'w')

    chunk_name = '{name}_{id}.chunk'.format(name=slice_name,
                                            id='{id}')
    chunks_number = int(math.ceil(len(slices) / chunk_size));

    if binary:
        f.write('{width} {height} 0 {chunks} {slices}\n'.format(width=width,
                                                     height=height,
                                                     slices=len(slices),
                                                     chunks=chunks_number))
    else:
        f.write('{width} {height} {slices}\n'.format(width=width,
                                                     height=height,
                                                     slices=len(slices)))

    index_f = None
    if generate_index_file:
        index_f = open(os.path.join(output_directory, 'index.idx.xml'), 'w')
        index_f.write('<?xml version="1.0" encoding="UTF-8"?>\n<directory>\n')
        index_f.write('\t<file><name>{0}</name></file>\n'.format(info_name))

    if binary:
        for i in range(0, chunks_number):
            chunk_file_name = chunk_name.format(id=i)
            f.write('{id} {chunk}\n'.format(id=i,
                                            chunk=chunk_file_name))
            index_f.write('\t<file><name>{0}</name></file>\n'.format(chunk_file_name))


    slice_id = 0
    chunk_id = -1
    chunk_file_out = None

    for s in slices:
        cur_chunk_id = slice_id // chunk_size
        if binary and cur_chunk_id != chunk_id:
            chunk_id = cur_chunk_id
            if chunk_file_out is not None:
                chunk_file_out.close()
            chunk_file_name = chunk_name.format(id=chunk_id)
            chunk_file_out = open(os.path.join(output_directory, chunk_file_name), 'wb')
        slice_id += 1

        cropped = image.clone()
        cropped.crop(s.x,
                     s.y,
                     width=s.width,
                     height=s.height)
        cropped.compression_quality = int(compression_quality)
        print('Saving: {0}'.format(s.output_name))
        output_slice_name = os.path.join(output_directory, s.output_name)
        cropped.save(filename=output_slice_name)

        if binary:
            position = chunk_file_out.tell()
            size = 0

            slice_file = open(output_slice_name, mode='rb')
            chunk_file_out.write(slice_file.read())
            slice_file.close()

            size = chunk_file_out.tell() - position

            f.write('{x} {y} {width} {height} {chunk} {position} {length}\n'.format(
                x=s.x, y=s.y, width=s.width, height=s.height,
                chunk=chunk_id, position=position, length=size
            ))
            os.remove(output_slice_name)

        else:
            f.write('{x} {y} {width} {height} {name}\n'.format(
                x=s.x, y=s.y, width=s.width, height=s.height,
                name=s.output_name
            ))
            if generate_index_file:
                index_f.write('\t<file><name>{0}</name></file>\n'.format(s.output_name))

    if generate_index_file:
        index_f.write('</directory>\n')
Example #49
0
def random_wall(real_target_filename):
  name = real_target_filename

  filename = name.rpartition("/")[-1]
  name, _, ext = filename.rpartition(".")

  target_filename = "{}/{}.2.{}".format(tempfile.gettempdir(), name, ext)
  
  try:
    #remove any existing tmp file
    os.unlink(target_filename)
  except OSError:
    pass
  
  if os.path.exists(target_filename):
    #if source already exist, build up on it
    os.system("cp %s %s" % (target_filename, real_target_filename))

  
  print("Target file is %s" % real_target_filename )
  target = None
  if mime is not None:
    try:
      mimetype = mime.from_file(target_filename)
      if "symbolic link" in mimetype:
        filename = os.readlink(target_filename)
        mimetype = mime.from_file(target_filename)
        
      if "image" in mimetype:
        target = Image(filename=target_filename)
      
    except IOError:
      pass

  if target is None:
    height = PARAMS["LINES"] * PARAMS["LINE_HEIGHT"]
    
    do_blank_image(height, PARAMS["WIDTH"], target_filename)
    target = Image(filename=target_filename)
  
  cnt = 0
  while True:
    updateCB.checkPause()
    if updateCB.stopRequested():
      break
      
    filename = get_next_file()
    print(filename)
    
    img = Image(filename=filename)
    with img.clone() as clone:
      if not PARAMS["DO_NOT_RESIZE"]:
        factor = float(PARAMS["LINE_HEIGHT"])/clone.height
        
        print("Resize image {} of a factor {}".format(filename, factor))
        clone.resize(width=int(clone.width*factor), height=int(clone.height*factor))

      do_polaroid_and_random_composite(target_filename, target, clone, filename)
      updateCB.checkPause()
      if updateCB.stopRequested():
        break
      updateCB.newImage(row=cnt, filename=filename)
      updateCB.newFinal(target_filename)
      os.system("cp %s %s" % (target_filename, real_target_filename))
      cnt += 1
      
    updateCB.checkPause()
    if updateCB.stopRequested():
      break  
    time.sleep(PARAMS["SLEEP_TIME"])
    updateCB.checkPause()
    if updateCB.stopRequested():
      break
Example #50
0
def process_file(user_id, new_file):
    store_base = "I" + datetime.datetime.now().strftime(
        '%Y-%m-%d-%H-%M-%S') + '-' + str(uuid.uuid4())
    store_ext = filename_extension(new_file.filename)
    original_pic = store_base + '.' + store_ext
    # original_store_path = os.path.join("app\\static\\User_Images", store_base + "." + store_ext)
    # new_file.save(original_store_path)

    # Get the service client and upload to the s3 bucket
    s3 = boto3.client('s3', region_name='us-east-1')
    file_key_name = str(user_id) + '/' + original_pic
    s3.upload_fileobj(new_file,
                      s3_bucketName,
                      file_key_name,
                      ExtraArgs={"ContentType": "image/jpeg"})

    try:
        cnx = get_db()
        cursor = cnx.cursor()

        # create a new tuple for the photo and store the
        query = "INSERT INTO photo (user_id) VALUES (%s)"
        cursor.execute(query, (user_id, ))

        # get id of newly created tuple
        query = "SELECT LAST_INSERT_ID()"
        cursor.execute(query)

        row = cursor.fetchone()

        photo_id = row[0]
        # store the path to the original image
        query = "INSERT INTO storedphoto (filename,type_id,photo_id) VALUES (%s,%s,%s)"

        cursor.execute(query, (original_pic, TYPE_ORIGINAL, photo_id))

        # get the url of the upload image
        url = s3.generate_presigned_url('get_object',
                                        Params={
                                            'Bucket': s3_bucketName,
                                            'Key': file_key_name
                                        })

        # create thumbnail
        img = Image(file=urllib.request.urlopen(url))
        i = img.clone()
        i.resize(80, 80)
        bytes_io_file = BytesIO(i.make_blob('JPEG'))
        thumbail_pic = store_base + "_thumb." + store_ext
        # thumbnail_store_path = os.path.join("app\\static\\User_Images", store_base + "_thumb." + store_ext)
        # i.save(filename=thumbnail_store_path)
        # Get the service client and upload to the s3 bucket
        s3 = boto3.client('s3', region_name='us-east-1')
        file_key_name_thumb = str(user_id) + '/' + thumbail_pic
        s3.upload_fileobj(bytes_io_file,
                          s3_bucketName,
                          file_key_name_thumb,
                          ExtraArgs={"ContentType": "image/jpeg"})

        # store path to thumbnail
        query = "INSERT INTO storedphoto (filename,type_id,photo_id) VALUES (%s,%s,%s)"
        cursor.execute(query, (thumbail_pic, TYPE_THUMBNAIL, photo_id))

        # with open(original_store_path, 'rb') as f:
        #     image_bytes = f.read()
        di = img.clone()
        df_pic = store_base + "_df." + store_ext
        # df_store_path = os.path.join("app\\static\\User_Images", store_base + "_df." + store_ext)
        detect_faces_and_save(di, user_id, df_pic)

        query = "INSERT INTO storedphoto (filename,type_id,photo_id) VALUES (%s,%s,%s)"
        cursor.execute(query, (df_pic, TYPE_FACE_DETECTED, photo_id))

        cursor.close()

        cnx.commit()

    except Exception as e:
        raise e
Example #51
0
File: card.py Project: Ja-vi/pnp
class Card(object):
	"""Individual object containing an image and actions to manipulate it.
	Posible kwargs to __init__ are filename, file, image, blob. it will load the image from there"""
	def __init__(self, *args, **kwargs):
		"""Init a new cards with *img* being a wand.image.Image object"""
		self.img = Image(*args, **kwargs)
		self.border = None
		self.changed = True
		self.pixmap()

	def __del__(self):
		self.img.destroy()

	def format(self, fmt=None):
		if fmt is None:
			return self.img.format.lower()
		else:
			self.img.format = fmt

	@set_changed
	def resize(self, width, height, newres=300):
		"""Resize this card to (*width*, *height*) inches, with a resolution of *newres*"""
		self.img.transform(resize=str(int(width*newres)) + "x" + str(int(height*newres)) + "!")
		self.img.reset_coords()
		self.img.resolution = (newres, newres)
		return newres

	def width(self):
		return self.img.size[0]

	def height(self):
		return self.img.size[1]

	def reset_coords(self):
		self.img.reset_coords()

	@set_changed
	def set_border(self, border):
		"""Set a new *border* for this card"""
		if self.border is not None:
			self.del_border()
		self.border = border
		with Color(self.border.colour) as colour:
			self.img.border(colour, self.border.wide, self.border.wide)

	@set_changed
	def crop(self, *args, **kwargs):
		"""Crop this card *top*, *bottom*, *left* and *right* pixels"""
		w, h = self.img.size
		if "right" in kwargs:
			kwargs["right"] = w - kwargs["right"]
		if "bottom" in kwargs:
			kwargs["bottom"] = h - kwargs["bottom"]
		self.img.crop(*args, **kwargs)
		self.reset_coords()

	def del_border(self):
		"""Remove the border of this card"""
		if self.border is not None:
			w = self.border.wide
			self.crop(top=w, bottom=w, right=w, left=w)
			self.border = None
			self.changed = True

	@set_changed
	def trim(self, fuzz=13):
		self.img.trim(fuzz=fuzz)
		self.reset_coords()

	def save_as(self, filename):
		"""Save this card in a file named *filename*"""
		self.img.save(filename = filename)

	def split(self, rows, cols, separation=0):
		"""Divide this cards in *rows* by *cols* cards, and returns a list"""
		width, hight = self.img.size
		width, hight = (int(width), int(hight))
		cardWidth = (width - separation * (cols-1)) / cols
		cardHight = (hight - separation * (rows-1)) / rows
		res = []
		for i in range(rows):
			for j in range(cols):
				with self.img.clone() as clon:
					clon.crop(top=i*cardHight+i*separation, width=cardWidth, left=j*cardWidth+j*separation, height=cardHight)
					clon.reset_coords()
					res.append(Card(image=clon))
		return res

	@set_changed
	def round_corners(self):
		"""Round the corners of the card (setting them to alpha)"""
		pass

	def clone(self):
		c = Card(image=self.img.clone())
		c.border = self.border
		return c

	def pixmap(self):
		"""Update and returns the pixmap (QPixmap) of the contained image"""
		if self.changed:
			self._pixmap = QPixmap(QImage.fromData(self.img.make_blob("jpg"), "jpg"))#self.img.format))
			self.changed = False
		return self._pixmap