Example #1
0
 def render_image_background(self, image_path, opacity=True):
     image = Image(image_path)
     if type(opacity) is int:
         image.opacity(opacity)
     elif opacity is True:
         image.opacity(50)
     return image
Example #2
0
 def test_fromblob(self):
     with open('../example/X.jpg', 'rb') as f:
         data = f.read()
         b = Blob(data)
         img = Image(b)
         img.write('X2.jpg')
         self.assertEqual(type(img), Image)
Example #3
0
def pgmagick_image(source, **options):
    """
    Try to open the source file using pgmagick, ignoring any errors.

    """
    # Use a StringIO wrapper because if the source is an incomplete file like
    # object, PIL may have problems with it. For example, some image types
    # require tell and seek methods that are not present on all storage
    # File objects.
    #    import ipdb; ipdb.set_trace()
    if not source:
        return
    source.open()  # If tried by a previous source_generator, will be closed
    source = StringIO(source.read())
    try:
        blob = Blob(source.read())
        image = Image(blob)
    except Exception:
        logger.exception("unable to read image to create thumbnail")
        return

    if not image.isValid():
        return

    return convertGMtoPIL(image)
 def test_scale_jpeg(self):
     img = api.Image((400, 400), 'blue')
     img.write(self.tmp_filename_jpg)
     img2 = Image(Blob(open(self.tmp_filename_jpg).read()),
                  Geometry(200, 200))
     img2.scale('200x200')
     img2.write(self.tmp_filename_jpg)
 def _watermark(self, image, watermark_path, opacity, size, position_str):
     with open(watermark_path, "rb") as watermark_file:
         watermark = self.get_image(watermark_file)
     image_size = self.get_image_size(image)
     layer = Image(Geometry(image_size[0], image_size[1]), "transparent")
     if opacity < 1:
         self._reduce_opacity(watermark, opacity)
     if not size:
         mark_size = self.get_image_size(watermark)
     else:
         mark_size = tuple(
             self._get_new_watermark_size(size, self.get_image_size(watermark))
         )
         options = {
             "crop": "center",
             "upscale": mark_size > self.get_image_size(watermark),
         }
         watermark = self.scale(watermark, mark_size, options)
         watermark = self.crop(watermark, mark_size, options)
     if position_str == "tile":
         for x_pos in range(0, image_size[0], mark_size[0]):
             for y_pos in range(0, image_size[1], mark_size[1]):
                 layer.composite(watermark, x_pos, y_pos, CoOp.OverCompositeOp)
     else:
         position = self._define_watermark_position(
             position_str, image_size, mark_size
         )
         layer.composite(watermark, position[0], position[1], CoOp.OverCompositeOp)
     image.composite(layer, 0, 0, CoOp.OverCompositeOp)
     return image
def pgmagick_image(source, **options):
    """
    Try to open the source file using pgmagick, ignoring any errors.

    """
    # Use a StringIO wrapper because if the source is an incomplete file like
    # object, PIL may have problems with it. For example, some image types
    # require tell and seek methods that are not present on all storage
    # File objects.
    #    import ipdb; ipdb.set_trace()
    if not source:
        return
    source.open()  # If tried by a previous source_generator, will be closed
    source = StringIO(source.read())
    try:
        blob = Blob(source.read())
        image = Image(blob)
    except Exception:
        logger.exception("unable to read image to create thumbnail")
        return

    if not image.isValid():
        return

    return convertGMtoPIL(image)
Example #7
0
def ConvertJp2(input):
    """
    If the input is a jp2 picture, the image is transformed into bmp,
    else the image is returned without any modifications.

    @param input: A binary string representing the picture to convert
    @type input: A string
    @return: A binary string representing the picture in bmp, or the original input if the input is not a jp2 stream.
    """

    jp2 = open("tmp.jp2", "wb")
    jp2.write(input)
    jp2.close()

    if isMagick == False:
        geojasper = "geojasper"
        if (sys.platform != "win32") and os.path.isfile(
            os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "geojasper", geojasper)
        ):
            geojasper = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "geojasper", geojasper)
        a = os.popen(geojasper + " -f tmp.jp2 -F tmp.jpg")
        a.close()
    else:
        jpg = MImage("tmp.jp2")
        jpg.write("tmp.jpg")

    try:
        f = open("tmp.jpg", "rb")
        input = f.read()
        f.close()
    except IOError, msg:
        pass
Example #8
0
 def test_fromblob(self):
     with open('../example/X.jpg', 'rb') as f:
         data = f.read()
         b = Blob(data)
         img = Image(b)
         img.write('X2.jpg')
         self.assertEqual(type(img), Image)
Example #9
0
    def get_image( self ):
        # Open the image
        try:
            img_file = urllib.urlopen( self.path )
            img_data = img_file.read()
            bytes_read = len(img_data)
        except urllib.HTTPError as e:
            raise ImageRetrievalError(self.path, "Error code: %s" % e.code)
        except urllib.URLError as e:
            raise ImageRetrievalError(self.path, e.reason)

        blob = Blob( img_data )
        image = Image( blob )
        # Check if the whole image should be used and cropped if necessary.
        src_width = image.size().width()
        src_height = image.size().height()
        if self.width != src_width or self.height != src_height:
            box = Geometry( self.width, self.height, self.x_min_src, self.y_min_src )
            image.crop( box )

        # Estimates the size in Bytes of this image part by scaling the number
        # of Bytes read with the ratio between the needed part of the image and
        # its actual size.
        self.estimated_size = bytes_read * abs(float(self.width * self.height) /
                                               float(src_width * src_height))
        return image
