Пример #1
0
def watermark_image(filename, distname):
	from image import SimpImage
	im = SimpImage(filename)
	if os.environ.has_key('IMSTO_CONF_DIR'):
		watermark = os.path.join(os.environ['IMSTO_CONF_DIR'], 'watermark.png')
		copyright = os.path.join(os.environ['IMSTO_CONF_DIR'], 'watermark-copy.png')
	else:
		watermark = os.path.join(os.getcwd(), 'config/watermark.png')
		copyright = os.path.join(os.getcwd(), 'config/watermark-copy.png')
	#print ini_file
	im_w = SimpImage(watermark)
	#print im_w.wand
	check_dirs(distname)
	ci = SimpImage(copyright) if os.access(copyright, os.R_OK) else None
	r = None
	if im.watermark(im_w, 0.5, position='golden', copyright=ci):
		print 'watermark ok'
		r = im.save(distname)

	if r is None:
		print 'error watermark'

	del im
	del im_w
	return r
Пример #2
0
def thumbnail_wand(filename, size_1, distname, mode='s'):
	from image import SimpImage
	im = SimpImage(filename)
	if mode == 'c':
		ret = im.cropThumbnail(size_1, size_1)
	elif mode == 'w':
		ret = im.thumbnail(size_1, max_width=size_1)
	elif mode == 'h':
		ret = im.thumbnail(size_1, max_height=size_1)
	else:
		ret = im.thumbnail(size_1)

	print "thumbnail {} result: {}".format(size_1, ret)
	if ret:
		ret = im.save(distname)
	del im

	return ret
Пример #3
0
def thumbnail_wand(filename, width, height, distname, mode='s'):
	from image import SimpImage
	im = SimpImage(filename)
	if mode == 'c':
		ret = im.cropThumbnail(width, height)
	elif mode == 'w':
		ret = im.thumbnail(width, max_width=width)
	elif mode == 'h':
		ret = im.thumbnail(width, max_height=width)
	else:
		ret = im.thumbnail(width, height)

	print "thumbnail {} {}x{} result: {}".format(mode, width, height, ret)
	if ret:
		ret = im.save(distname)
	del im

	return ret
