本文整理汇总了Python中PythonMagick.Image.write方法的典型用法代码示例。如果您正苦于以下问题:Python Image.write方法的具体用法?Python Image.write怎么用?Python Image.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PythonMagick.Image
的用法示例。
在下文中一共展示了Image.write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: bmp_or_jpg_to_pdf
# 需要导入模块: from PythonMagick import Image [as 别名]
# 或者: from PythonMagick.Image import write [as 别名]
def bmp_or_jpg_to_pdf(list_of_file_paths, destination_directory, delete_source=False):
operation_result = {}
invalid_file_paths = []
for files in list_of_file_paths:
if os.path.exists(files):
continue
else:
invalid_file_paths.append(files)
list_of_file_paths.remove(files)
for files in list_of_file_paths:
image = PyImage()
image.density("600")
image.read(files)
file_name = os.path.basename(files)
name, ext = os.path.splitext(file_name)
file_name_at_destination = os.path.join(destination_directory, name + ".pdf")
image.write(file_name_at_destination)
if delete_source is True:
for files in list_of_file_paths:
os.remove(files)
if not invalid_file_paths:
operation_result.update({"code": 0, "invalid_file_paths": "None"})
else:
invalid_files = ",".join(list_of_file_paths)
operation_result.update({"code": 1, "invalid_file_paths": invalid_files})
return operation_result
示例2: main
# 需要导入模块: from PythonMagick import Image [as 别名]
# 或者: from PythonMagick.Image import write [as 别名]
def main():
# os.environ["MAGICK_HOME"] = r"path_to_ImageMagick"
if len(sys.argv) == 1:
dirpath = '.'
else:
dirpath = sys.argv[1]
temp_dir = os.path.join(dirpath, '.temp')
if not os.path.exists(temp_dir):
os.mkdir(temp_dir)
for file_name in os.listdir(dirpath):
if not os.path.isfile(file_name) or not file_name.endswith('.pdf'):
continue
print('Converting file {} ...'.format(file_name))
in_path = os.path.join(dirpath, file_name)
with open(in_path, 'rb') as handle:
inputpdf = PdfFileReader(handle)
for i in xrange(inputpdf.numPages):
outputpdf = PdfFileWriter()
outputpdf.addPage(inputpdf.getPage(i))
new_file_name = file_name.replace('.pdf', '') + '_{}.pdf'.format(i)
new_in_path = os.path.join(temp_dir, new_file_name)
with open(new_in_path, 'wb') as handle:
outputpdf.write(handle)
output_file_name = new_file_name.replace('.pdf', '.jpeg')
output_path = os.path.join(dirpath, output_file_name)
p = Image()
p.density('1080')
p.read(os.path.abspath(new_in_path))
p.write(os.path.abspath(output_path))
os.remove(new_in_path)
os.rmdir(temp_dir)
示例3: get
# 需要导入模块: from PythonMagick import Image [as 别名]
# 或者: from PythonMagick.Image import write [as 别名]
def get(self):
self.set_header("Content-Type", "image/jpeg")
image = Image("../image.jpg")
image.resize(Geometry(100, 100))
blob = Blob()
image.write(blob)
self.write(blob.data)
示例4: handle
# 需要导入模块: from PythonMagick import Image [as 别名]
# 或者: from PythonMagick.Image import write [as 别名]
def handle(self, *args, **options):
routes = glob(options['input']+'/routes-*.json')
routes = sorted(routes, lambda x,y:cmp(stat(path.abspath(x))[8], stat(path.abspath(y))[8]))
segment = 0
img = None
for route in routes:
self.stdout.write('Opening route "%s"\n' % route)
rfile = open(route, 'r')
fc = json.load(rfile)
rfile.close()
if segment == 0:
self.stdout.write('Creating image file.\n')
img = Image('1280x720', 'white')
img.draw(DrawableStrokeColor('black'))
img.draw(DrawableStrokeOpacity(0.01))
img.draw(DrawableStrokeWidth(1.0))
for i,feature in enumerate(fc['features']):
coords = feature['geometry']['coordinates']
coords = map(lambda x:self.proj(x), coords)
for start,end in zip(coords[0:-1],coords[1:]):
img.draw(DrawableLine(start[0], start[1], end[0], end[1]))
segment += 1
if segment == options['number']:
self.stdout.write('Writing image file "%s.png".\n' % route)
img.write(route + '.png')
segment = 0
示例5: guardar_img
# 需要导入模块: from PythonMagick import Image [as 别名]
# 或者: from PythonMagick.Image import write [as 别名]
def guardar_img(self, widget, string, img):
filechooser = gtk.FileChooserDialog("Guardar Imagen", None, gtk.FILE_CHOOSER_ACTION_SAVE,
(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK))
filechooser.set_default_response(gtk.RESPONSE_OK)
filechooser.set_current_name(img.split("/")[3])
filter = gtk.FileFilter()
filter.set_name("Todos los archivos")
filter.add_pattern("*")
filechooser.add_filter(filter)
filter = gtk.FileFilter()
filter.set_name("Imágenes")
filter.add_mime_type("image/png")
filter.add_mime_type("image/jpeg")
filter.add_mime_type("image/gif")
filter.add_pattern("*.png")
filter.add_pattern("*.jpg")
filter.add_pattern("*.gif")
filter.add_pattern("*.tif")
filter.add_pattern("*.xpm")
filechooser.add_filter(filter)
respuesta = filechooser.run()
if respuesta == gtk.RESPONSE_OK:
try:
fimg = Image(img)
fimg.write(filechooser.get_filename())
filechooser.destroy()
except:
pass
else:
filechooser.destroy()
示例6: finish_response
# 需要导入模块: from PythonMagick import Image [as 别名]
# 或者: from PythonMagick.Image import write [as 别名]
def finish_response(self, app_iter):
if not self.scale:
self.start_response(self.status, self.headers)
self.output = app_iter
return
CONTENT_LENGTH.delete(self.headers)
inBuffer = StringIO()
try:
for s in app_iter:
self.logger.debug("Writing %d bytes into image buffer." % len(s))
inBuffer.write(s)
finally:
if hasattr(app_iter, 'close'):
app_iter.close()
rawImg = Blob()
rawImg.data = inBuffer.getvalue()
inBuffer.close()
image = Image(rawImg)
self.logger.debug("Scaling image to %s" % self.scaled_size)
image.scale(self.scaled_size[0])
image.write(self.outbuffer)
content_length = self.outbuffer.length()
CONTENT_LENGTH.update(self.headers, content_length)
CACHE_CONTROL.update(self.headers, s_maxage=CACHE_CONTROL.ONE_HOUR)
self.start_response(self.status, self.headers)
示例7: pdf2images
# 需要导入模块: from PythonMagick import Image [as 别名]
# 或者: from PythonMagick.Image import write [as 别名]
def pdf2images(name):
np = getPdfNumPages(name)
for p in range(np):
i = Image()
i.density('200')
i.quality(100)
i.depth(24)
#i.backgroundColor(
#i.channel(
i.read(name + '[' + str(p) + ']')
i.write(name + str(p) + defaultImageExtension)
示例8: rsr2png
# 需要导入模块: from PythonMagick import Image [as 别名]
# 或者: from PythonMagick.Image import write [as 别名]
def rsr2png(rsrfile):
rsr2pct(rsrfile)
pictfile = os.path.splitext(rsrfile)[0]+".pct"
try:
thumb = Image(str(pictfile))
except:
print pictfile
raise
thumb.opacity(100)
thumb.scale(91,91)
thumb.write(str(os.path.splitext(rsrfile)[0]+".png"))
示例9: convert_photo_to_jpeg
# 需要导入模块: from PythonMagick import Image [as 别名]
# 或者: from PythonMagick.Image import write [as 别名]
def convert_photo_to_jpeg(photo_path):
print 'Converting %s to JPEG...' % (photo_path,)
image = Image(photo_path)
image.magick("jpeg")
image.quality(100)
(_, file_name) = os.path.split(photo_path)
file_name = convert_local_filename_to_flickr(file_name)
file_name = os.path.join(tempfile.mkdtemp('.flickrsmartsync'), file_name)
image.write(file_name)
print 'Done converting photo!'
return file_name
示例10: convertMGtoPIL
# 需要导入模块: from PythonMagick import Image [as 别名]
# 或者: from PythonMagick.Image import write [as 别名]
def convertMGtoPIL(magickimage):
'works with grayscale and color'
img = PMImage(magickimage) # make copy
img.depth = 8 # this takes 0.04 sec. for 640x480 image
img.magick = "RGB"
w, h = img.columns(), img.rows()
blb=Blob()
img.write(blb)
data = blb.data
# convert string array to an RGB Pil image
pilimage = Image.fromstring('RGB', (w, h), data)
return pilimage
示例11: manipula_img
# 需要导入模块: from PythonMagick import Image [as 别名]
# 或者: from PythonMagick.Image import write [as 别名]
def manipula_img(self, img_r, nmsuc):
"""Procesa la imagen adquirida en formato xwd y la trasforma en jpg"""
image_final = self.dir_tmp + nmsuc + ".jpg"
contador = 0
if path.exists(image_final):
contador += 1
image_final = self.dir_tmp + nmsuc + "_" + str(contador) + ".jpg"
if path.exists(image_final):
image_final = self.comprueba_nombre(image_final, nmsuc)
img = Image(img_r)
img.scale("1024x768")
img.write(image_final)
exe(image_final, nmsuc)
示例12: thumb
# 需要导入模块: from PythonMagick import Image [as 别名]
# 或者: from PythonMagick.Image import write [as 别名]
def thumb(self, req):
if self.mime_type.startswith('image') \
and guess_extension(self.mime_type) in _image_exts:
file_path = req.cfg.attachments_path + '/' + self.webname()
img = Image(file_path.encode('utf-8'))
width, height = req.cfg.attachments_thumb_size.get()
img.scale(Geometry(width, height))
thumb_path = req.cfg.attachments_thumb_path + '/' + self.webname()
if not exists(dirname(thumb_path)):
makedirs(dirname(thumb_path))
img.write(thumb_path.encode('utf-8'))
示例13: _ps2png
# 需要导入模块: from PythonMagick import Image [as 别名]
# 或者: from PythonMagick.Image import write [as 别名]
def _ps2png(self, filename, relative):
"Try to converts bands.ps -> bands.png and returns absolute filename"
try:
pspath = self.bandsPS()
pngpath = os.path.join(self._resultPath.localPath(), PNGBAND) # Absolute
# Rotate 90 degrees and convert .ps -> .png
from PythonMagick import Image
img = Image(pspath)
img.rotate(90) # For some reason plotband.x rotates image
img.write(pngpath) # Write to .png file
fpngpath = os.path.join(self._resultPath.localPath(relative), PNGBAND) # Format dependent
return fpngpath # If success, return path to .png file
except:
return None
示例14: __init__
# 需要导入模块: from PythonMagick import Image [as 别名]
# 或者: from PythonMagick.Image import write [as 别名]
class Answers:
def __init__(self, filename, i):
self.image = Image()
self.image.density('%d' % DENSITY)
self.image.read('%s[%d]' % (filename, i))
temp = tempfile.NamedTemporaryFile(suffix='.png')
self.image.write(temp.name)
self.pimage = pygame.image.load(temp.name)
temp.close()
def draw(self, screen, C):
pygame.draw.rect(screen, (255, 255, 255), (0, 0, W, H), 0)
scaled = self.pimage
screen.blit(scaled, (0, 0), (C[0], C[1], C[2] - C[0], C[3] - C[1]))
pygame.display.flip()
示例15: walk_menu
# 需要导入模块: from PythonMagick import Image [as 别名]
# 或者: from PythonMagick.Image import write [as 别名]
def walk_menu(entry):
if isinstance(entry, xdg.Menu.Menu) and entry.Show is True:
map(walk_menu, entry.getEntries())
elif isinstance(entry, xdg.Menu.MenuEntry) and entry.Show is True:
# byte 1 signals another entry
conn.sendall('\x01')
img_path = icon_attr(entry.DesktopEntry).encode('utf-8')
if img_path and os.path.isfile(img_path):
try:
# Create an empty image and set the background color to
# transparent. This is important to have transparent background
# when converting from SVG
img = Image()
img.backgroundColor(Color(0, 0, 0, 0xffff))
img.read(img_path)
# scale the image to 48x48 pixels
img.scale(Geometry(48, 48))
# ensure the image is converted to ICO
img.magick('ICO')
b = Blob()
img.write(b)
# icon length plus data
conn.sendall(struct.pack('i', len(b.data)))
conn.sendall(b.data)
except Exception:
conn.sendall(struct.pack('i', 0))
else:
conn.sendall(struct.pack('i', 0))
name = entry.DesktopEntry.getName()
# name length plus data
conn.sendall(struct.pack('i', len(name)))
conn.sendall(name)
command = re.sub(' -caption "%c"| -caption %c',
' -caption "%s"' % name, entry.DesktopEntry.getExec())
command = re.sub(' [^ ]*%[fFuUdDnNickvm]', '', command)
if entry.DesktopEntry.getTerminal():
command = 'xterm -title "%s" -e %s' % (name, command)
# command length plus data
conn.sendall(struct.pack('i', len(command)))
conn.sendall(command)