Example #10
0
    def test_image_setpixels(self):
        img = Image(Geometry(300, 200), Color('transparent'))
        pixels = img.setPixels(40, 50, 5, 5)
        for pixel in pixels:
            pixel.red = 50
        img.syncPixels()

        for pixel in img.getPixels(40, 50, 5, 5):
            self.assertEqual(50, pixel.red)
Example #11
0
def get_sized_image(filename, size):
	if not os.path.exists(DIR):
		os.mkdir(DIR)
	cache_hash = sha1('{0}\0{1}'.format(filename, size)).hexdigest() + '.jpg'
	cache_path = os.path.join(DIR, cache_hash)
	if not os.path.exists(cache_path):
		im = Image(filename.encode('utf-8'))
		im.sample(size)
		im.write(cache_path)
	return '/'.join(PARTS + (cache_hash,))
Example #12
0
 def resize2( srcFile="", destFile="", w=200,h=200 ):
     blobData = Blob(open(srcFile).read())
     if ( h != -1 ):
         img = Image( blobData, Geometry(w, h))
         img.scale("%dx%d!" % (w,h))
     else:
         img = Image( blobData )
         img.scale("%dx!" % w )
     img.profile("*",Blob())
     img.write(destFile)
     return "True"
Example #13
0
    def resize0(srcFile="", destFile="", w=200):

        img = Image(srcFile)
        sw = img.columns()
        sh = img.rows()
        if (sw > w):
            tw = w
            th = sh * (float(w) / float(sw))
            img.scale("%dx%d" % (tw, th))
        img.profile("*", Blob())
        img.write(destFile)
        return "True"
Example #14
0
 def get_image( self ):
     # Open the image
     img_file = urllib.urlopen( self.path )
     blob = Blob( img_file.read() )
     image = Image( blob )
     # Check if the whole image should be used and croped
     # if necessary.
     src_width = image.size().width()
     src_height = image.size().height()
     if self.width !=  src_width or self.height != src_height:
         box = Geometry( self.width, self.height, self.x_min_src, self.y_min_src )
         image.crop( box )
     return image
Example #15
0
def process_images(subdir):
  curr_dir = data_dir + subdir + '/'

  counter = 1
  files = os.listdir(curr_dir)
  interval = int(len(files) / target)

  for file in files:
    if counter % interval == 0 and counter / interval <= target:
      img = Image(curr_dir + '/' + file)
      img.type(ImageType.GrayscaleType)
      img.write(out_dir + subdir + str(counter / interval) + '.tif')
    counter = counter + 1
Example #16
0
    def resize10(srcFile="", destFile="", w=200):
        img = Image(srcFile)
        sw = img.columns()
        sh = img.rows()
        scale = sw * sh

        if (scale > w):
            tw = int(sw * ((float(w) / float(scale))**0.5))
            th = int(w / tw)
            img.scale("%dx%d" % (tw, th))
        img.profile("*", Blob())
        img.write(destFile)
        return "True"
Example #17
0
 def test_color_histogram(self):
     redColor = Color('red')
     im = Image(Geometry(30, 20), redColor)
     histogram = im.colorHistogram()
     self.assertEqual(1, len(histogram))
     # test in, __getitem__
     self.assertIn(redColor, histogram)
     self.assertEqual(30 * 20, histogram[redColor])
     # iteration example
     for packet in histogram:
         color, count = packet.key(), packet.data()
         self.assertEqual(redColor, color)
         self.assertEqual(30 * 20, count)
Example #18
0
 def test_color_histogram(self):
     redColor = Color('red')
     im = Image(Geometry(30, 20), redColor)
     histogram = im.colorHistogram()
     self.assertEqual(1, len(histogram))
     # test in, __getitem__
     self.assertIn(redColor, histogram)
     self.assertEqual(30 * 20, histogram[redColor])
     # iteration example
     for packet in histogram:
         color, count = packet.key(), packet.data()
         self.assertEqual(redColor, color)
         self.assertEqual(30 * 20, count)
Example #19
0
def image_process():
    # If you change directory of loaded images, change this variable
    # it will change the directory for the rest of this function.
    # the '/' is important at the end of the file name.
    load_images_here = 'load_images_here/'

    files = [
        f for f in listdir(load_images_here)
        if isfile(join(load_images_here + '.', f))
    ]
    # files.remove('program.py')
    # files.remove('README.md')

    print(files)

    num = 0
    i = 0

    image_scale = input("Scale in px. Ex: 1000x1000 \n")

    for file in files:
        new_filename = file
        no_spaces_true = True
        if ' ' in file:
            no_spaces_true = False
            print("Found spaces...")
            file_no_space = file.replace(' ', '_')
            new_filename = file_no_space
            print("replaced spaces....")
            print("writing..." + file + ' -> ' + file_no_space)
            file = load_images_here + file
            file_no_space = load_images_here + file_no_space
            shutil.copy(file, file_no_space)
            print("New File is written.")
            file = file_no_space
        print(file)
        if no_spaces_true == True:
            im = Image(load_images_here + file)
        else:
            im = Image(file)
        im.quality(100)
        im.scale(image_scale)
        # im.sharpen(1.0) # This doesn't seem to help. Keeping it for further research
        im.write('pre_processed/sc' + str(num) + '_' +
                 new_filename)  # 'sc' in this line indicates 'scaled'
        if no_spaces_true == False:
            clean_up = "rm " + file_no_space
            os.system(clean_up)
        num += 1
        i += 1