Пример #4
0
    def store(self, file=None, content=None, ctype=None, **kwd):
        """save a file-like item"""
        if content is None and not hasattr(file, 'read'):
            raise TypeError('invalid file-like object')

        data = content if content is not None else file.read()
        size = len(data)
        ext = guessImageType(data[:32])
        if ext is None:
            raise ValueError('invalid image file')

        hashes = [md5(data).hexdigest()]
        _exists_id = self.exists(hashed=hashes[0])
        if _exists_id:
            id = _exists_id
            filename = _make_filename(id, ext)
            print('id {} or hash {} exists!!'.format(id, hashes[0]))
            #raise DuplicateError('already exists')
            return [True, id, filename]
        ids = [_make_id(hashes[0])]
        if 'id' in kwd and kwd['id'] and kwd['id'] not in ids:
            ids += [kwd['id']]

        from image import SimpImage, MIN_QUALITY

        max_file_size = int(self.get_config('max_file_size'))
        max_jpeg_quality = int(self.get_config('max_jpeg_quality'))
        max_width = int(self.get_config('max_width'))
        max_height = int(self.get_config('max_height'))

        if size > max_file_size: max_jpeg_quality -= 1
        if max_jpeg_quality < MIN_QUALITY: max_jpeg_quality = MIN_QUALITY

        im = SimpImage(blob=data)
        meta = im.meta
        if meta['width'] > max_width or meta['height'] > max_height:
            if self.get_config('auto_scale') and im.thumbnail(
                    max_width, max_height):
                if im.format == 'JPEG' and im.quality > max_jpeg_quality:
                    im.quality = max_jpeg_quality
                data = im.get_blob()
                size = len(data)
                print im.meta
                print 'new scaled size {}'.format(size)
                hashes += [md5(data).hexdigest()]
            else:
                raise ValueError(
                    'file: {} dimension {}x{} is too big, max is {}x{}'.format(
                        kwd['name'] if 'name' in kwd else '', meta['width'],
                        meta['height'], max_width, max_height))

        if im.format == 'JPEG':
            if im.quality > max_jpeg_quality:
                print 'quality {} is too high, hash {}'.format(
                    im.quality, hashes[0])
                from tempfile import NamedTemporaryFile
                _tmp = NamedTemporaryFile('w+b',
                                          dir=self.get_config('temp_root'),
                                          delete=False)
                _tmp.file.close()
                save_file(_tmp.name, blob=data)
                if jpegoptim(_tmp.name):
                    fp = open(_tmp.name)
                    data = fp.read()
                    size = len(data)

                    # print 'new optimized size {}'.format(size)
                    fp.close()
                    _tmp.unlink(_tmp.name)
                    del im
                    im = SimpImage(blob=data)
                    meta = im.meta
                    hashes += [md5(data).hexdigest()]
                else:
                    raise EnvironmentError(
                        'jpeg qualty is too high, or need jpegoptim')
        elif im.format == 'PNG' and self.get_config('force_jpeg'):
            im.format = 'JPEG'
            im.quality = max_jpeg_quality
            data = im.get_blob()
            size = len(data)
            hashes += [md5(data).hexdigest()]
            ext = 'jpg'
            meta = im.meta
        del im

        if (size > max_file_size):
            raise ValueError('file: {} size {} is too big, max is {}'.format(
                kwd['name'] if 'name' in kwd else '', size, max_file_size))

        hashed = hashes[len(hashes) - 1]  #md5(data).hexdigest()
        # print ('md5 hash: {}'.format(hashed))

        # TODO: add for support (md5 + size) id
        id = _make_id(hashed)

        # print ('new filename: %r' % filename)

        # TODO: fix for support s3 front browse
        _exists_id = self.exists(id) or self.exists(hashed=hashed)
        if _exists_id:
            id = _exists_id
            filename = _make_filename(id, ext)
            print('id {} or hash {} exists!!'.format(id, hashed))
            #raise DuplicateError('already exists')
            return [True, id, filename]
        filename = _make_filename(id, ext)
        # print ('id: {}'.format(id))

        # if ctype is None or ctype == '':
        from _util import guess_mimetype
        ctype = guess_mimetype(filename)

        # save to mongodb
        spec = {
            '_id': id,
            'filename': filename,
            'hash': hashes,
            'mime': ctype,
            'size': size,
            'meta': meta,
            'ids': ids
        }

        if 'name' in kwd and isinstance(kwd['name'], (str, unicode)):
            spec['name'] = kwd['name']

        for k in ['created', 'app_id']:
            if k in kwd and kwd[k]:
                spec[k] = kwd[k]

        if self._store_exists(id, filename=filename):
            self._save_meta(id, spec)
            return [True, id, filename]

        rr = self._put(data, **spec)
        if rr:
            return [True, rr, filename]