Example #20
0
def convertToJpg():
    problemImages = []
    os.chdir("data/FullPages")
    batchLevel = os.listdir(os.getcwd())
    totalBatches = len(batchLevel)
    currentBatch = 0
    for i in batchLevel:
        currentBatch += 1
        os.chdir(i)
        issueLevel = os.listdir(os.getcwd())
        totalIssues = len(issueLevel)
        currentIssue = 0
        for j in issueLevel:
            currentIssue += 1
            os.chdir(j)
            jp2Images = os.listdir(os.getcwd())
            totalImages = len(jp2Images)
            currentImage = 0
            for k in jp2Images:
                currentImage += 1
                try:
                    im = Image(str(k))
                    newName = k[:-3] + 'jpg'
                    im.write(str(newName))

                    #Status update on how many images have been processed
                    sys.stdout.write("\rConverted Batch: " +
                                     str(currentBatch) + "/" +
                                     str(totalBatches) + " Issue: " +
                                     str(currentIssue) + "/" +
                                     str(totalIssues) + " Image: " +
                                     str(currentImage) + "/" +
                                     str(totalImages) + "           ")
                    sys.stdout.flush()
                    #remove old jp2 image to conserve space, also only remove if conversion was successful
                    os.remove(k)
                except:
                    problemImages.append(str(k))
            os.chdir('..')
        os.chdir('..')
    os.chdir('../..')

    #end of process message
    if len(problemImages) > 0:
        print(
            "These are images that could not be converted to jpg for some reason. Please check for corruption/ proper download."
        )
        print(problemImages)
    else:
        print("All images converted successfully")
Example #21
0
    def _xor_composite_clip_layer(self, clips, layer_level=0):
        """
        round two clipping.
        """

        #skip the first clip as it doesn't need anything taken away from it.
        this_clip = GMImage(
            os.path.join(self.clips_dir, 'clip-%s.png' % clips[0]))
        this_clip.write(
            os.path.join(self.clips_dir, "clip-co-%s.png" % clips[0]))
        #self.masks.append(os.path.join(self.clips_dir, 'clip-co-%s.png' %
        #clips[0]))

        clip_i = 0
        for clip_id in clips[1:]:
            previous_clip = GMImage(
                os.path.join(self.clips_dir, 'clip-%s.png' % clips[clip_i]))
            this_clip = GMImage(
                os.path.join(self.clips_dir, 'clip-%s.png' % clip_id))

            this_clip.composite(previous_clip, 0, 0, co.XorCompositeOp)
            img_file = os.path.join(self.clips_dir, "clip-co-%s.png" % clip_id)
            this_clip.write(img_file)
            clip_i = clip_i + 1
            im = Image.open(img_file)
            if not im.getbbox():  # nothing there so delete it
                os.unlink(img_file)
Example #22
0
    def _xor_composite_clip_layer(self, clips, layer_level=0):
        """
        round two clipping.
        """

        #skip the first clip as it doesn't need anything taken away from it.
        this_clip = GMImage(os.path.join(self.clips_dir, 'clip-%s.png' %
            clips[0]))
        this_clip.write(os.path.join(self.clips_dir, "clip-co-%s.png" %
            clips[0]))
        #self.masks.append(os.path.join(self.clips_dir, 'clip-co-%s.png' %
            #clips[0]))

        clip_i = 0
        for clip_id in clips[1:]:
            previous_clip = GMImage(os.path.join(self.clips_dir, 'clip-%s.png' %
                clips[clip_i]))
            this_clip = GMImage(os.path.join(self.clips_dir, 'clip-%s.png' %
                clip_id))

            this_clip.composite(previous_clip, 0, 0, co.XorCompositeOp)
            img_file = os.path.join(self.clips_dir, "clip-co-%s.png" % clip_id)
            this_clip.write(img_file)
            clip_i = clip_i + 1
            im = Image.open(img_file)
            if not im.getbbox(): # nothing there so delete it
                os.unlink(img_file)
Example #23
0
def create_thumb(pvi_img_path):
    img = Image(Blob(open(pvi_img_path).read()))
    img.scale(ws.thumb_size_x + 'x' + ws.thumb_size_y)
    img.quality(ws.thumb_jpeg_compression_quality)
    img.write(ws.working_directory + "tmp_thumb_resized.jpg")
    blob = Blob(open(ws.working_directory + "tmp_thumb_resized.jpg").read())
    return blob.data
Example #24
0
 def test_image_resize(self):
     im = Image(Geometry(300, 200), Color('transparent'))
     g = Geometry(150, 100)
     ft = FilterTypes.BlackmanFilter
     blur = 0.5
     im.resize(g, ft, blur)
     im.resize(g, ft)
     im.resize(g)
Example #25
0
    def resize0( srcFile="", destFile="", w=200 ):

        img = Image(srcFile)
        sw = img.columns()
        sh = img.rows()
        if ( sw > w  ):
            tw = w
            th = sh*(float(w)/float(sw))
            img.scale("%dx%d"%(tw,th))
        img.profile("*", Blob())
        img.write(destFile)
        return "True"
Example #26
0
	def convertirJPEG2000(self,nombre_imagen,nuevo_nombre,optimizado=True,calidad=100):
		#tiempo_inicio=int(time.time())
		tiempo_inicio=time.time()
		print "convert"
		resultado=False
		try:
			imagen = Image_PG(RUTA_IMAGENES+nombre_imagen)
			imagen.write(RUTA_IMAGENES+nuevo_nombre)
			resultado=True
		except Exception as e:
			print "Error...."
			print e
		#tiempo_fin=int(time.time())
		tiempo_fin=time.time()
		self.__tiempo=tiempo_fin-tiempo_inicio
		return resultado
	def buildImage(self):


		#first build the image, we need to know how big it is
		with open(self.dataBase + "base.json", "r") as f:
			base = json.loads(f.read())
		
		self.totalWidth = base['width']
		self.totalHeight = base['height']



		print ("Creating large base image", int(self.totalWidth), 'x',int(self.totalHeight) )
		im = Image(Geometry(int(self.totalWidth), int(self.totalHeight)), Color("black"))


		#throw a logo onnn
		#layer = Image('logo.png')
		#im.composite(layer, 0, 0, co.OverCompositeOp)


		for file in os.listdir(self.dataNodes):

			if file.endswith('.json'):

				with open(self.dataNodes + file, "r") as f:

					nodes = json.loads(f.read())
					print ("Building Image Nodes", self.dataNodes + file, len(nodes))
					self.buildCounterNodeTotal = len(nodes)
					self.buildCounterNode = 0

					for node in nodes:

						self.buildCounterNode+=1

						print (self.buildCounterNode / self.buildCounterNodeTotal * 100)," percent complete of this batch                                         \r",
						layer = Image(self.dataCircles + str(node['id']) +'.png')

						cords = self.convertCoordinates(node['posX'],node['posY'])

						im.composite(layer, int(cords[0]), int(cords[1]), co.OverCompositeOp)


		print ("")
		print ("Writing large file out")
		im.write('base.png')
Example #28
0
    def resize10( srcFile="", destFile="", w=200 ):
        img = Image( srcFile )
        sw = img.columns()
        sh = img.rows()
        scale = sw*sh

        if ( scale > w ):
            tw = int(sw*((float(w)/float(scale))**0.5))
            th = int(w/tw)
            img.scale("%dx%d"%(tw,th))
        img.profile("*",Blob())
        img.write(destFile)
        return "True"
Example #29
0
def thumbnail(request, type, identifier):
    response = HttpResponse(mimetype="image/png")
    size = str(request.GET.get("size", "190x270"))
    if not re.match("\d+[x]\d+", size):
        size = "190x270"

    cache_key = "thumbnail:%s:%s:%s" % (type, identifier, size)
    cached = cache.get(cache_key)
    if cached is None:
        if type == "file":
            file_ = str(os.path.join(settings.INCOMING_DIRECTORY, identifier))
        elif type == "document":
            document = get_object_or_404(Document, pk=identifier)
            file_ = Blob(document.document.read())

        image = Image(file_)
        image.filterType(FilterTypes.SincFilter)
        image.scale(size)

        output = Blob()
        image.write(output, "png")
        response.write(output.data)
        cache.set(cache_key, output.data)
    else:
        response.write(cached)

    return response
 def dummy_image(self, width, height):
     im = Image(Geometry(width, height), Color(240, 240, 240))
     im.strokeColor(Color(128, 128, 128))
     im.strokeWidth(1)
     im.draw(DrawableLine(0, 0, width, height))
     im.draw(DrawableLine(0, height, width, 0))
     return im
Example #31
0
    def resize3( srcFile="", destFile="", w=200,h=200, color="", crop=False, align="center" ):

        img = Image(srcFile)
        img.scale("%dx%d>"%(w,h))
        img.profile("*",Blob())
        img.write(destFile)
        return "True"
Example #32
0
    def _in_composite(self, previous_clips, clips):
        for prev_clip_id in previous_clips:
            for this_clip_id in clips:
                previous_clip = GMImage(os.path.join(self.clips_dir, 'clip-co-%s.png' %
                    prev_clip_id))
                this_clip = GMImage(os.path.join(self.clips_dir, 'clip-co-%s.png' %
                    this_clip_id))

                this_clip.composite(previous_clip, 0, 0, co.InCompositeOp)
                img_file = os.path.join(self.clips_dir, "clip-in-%s-%s.png" %
                    (prev_clip_id, this_clip_id))
                this_clip.write(img_file)

                im = Image.open(img_file)
                if not im.getbbox(): # nothing there so delete it
                    os.unlink(img_file)
                else:
                    self.masks.append(img_file)
Example #33
0
    def _composite(self, mask, pic, i=0):
        """
        composite of mask and pic. also trims it and renames with offset.
        """
        base = GMImage(pic)
        layer = GMImage(mask)
        base.composite(layer, 0, 0, co.CopyOpacityCompositeOp)
        finished_clip_filename = os.path.join(self.target_directory, self.junk_dir, "%s-%s.png" %
            (os.path.basename(pic), os.path.basename(mask)))
        base.write(finished_clip_filename)

        box = self._trim(finished_clip_filename,
                os.path.join(self.target_directory, self.raster_dir, "%i.png" % i))

        self._potrace(mask, i=i,
                trimmedpng=os.path.join(self.target_directory, self.raster_dir,"%i.png" % i))

        self.pieces[i] = box