Пример #5
0
	def store(self, file=None, content=None, ctype=None, **kwd):
		"""save a file-like item"""
		if content is None and not hasattr(file, 'read'):
			raise TypeError('invalid file-like object')

		data = content if content is not None else file.read()
		size = len(data)
		ext = guessImageType(data[:32])
		if ext is None:
			raise ValueError('invalid image file')

		hashes = [md5(data).hexdigest()]
		_exists_id = self.exists(hashed=hashes[0])
		if _exists_id:
			id = _exists_id
			filename = _make_filename(id, ext)
			print ('id {} or hash {} exists!!'.format(id, hashes[0]))
			#raise DuplicateError('already exists')
			return [True, id, filename]
		ids = [_make_id(hashes[0])]
		if 'id' in kwd and kwd['id'] and kwd['id'] not in ids:
			ids += [kwd['id']]

		from image import SimpImage, MIN_QUALITY

		max_file_size = int(self.get_config('max_file_size'))
		max_jpeg_quality = int(self.get_config('max_jpeg_quality'))
		max_width = int(self.get_config('max_width'))
		max_height = int(self.get_config('max_height'))

		if size > max_file_size: max_jpeg_quality -= 1
		if max_jpeg_quality < MIN_QUALITY: max_jpeg_quality = MIN_QUALITY

		im = SimpImage(blob=data)
		meta = im.meta
		if meta['width'] > max_width or meta['height'] > max_height:
			if self.get_config('auto_scale') and im.thumbnail(max_width, max_height):
				if im.format == 'JPEG' and im.quality > max_jpeg_quality:
					im.quality = max_jpeg_quality
				data = im.get_blob()
				size = len(data)
				print im.meta
				print 'new scaled size {}'.format(size)
				hashes += [md5(data).hexdigest()]
			else:
				raise ValueError('file: {} dimension {}x{} is too big, max is {}x{}'.format(kwd['name'] if 'name' in kwd else '', meta['width'], meta['height'], max_width, max_height))

		if im.format == 'JPEG':
			if im.quality > max_jpeg_quality:
				print 'quality {} is too high, hash {}'.format(im.quality, hashes[0])
				from tempfile import NamedTemporaryFile
				_tmp = NamedTemporaryFile('w+b',dir=self.get_config('temp_root'),delete=False)
				_tmp.file.close()
				save_file(_tmp.name, blob=data)
				if jpegoptim(_tmp.name):
					fp = open(_tmp.name)
					data = fp.read()
					size = len(data)

					# print 'new optimized size {}'.format(size)
					fp.close()
					_tmp.unlink(_tmp.name)
					del im
					im = SimpImage(blob=data)
					meta = im.meta
					hashes += [md5(data).hexdigest()]
				else:
					raise EnvironmentError('jpeg qualty is too high, or need jpegoptim')
		elif im.format == 'PNG' and self.get_config('force_jpeg'):
			im.format = 'JPEG'
			im.quality = max_jpeg_quality
			data = im.get_blob()
			size = len(data)
			hashes += [md5(data).hexdigest()]
			ext = 'jpg'
			meta = im.meta
		del im

		if (size > max_file_size):
			raise ValueError('file: {} size {} is too big, max is {}'.format(kwd['name'] if 'name' in kwd else '', size, max_file_size))

		hashed = hashes[len(hashes)-1] #md5(data).hexdigest()
		# print ('md5 hash: {}'.format(hashed))

		# TODO: add for support (md5 + size) id
		id = _make_id(hashed)

		# print ('new filename: %r' % filename)

		# TODO: fix for support s3 front browse
		_exists_id = self.exists(id) or self.exists(hashed=hashed)
		if _exists_id:
			id = _exists_id
			filename = _make_filename(id, ext)
			print ('id {} or hash {} exists!!'.format(id, hashed))
			#raise DuplicateError('already exists')
			return [True, id, filename]
		filename = _make_filename(id, ext)
		# print ('id: {}'.format(id))

		# if ctype is None or ctype == '':
		from _util import guess_mimetype
		ctype = guess_mimetype(filename)

		# save to mongodb
		spec = {'_id': id,'filename': filename, 'hash': hashes, 'mime': ctype, 'size': size, 'meta': meta, 'ids': ids}

		if 'name' in kwd and isinstance(kwd['name'], (str, unicode)):
			spec['name'] = kwd['name']

		for k in ['created', 'app_id']:
			if k in kwd and kwd[k]:
				spec[k] = kwd[k]

		if self._store_exists(id, filename=filename):
			self._save_meta(id, spec)
			return [True, id, filename]

		rr = self._put(data, **spec)
		if rr:
			return [True, rr, filename]