Example #34
0
def check_img():
    '''
    Checar se o arquivo declarado é realmente uma imagem;
    em caso afirmativo, carrega o arquivo
    '''

    try:
        check = Image()
        check.ping(sys.argv[1])
    except RuntimeError:
        print sys.argv[1], "is not a valid image file!"
        sys.exit()
    except:
        print "unexpected error:", sys.exc_info()[0]
        raise
        sys.exit()
    else:
        return sys.argv[1]
Example #35
0
def check_img():
    '''
    Checar se o arquivo declarado é realmente uma imagem;
    em caso afirmativo, carrega o arquivo
    '''

    try:
        check = Image()
        check.ping(sys.argv[1])
    except RuntimeError:
        print sys.argv[1], "is not a valid image file!"
        sys.exit()
    except:
        print "unexpected error:", sys.exc_info()[0]
        raise
        sys.exit()
    else:
        return sys.argv[1]
Example #36
0
    def get_image( self ):
        # Open the image
        try:
            img_file = urllib.urlopen( self.path )
        except urllib.HTTPError as e:
            raise ImageRetrievalError(self.path, "Error code: %s" % e.code)
        except urllib.URLError as e:
            raise ImageRetrievalError(self.path, e.reason)

        blob = Blob( img_file.read() )
        image = Image( blob )
        # Check if the whole image should be used and cropped if necessary.
        src_width = image.size().width()
        src_height = image.size().height()
        if self.width != src_width or self.height != src_height:
            box = Geometry( self.width, self.height, self.x_min_src, self.y_min_src )
            image.crop( box )
        return image
Example #37
0
 def test_image_resize(self):
     im = Image(Geometry(300, 200), Color('transparent'))
     g = Geometry(150, 100)
     ft = FilterTypes.BlackmanFilter
     blur = 0.5
     im.resize(g, ft, blur)
     im.resize(g, ft)
     im.resize(g)
    def _watermark(self, image, watermark_path, opacity, size, position_str):
        watermark = self.get_image(open(watermark_path))
        image_size = self.get_image_size(image)
        layer = Image(Geometry(image_size[0], image_size[1]), 'transparent')
        if opacity < 1:
            self._reduce_opacity(watermark, opacity)
        if not size:
            mark_size = self.get_image_size(watermark)
        else:
            mark_size = self._get_new_watermark_size(size, self.get_image_size(watermark))
            options = {'crop': 'center',
                       'upscale': False}
            watermark = self.scale(watermark, mark_size, options)
            watermark = self.crop(watermark, mark_size, options)

        position = self._define_watermark_position(position_str, image_size, mark_size)
        layer.composite(watermark, position[0], position[1], CoOp.OverCompositeOp)
        image.composite(layer, 0, 0, CoOp.OverCompositeOp)
        return image
Example #39
0
    def resize3(srcFile="",
                destFile="",
                w=200,
                h=200,
                color="",
                crop=False,
                align="center"):

        img = Image(srcFile)
        img.scale("%dx%d>" % (w, h))
        img.profile("*", Blob())
        img.write(destFile)
        return "True"
Example #40
0
	def watercolor(self,imgObj):
		print "watercolor()"
		img=imgObj
		#img.blur(2,2)
		img.oilPaint(1)
		img.enhance()
		img.sharpen()

		pink=Color(250,218,221,75)

		toplayer=Image(img.size(),pink)
		toplayer.matte(True)

		img.matte(True)
		img.composite(toplayer,0,0,CompositeOperator.CopyOpacityCompositeOp)

		img.blur(0,1)
		
		img.write('output.png')
		return img
Example #41
0
 def evaluar(self, url_imagen):
     resultado = True
     self.__nueva_url = url_imagen
     try:
         nombre, extension = os.path.splitext(url_imagen)
         if (extension in self.__extensiones):
             self.__nueva_url = nombre + str(int(time.time())) + ".jpeg"
             imagen = Image_PG(RUTA_IMAGENES + url_imagen)
             imagen.write(RUTA_IMAGENES + self.__nueva_url)
         imagen = Image.open(RUTA_IMAGENES + self.__nueva_url)
         imagen = self.escalaGrises(imagen)
         self.__nueva_url = "grises" + self.__nueva_url
         imagen.save(RUTA_IMAGENES + self.__nueva_url,
                     optimize=True,
                     quality=100)
     except Exception as e:
         print "Error EvaluarImagen.evaluar..."
         print e
         resultado = False
     return resultado
Example #42
0
def get_im(content):
    if hasattr(content, 'read'):
        content = content.read()
    if not content:
        return
    else:
        try:
            f = Blob(content)
            return Image(f)
        except:
            return
Example #43
0
    def _in_composite(self, previous_clips, clips):
        for prev_clip_id in previous_clips:
            for this_clip_id in clips:
                previous_clip = GMImage(
                    os.path.join(self.clips_dir,
                                 'clip-co-%s.png' % prev_clip_id))
                this_clip = GMImage(
                    os.path.join(self.clips_dir,
                                 'clip-co-%s.png' % this_clip_id))

                this_clip.composite(previous_clip, 0, 0, co.InCompositeOp)
                img_file = os.path.join(
                    self.clips_dir,
                    "clip-in-%s-%s.png" % (prev_clip_id, this_clip_id))
                this_clip.write(img_file)

                im = Image.open(img_file)
                if not im.getbbox():  # nothing there so delete it
                    os.unlink(img_file)
                else:
                    self.masks.append(img_file)
Example #44
0
    def _watermark(self, image, watermark_path, opacity, size, position_str):
        watermark = self.get_image(open(watermark_path))
        image_size = self.get_image_size(image)
        layer = Image(Geometry(image_size[0], image_size[1]), 'transparent')
        if opacity < 1:
            self._reduce_opacity(watermark, opacity)
        if not size:
            mark_size = self.get_image_size(watermark)
        else:
            mark_size = self._get_new_watermark_size(
                size, self.get_image_size(watermark))
            options = {'crop': 'center', 'upscale': False}
            watermark = self.scale(watermark, mark_size, options)
            watermark = self.crop(watermark, mark_size, options)

        position = self._define_watermark_position(position_str, image_size,
                                                   mark_size)
        layer.composite(watermark, position[0], position[1],
                        CoOp.OverCompositeOp)
        image.composite(layer, 0, 0, CoOp.OverCompositeOp)
        return image
Example #45
0
    def get_image(self):
        # Open the image
        try:
            r = requests.get(self.path,
                             allow_redirects=True,
                             verify=verify_ssl)
            if not r:
                raise ValueError("Could not get " + self.path)
            if r.status_code != 200:
                raise ValueError("Unexpected status code ({}) for {}".format(
                    r.status_code, self.path))
            img_data = r.content
            bytes_read = len(img_data)
        except requests.exceptions.RequestException as e:
            raise ImageRetrievalError(self.path, str(e))

        blob = Blob(img_data)
        image = Image(blob)
        # Check if the whole image should be used and cropped if necessary.
        src_width = image.size().width()
        src_height = image.size().height()
        if self.width != src_width or self.height != src_height:
            box = Geometry(self.width, self.height, self.x_min_src,
                           self.y_min_src)
            image.crop(box)

        # Estimates the size in Bytes of this image part by scaling the number
        # of Bytes read with the ratio between the needed part of the image and
        # its actual size.
        self.estimated_size = bytes_read * abs(
            float(self.width * self.height) / float(src_width * src_height))
        return image
Example #46
0
def specificRecord(theId):
  # Get the record.
  aRow = db.session.query(ServiceRecord, Vehicle).filter_by(id=theId).join(Vehicle).first()
  aRecord = {
    "id": aRow[0].id,
    "year": aRow[1].year,
    "make": aRow[1].make,
    "model": aRow[1].model,
    "date": aRow[0].date,
    "miles": aRow[0].miles,
    "description": aRow[0].description
  }

  # Get the filepaths for the photos.
  import os
  aPostfix = "vehicles/receipts/{}".format(theId)
  aList = [url_for("static", filename=aPostfix + os.sep + x) for x in os.listdir("app/static/" + aPostfix)]

  # Create the form.
  aForm = PhotoForm()

  # Check to see if the form is valid as well as a post request.
  if aForm.validate_on_submit():
    filename = secure_filename(aForm.upload.data.filename)
    aSavePath = 'app/static/vehicles/receipts/{}/'.format(theId) + filename
    aForm.upload.data.save(aSavePath)

    # Convert the photo to nice web stuff.
    from pgmagick import Image, InterlaceType
    aImg = Image(aSavePath)
    aImg.quality(80)
    aImg.scale("80%")
    aImg.interlaceType(InterlaceType.PlaneInterlace)
    aImg.write(aSavePath)

    flash("File uploaded", "success")

    aForm = PhotoForm()

  return render_template(
    "vehicles/record.html",
    theRecord=aRecord,
    theFiles=aList,
    theForm=aForm
  )
Example #47
0
 def test_scale_jpeg(self):
     img = api.Image((400, 400), 'blue')
     img.write(self.tmp_filename_jpg)
     img2 = Image(Blob(open(self.tmp_filename_jpg).read()),
                  Geometry(200, 200))
     img2.scale('200x200')
     img2.write(self.tmp_filename_jpg)
 def _watermark(self, image, watermark_path, opacity, size, position_str):
     with open(watermark_path, 'rb') as watermark_file:
         watermark = self.get_image(watermark_file)
     image_size = self.get_image_size(image)
     layer = Image(Geometry(image_size[0], image_size[1]), 'transparent')
     if opacity < 1:
         self._reduce_opacity(watermark, opacity)
     if not size:
         mark_size = self.get_image_size(watermark)
     else:
         mark_size = tuple(
             self._get_new_watermark_size(size,
                                          self.get_image_size(watermark)))
         options = {
             'crop': 'center',
             'upscale': mark_size > self.get_image_size(watermark)
         }
         watermark = self.scale(watermark, mark_size, options)
         watermark = self.crop(watermark, mark_size, options)
     if position_str == 'tile':
         for x_pos in range(0, image_size[0], mark_size[0]):
             for y_pos in range(0, image_size[1], mark_size[1]):
                 layer.composite(watermark, x_pos, y_pos,
                                 CoOp.OverCompositeOp)
     else:
         position = self._define_watermark_position(position_str,
                                                    image_size, mark_size)
         layer.composite(watermark, position[0], position[1],
                         CoOp.OverCompositeOp)
     image.composite(layer, 0, 0, CoOp.OverCompositeOp)
     return image
Example #49
0
    def get_image(self):
        # Open the image
        try:
            img_file = urlopen(self.path)
            img_data = img_file.read()
            bytes_read = len(img_data)
        except HTTPError as e:
            raise ImageRetrievalError(self.path, "Error code: %s" % e.code)
        except URLError as e:
            raise ImageRetrievalError(self.path, e.reason)

        blob = Blob(img_data)
        image = Image(blob)
        # Check if the whole image should be used and cropped if necessary.
        src_width = image.size().width()
        src_height = image.size().height()
        if self.width != src_width or self.height != src_height:
            box = Geometry(self.width, self.height, self.x_min_src,
                           self.y_min_src)
            image.crop(box)

        # Estimates the size in Bytes of this image part by scaling the number
        # of Bytes read with the ratio between the needed part of the image and
        # its actual size.
        self.estimated_size = bytes_read * abs(
            float(self.width * self.height) / float(src_width * src_height))
        return image
Example #50
0
 def getpixels_test_template(self, use_const):
     img = Image(Geometry(300, 200), Color('transparent'))
     getPixelsMethod = img.getConstPixels if use_const else img.getPixels
     pixels = getPixelsMethod(40, 50, 10, 10)
     self.assertEqual(10 * 10, len(pixels))
     with self.assertRaises(IndexError):
         pixels[2000]
     colorMax = Color.scaleDoubleToQuantum(1.0)
     self.assertEqual(0, pixels[0].red)
     self.assertEqual(0, pixels[0].blue)
     self.assertEqual(0, pixels[0].green)
     self.assertEqual(colorMax, pixels[0].opacity)
     return pixels
Example #51
0
    def _composite(self, mask, pic, i=0):
        """
        composite of mask and pic. also trims it and renames with offset.
        """
        base = GMImage(pic)
        layer = GMImage(mask)
        base.composite(layer, 0, 0, co.CopyOpacityCompositeOp)
        finished_clip_filename = os.path.join(
            self.target_directory, self.junk_dir,
            "%s-%s.png" % (os.path.basename(pic), os.path.basename(mask)))
        base.write(finished_clip_filename)

        box = self._trim(
            finished_clip_filename,
            os.path.join(self.target_directory, self.raster_dir, "%i.png" % i))

        self._potrace(mask,
                      i=i,
                      trimmedpng=os.path.join(self.target_directory,
                                              self.raster_dir, "%i.png" % i))

        self.pieces[i] = box
Example #52
0
 def test_scale_jpeg(self):
     img = api.Image((400, 400), 'blue')
     img.write(self.tmp_filename_jpg)
     with open(self.tmp_filename_jpg, 'rb') as fp:
         b = Blob(str(fp.read()))
         img2 = Image(b, Geometry(200, 200))
         if sys.platform.lower() == 'darwin':
             # NOTE: error occur when use '200x200' param
             #       -----------------------------------------------------
             #       RuntimeError: Magick: Application transferred too few
             #       scanlines (x.jpg) reported by coders/jpeg.c:344 (JPEGErrorHandler)
             img2.scale('199x199')
         else:
             img2.scale('200x200')
         img2.write(self.tmp_filename_jpg)
Example #53
0
 def pdf_to_image(self, pdf_file):
     if not self.check_file_exist(pdf_file):
         self.log.debug('Requested file not found in {} '.format(pdf_file))
         return False
     image_file = pdf_file.replace('.pdf', '.jpg')
     try:
         pdf_to_img = Image()
         pdf_to_img.density('200')
         pdf_to_img.read(pdf_file)
         pdf_to_img.write(image_file)
         self.log.info('Image convert passed - {} '.format(image_file))
         return True
     except Exception:
         self.log.error('Image convert failed - {} '.format(image_file))
         self.log.error('', exc_info=True)
         return False
Example #54
0
    def test_image_setpixels(self):
        img = Image(Geometry(300, 200), Color('transparent'))
        pixels = img.setPixels(40, 50, 5, 5)
        for pixel in pixels:
            pixel.red = 50
        img.syncPixels()

        for pixel in img.getPixels(40, 50, 5, 5):
            self.assertEqual(50, pixel.red)
Example #55
0
    def convert_split(srcfile='', dstpath='', truefile='', split='3x3', w=100, h=100):
        """
        目前仅用作封面频道
        """
        srcfile = srcfile.encode("utf-8")
        dstpath = dstpath.encode("utf-8")
        truefile = truefile.encode("utf-8")
        (sp_x, sp_y) = split.split('x')
        (file_name, image_ext) = os.path.splitext(os.path.basename(srcfile))

        cw = int(sp_x) * int(w)
        ch = int(sp_y) * int(h)
        t1 = time.time()
        #生成封面列表图
        re = myGraphicsMagick.convert_gif_thumbnail_frame0_g(srcfile=srcfile, dstfile=truefile, w=cw, h=ch,
            need_return=False)


        if re == True:
            #切割方式为从图片的左上开始逐行切割
            #目标图片文件名为:50d8059b1a822.11.jpg
            blobData = Blob(open(srcfile).read())

            try:
                num = 0#图片输出的编号
                for j in range(int(sp_y)):

                    if ( num >= ( int( sp_x )*int( sp_y ) - 1 ) ):
                        break
                    for i in range(int(sp_x)):
                        img = Image( blobData, Geometry(cw,ch) )
                        linePos = i * int(w)
                        colsPos = j * int(h)
                        #从指定的像素点进行裁剪
                        img.crop( Geometry(w,h,linePos, colsPos) )
                        destFilename = dstpath+'/%s.%d.%s' %( file_name,num,image_ext )
                        img.profile("*",Blob())
                        img.write( destFilename )
                        num = num + 1
                t2 = time.time()
                sys.stdout.writelines(datetime.now().strftime('%Y-%m-%d %H:%M:%S  ')+"libconvert appName:%s ver:%s cmdSN:%s type:%s cmdData:%s command : convert_split srcfile:%s dstfile:%s runTime:%s\n" % ( proto.protocal['appName'],proto.protocal['ver'],proto.protocal['cmdSN'],proto.protocal['type'],proto.protocal['cmdData'], srcfile,dstfile,(t2-t1)) )
                sys.stdout.flush()
                return ret
            except Exception as e:
                sys.stderr.writelines(datetime.now().strftime('%Y-%m-%d %H:%M:%S  ')+"libconvert_split %s %s srcfile:%s destFilename:%s\n" % (e.args, e.message, srcfile,destFilename))
                sys.stderr.flush()
                return 'False'
        else:
            return "False"
            pass
        return 'True'
Example #56
0
    def post(self):
        # check pic exgister
        if self.request.files == {} or 'pic' not in self.request.files:
            self.write('<script>m_ksb_msg.show("请选择图片")</script>')
            return

        # check pic format
        image_type_list = ['image/gif', 'image/jpeg', 'image/pjpeg', 'image/bmp', 'image/png', 'image/x-png']
        send_file = self.request.files['pic'][0]

        if send_file['content_type'] not in image_type_list:
            self.write('<script>m_ksb_msg.show("仅支持jpg,jpeg,bmp,gif,png格式的图片!")</script>')
            return
        # check pic size 4M
        if len(send_file['body']) > 4 * 1024 * 1024:
            self.write('<script>m_ksb_msg.show("请上传4M以下的图片");</script>')
            return

        # create temp file
        tmp_file = tempfile.NamedTemporaryFile(delete=True)
        tmp_file.write(send_file['body'])
        tmp_file.seek(0)

        # illegal pic can't open with Image
        try:
            image_one = Image(tmp_file.name)
        except IOEturerror:
            logging.info(error)
            logging.info('+'*30 + '\n')
            logging.info(self.request.headers)
            tmp_file.close()
            self.write('<script>m_ksb_msg.show("图片不合法!")</script>')
            return

        # check pixel
        if image_one.columns() < 250 or image_one.rows() < 250 or \
                image_one.columns() > 2000 or image_one.rows() > 2000:
            tmp_file.close()
            self.write('<script>m_ksb_msg.show("图片长宽在250px~2000px之间!")</script>')
            return

        # saving
        image_path = "./static/pic/goods/"
        image_format = send_file['filename'].split('.').pop().lower()
        tmp_name = image_path + str(int(time.time())) + image_format
        image_one.write(tmp_name)

        # close temp
        tmp_file.close()
        self.write('<script>m_ksb_msg.show("文件上传成功,路径为:" + image_path[1:])</script>')
        return
Example #57
0
def convertGMtoPIL(gmimage):
    """
    Convert GraphicsMagick image to PIL

    work with grayscale and colour
    """
    img = Image(gmimage)  # make copy
    gmimage.depth(8)
    img.magick("RGB")
    w, h = img.columns(), img.rows()
    blob = Blob()
    img.write(blob)
    data = blob.data

    # convert string array to an RGB PIL image
    pilimage = PilImage.fromstring('RGB', (w, h), data)
    return pilimage
Example #58
0
def process_images(subdir):
    curr_dir = data_dir + subdir + '/'

    counter = 1
    files = os.listdir(curr_dir)
    interval = int(len(files) / target)

    for file in files:
        if counter % interval == 0 and counter / interval <= target:
            img = Image(curr_dir + '/' + file)
            img.type(ImageType.GrayscaleType)
            img.write(out_dir + subdir + str(counter / interval) + '.tif')
        counter = counter + 1
Example #59
0
 def to_jpgs(self, size='mid', pages=None):
     """ Convert pdf to jpeg images
       pages: array for pages, None for extract all
     """
     dendic = dict(thumb=40, mid=100, big=150)
     density = dendic[size]
     pages = np.arange(0, self.pages, 1) if pages is None else pages
     if len(pages) < 1:
         return
     sp = self.slides_path(size)
     if os.path.exists(sp):
         shutil.rmtree(sp)
     os.makedirs(sp)
     img = Image()
     img.density("{}".format(density))
     for page in pages:
         if page > self.pages or page < 0:
             continue
         pdf = "{}[{}]".format(self.pdf_path, page)
         slid = "{}/{:03d}".format(sp, page)
         img.read(pdf)
         img.write("{}.jpg".format(slid))
Example #60
0
    def get_image(self):
        # Open the image
        try:
            img_file = urllib.urlopen(self.path)
        except urllib.HTTPError as e:
            raise ImageRetrievalError(self.path, "Error code: %s" % e.code)
        except urllib.URLError as e:
            raise ImageRetrievalError(self.path, e.reason)

        blob = Blob(img_file.read())
        image = Image(blob)
        # Check if the whole image should be used and cropped if necessary.
        src_width = image.size().width()
        src_height = image.size().height()
        if self.width != src_width or self.height != src_height:
            box = Geometry(self.width, self.height, self.x_min_src,
                           self.y_min_src)
            image.crop(box)
        return image