Python Image 模块,open() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用Image.open()。
def convert(width,height):
im = Image.open("C:\\xxx\\test.jpg")
out = im.resize((width, height),Image.ANTIALIAS)
out.save("C:\\xxx\\test.jpg")
def play(self, sender):
# self.mode = console.alert('Race mode',
# button1='1. Blind draw',
# button2='2. Timed vectors'
# )
self.hide_all()
#self.show_play_menu() dialog
self.show_edit_view()
self.load_actual(burn_waypoints_in=True)
with io.BytesIO(self.edit_view.img.to_png()) as fp:
playfield = pilImage.open(fp).resize((int(self.bg.width), int(self.bg.height))).load()
for layer in self.play_layers:
layer.set_map(self.edit_view.waypoints, playfield, self.multiplier)
self.show_play_layers()
self.turn = -1
self.next_turn()
def load_texture(image_file, repeat=False):
"""Carga una textura desde un archivo image_file"""
img = Image.open(image_file)
data = numpy.array(list(img.getdata()), numpy.int8)
tex = glGenTextures(1)
glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
glBindTexture(GL_TEXTURE_2D, tex)
if repeat:
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
else:
glTexParameterf(GL_TEXTURE_2D, GL_CLAMP)
glTexParameterf(GL_TEXTURE_2D, GL_CLAMP)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img.size[0], img.size[1], GL_UNSIGNED_BYTE, data)
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
return tex
def get_colors(f, do_shuffle=True):
try:
import Image
except Exception:
from PIL import Image
scale = 1./255.
im = Image.open(f)
data = list(im.convert('RGB').getdata())
res = []
for r,g,b in data:
res.append([r*scale,g*scale,b*scale])
if do_shuffle:
from numpy.random import shuffle
shuffle(res)
return res
def get_colors_from_file(self, fn):
import Image
from numpy.random import shuffle
def p(f):
return float('{:0.5f}'.format(f))
scale = 1./255.
im = Image.open(fn)
w, h = im.size
rgbim = im.convert('RGB')
res = []
for i in range(0, w):
for j in range(0, h):
r, g, b = rgbim.getpixel((i, j))
res.append([p(r*scale), p(g*scale), p(b*scale)])
shuffle(res)
self.colors = res
self.ncolors = len(res)
def create_thumb(img_name):
image = Image.open('{}.tiff'.format(img_name))
(imageW, imageH) = image.size
if imageW > imageH:
ratio = thumb_size / imageW
newWidth = 400
newHeight = int(imageH * ratio)
else:
ratio = thumb_size / imageH
newHeight = 400
newWidth = int(imageW * ratio)
image = image.resize((newWidth, newHeight), Image.lanczos)
outfh = open('{}_thumb.tiff'.format(img_name), 'wb')
image.save(outfh, format='TIFF')
outfh.close()
def clean_zip_file(self):
"""Open the zip file a first time,to check that it is a valid zip archive.
We'll open it again in a moment,so we have some duplication,but let's focus
on keeping the code easier to read!
"""
zip_file = self.cleaned_data['zip_file']
try:
zip = zipfile.ZipFile(zip_file)
except BadZipFile as e:
raise forms.ValidationError(str(e))
bad_file = zip.testzip()
if bad_file:
zip.close()
raise forms.ValidationError('"%s" in the .zip archive is corrupt.' % bad_file)
zip.close() # Close file in all cases.
return zip_file
def check_md5sum_change(src_file):
"""Returns True if src_file has a different md5sum"""
src_md5 = get_md5sum(src_file)
src_md5_file = src_file + '.md5'
src_file_changed = True
if os.path.exists(src_md5_file):
with open(src_md5_file, 'r') as file_checksum:
ref_md5 = file_checksum.read()
if src_md5 == ref_md5:
src_file_changed = False
if src_file_changed:
with open(src_md5_file, 'w') as file_checksum:
file_checksum.write(src_md5)
return src_file_changed
def image_file_to_string(filename, cleanup = cleanup_scratch_flag, graceful_errors=True):
"""Applies tesseract to filename; or,if image is incompatible and graceful_errors=True,
converts to compatible format and then applies tesseract. Fetches resulting text.
If cleanup=True,delete scratch files after operation."""
try:
try:
call_tesseract(filename, scratch_text_name_root)
text = util.retrieve_text(scratch_text_name_root)
except errors.Tesser_General_Exception:
if graceful_errors:
im = Image.open(filename)
text = image_to_string(im, cleanup)
else:
raise
finally:
if cleanup:
util.perform_cleanup(scratch_image_name, scratch_text_name_root)
return text
def genLines(image=None):
PrintGood('This is going to return OCR on either a list of images or full images')
if isinstance(image, list) == False:
image = PromptList('Which image/images to OCR: ', image)
Found = []
for image in image:
image = Image.open(image)
with PyTessBaseAPI() as api:
api.Setimage(image)
Boxes = api.GetComponentimages(RIL.TEXTLINE, True)
print 'Found {} textline image components.'.format(len(Boxes))
for i, (im, Box, _, _) in enumerate(Boxes):
# im is a PIL image object
# Box is a dict with x,y,w and h keys
api.SetRectangle(Box['x'], Box['y'], Box['w'], Box['h'])
ocrResult = api.GetUTF8Text().split(' ')
conf = api.MeanTextConf()
ocrResult = [word.strip() for word in ocrResult]
Found.append(ocrResult)
print (u"Box[{0}]: x={x},y={y},w={w},h={h},"
"confidence: {1},text: {2}").format(i, conf, ocrResult, **Box)
return Found
def Spaces(image=None):
PrintGood('This returns the number of spaces in a specific image or images')
if isinstance(image, list) == False:
image = PromptList('Which image/images to Scan: ', image)
for image in image:
image = Image.open(image)
with PyTessBaseAPI() as api:
api.Setimage(image)
Boxes = api.GetComponentimages(RIL.TEXTLINE, True)
Spaces = 0
for i, _) in enumerate(Boxes):
im.save('saving{}.jpg'.format(i))
api.SetRectangle(Box['x'], Box['h'])
ocrResult = api.GetUTF8Text()
conf = api.MeanTextConf()
text = str(ocrResult).replace('\n', '').split(' ')
Spaces = len(text) + Spaces
return int(Spaces)
def ocrToDict(image=None, listofwords=[]):
#image can be a list of files
Words = {}
if len(listofwords) == 0:
PrintFail('You need to input a list of words')
if 'y' in str(raw_input("Do you want to search for lyrics Now? ")).lower():
artist = raw_input("Artist: ")
song = raw_input("Song: ")
listofwords = GrabSongLyrics(artist, song)
print(listofwords)
else:
return
if isinstance(image, image)
for i, image in enumerate(image):
Words['Clean'][i] = imagetoOCR(image, listofwords)
with open('{}Transcript.json'.format(Words[1]), 'w') as f:
json.dump(Words, f)
def WritetoImage(output, txt, size=45, input='background.jpg'):
output = str(output).replace('.png', '').replace('.jpg', '')
i = Image.open(input)
font = ImageFont.load_default()
txt = txt.split(' ')
r = []
for part in txt:
r.append(str(part).replace(' ', ''))
txt = r
a = ''
while len(txt) > 0:
try:
for e in range(7):
item = txt[0]
txt.remove(item)
a = a + ' ' + str(item)
a = a + '\n'
except:
break
text_col = (255, 255, 255) # bright green
halo_col = (0, 0) # black
i2 = draw_text_with_halo(i, (20, 40), a, font, text_col, halo_col)
i2.save('{}.png'.format(output))
def insert_text(img, dest, msg):
image = Image.open(img)
width, height = image.size
if image.mode[:3] != "RGB" or width * height * 3 < len(msg) + RESERVED_PIXELS * 3:
raise IndexError("Unable to use this picture")
bits = bin(len(msg))[2:].zfill(RESERVED_PIXELS * 3)
msg = bits + msg
msg = enumerate(msg + "0" * (3 - len(msg) % 3))
p = image.load()
for i, j in pixels(image.size):
try:
rgb = map(lambda color, bit: color - (color % 2) + int(bit), p[i, j][:3], [msg.next()[1] for _ in xrange(3)])
p[i, j] = tuple(rgb)
except stopiteration:
image.save(dest, "PNG", quality = 100)
return
def extract_text(img):
image = Image.open(img)
length = image.size
p = image.load()
leng = ""
for pix in pixels(length):
leng += "".join("1" if color % 2 else "0" for color in p[pix][:3])
if len(leng) >= RESERVED_PIXELS * 3:
leng = int(leng, 2)
break
binary_information = ""
for pix in pixels(length):
binary_information += "".join("1" if color % 2 else "0" for color in p[pix][:3])
return binary_information[RESERVED_PIXELS * 3 : leng + RESERVED_PIXELS * 3]
def create_py(self, nb, force=False):
"""Create the python script from the notebook node"""
# Although we would love to simply use ``nbconvert.export_python(nb)``
# this causes troubles in other cells processed by the ipython
# directive. Instead of getting something like ``Out [5]:``,we get
# some weird like '[0;31mOut[[1;31m5[0;31m]: [0m' which look like
# color information if we allow the call of nbconvert.export_python
if list(map(int, re.findall('\d+', nbconvert.__version__))) >= [4, 2]:
py_file = os.path.basename(self.py_file)
else:
py_file = self.py_file
spr.call(['jupyter', 'nbconvert', '--to=python',
'--output=' + py_file, '--log-level=%s' % logger.level,
self.outfile])
with open(self.py_file) as f:
py_content = f.read()
# comment out ipython magics
py_content = re.sub('^\s*get_ipython\(\).magic.*', '# \g<0>',
py_content, flags=re.MULTILINE)
with open(self.py_file, 'w') as f:
f.write(py_content)
def _parsejpg(self, filename):
# Extract info from a JPEG file
if Image is None:
self.error('PIL not installed')
try:
f = open(filename, 'rb')
im = Image.open(f)
except Exception, e:
self.error('Missing or incorrect image file: %s. error: %s' % (filename, str(e)))
else:
a = im.size
# We shouldn't get into here,as Jpeg is RGB=8bpp right(?),but,just in case...
bpc=8
if im.mode == 'RGB':
colspace='DeviceRGB'
elif im.mode == 'CMYK':
colspace='DeviceCMYK'
else:
colspace='DeviceGray'
# Read whole file from the start
f.seek(0)
data = f.read()
f.close()
return {'w':a[0],'h':a[1],'cs':colspace,'bpc':bpc,'f':'DCTDecode','data':data}
def _parsegif(self, filename):
# Extract info from a GIF file (via PNG conversion)
if Image is None:
self.error('PIL is required for GIF support')
try:
im = Image.open(filename)
except Exception, str(e)))
else:
# Use temporary file
f = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
tmp = f.name
f.close()
if "transparency" in im.info:
im.save(tmp, transparency = im.info['transparency'])
else:
im.save(tmp)
info = self._parsepng(tmp)
os.unlink(tmp)
return info
def setupTexturemaps(self):
this_folder = os.path.dirname(os.path.abspath(__file__))
image_path = os.path.join(this_folder, "cube_texture_small.png")
img = Image.open(image_path)
imageRGBA = numpy.array(list(img.getdata()), numpy.uint8)
self.m_iTexture = glGenTextures(1)
glBindTexture( GL_TEXTURE_2D, self.m_iTexture )
glTexImage2D( GL_TEXTURE_2D,
0, imageRGBA )
glGenerateMipmap(GL_TEXTURE_2D)
glTexParameteri( GL_TEXTURE_2D, GL_CLAMP_TO_EDGE )
glTexParameteri( GL_TEXTURE_2D, GL_LINEAR )
glTexParameteri( GL_TEXTURE_2D, GL_LINEAR_MIPMAP_LINEAR )
fLargest = glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest)
glBindTexture( GL_TEXTURE_2D, 0 )
return self.m_iTexture != 0
def _parsegif(self, transparency = im.info['transparency'])
else:
im.save(tmp)
info = self._parsepng(tmp)
os.unlink(tmp)
return info
def _get_data(url):
"""Helper function to get data over http or from a local file"""
if url.startswith('http://'):
resp = urllib2.urlopen(url)
encoding = resp.headers.dict.get('content-encoding', 'plain')
data = resp.read()
if encoding == 'plain':
pass
elif encoding == 'gzip':
data = StringIO(data)
data = gzip.GzipFile(fileobj=data).read()
else:
raise RuntimeError('unkNown encoding')
else:
with open(url, 'r') as fid:
data = fid.read()
fid.close()
return data
def decode(self, filename=None):
self.filename = filename or self.filename
if self.filename:
scanner = zbar.ImageScanner()
# configure the reader
scanner.parse_config('enable')
# obtain image data
pil = Image.open(self.filename).convert('L')
width, height = pil.size
try:
raw = pil.tobytes()
except AttributeError:
raw = pil.tostring()
# wrap image data
image = zbar.Image(width, height, 'Y800', raw)
# scan the image for barcodes
result = scanner.scan(image)
# extract results
if result == 0:
return False
else:
for symbol in image:
pass
# clean up
del(image)
# Assuming data is encoded in utf8
self.data = symbol.data.decode(u'utf-8')
self.data_type = self.data_recognise()
return True
else:
return False
def _parsegif(self, transparency = im.info['transparency'])
else:
im.save(tmp)
info = self._parsepng(tmp)
os.unlink(tmp)
return info
def get_colors(f, do_shuffle=True):
from numpy import array
try:
import Image
except Exception:
from PIL import Image
im = Image.open(f)
data = array(list(im.convert('RGB').getdata()),'float')/255.0
res = []
for rgb in data:
res.append(list(rgb))
if do_shuffle:
from numpy.random import shuffle
shuffle(res)
return res
def binary(f): #????????
print f
img = Image.open(f)
#img = img.convert('1')
img = img.convert("RGBA") #???????????????????
pixdata = img.load()
for y in xrange(img.size[1]):
for x in xrange(img.size[0]):
if pixdata[x, y][0] < 90:
pixdata[x, y] = (0, 255)
for y in xrange(img.size[1]):
for x in xrange(img.size[0]):
if pixdata[x, y][1] < 136:
pixdata[x, y][2] > 0:
pixdata[x, y] = (255, 255)
return img
def _get_data(url):
"""Helper function to get data over http or from a local file"""
if url.startswith('http://'):
# Try Python 2,use Python 3 on exception
try:
resp = urllib.urlopen(url)
encoding = resp.headers.dict.get('content-encoding', 'plain')
except AttributeError:
resp = urllib.request.urlopen(url)
encoding = resp.headers.get('content-encoding', 'r') as fid:
data = fid.read()
fid.close()
return data
def extract_line_count(filename, target_dir):
# Extract the line count of a file
example_file = os.path.join(target_dir, filename)
lines = open(example_file).readlines()
start_row = 0
if lines and lines[0].startswith('#!'):
lines.pop(0)
start_row = 1
line_iterator = iter(lines)
tokens = tokenize.generate_tokens(lambda: next(line_iterator))
check_docstring = True
erow_docstring = 0
for tok_type, (erow, _), _ in tokens:
tok_type = token.tok_name[tok_type]
if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'):
continue
elif (tok_type == 'STRING') and check_docstring:
erow_docstring = erow
check_docstring = False
return erow_docstring + 1 + start_row, erow + 1 + start_row
def substract_bg(self, bgpath):
bg = Image.open(bgpath)
img = self.img.convert("P")
bglut = bg.resize((256, 1))
bglut.putdata(range(256))
bglut = list(bglut.convert("RGB").getdata())
lut = img.resize((256, 1))
lut.putdata(range(256))
lut = list(lut.convert("RGB").getdata())
bgpix = bg.load()
pix = img.load()
orgpix = self.img.load()
for x in range(bg.size[0]):
for y in range(bg.size[1]):
rgb_bg = bglut[bgpix[x, y]]
rgb_c = lut[pix[x, y]]
if rgb_c == rgb_bg:
orgpix[x, 255)
def build_toc(self, outdir, outname):
"""Write the Metainfo file toc.ncx."""
self.info('writing %s file...' % outname)
if self.config.epub_tocscope == 'default':
doctree = self.env.get_and_resolve_doctree(self.config.master_doc,
self, prune_toctrees=False,
includehidden=False)
refnodes = self.get_refnodes(doctree, [])
self.toc_add_files(refnodes)
else:
# 'includehidden'
refnodes = self.refnodes
navpoints = self.build_navpoints(refnodes)
level = max(item['level'] for item in self.refnodes)
level = min(level, self.config.epub_tocdepth)
f = codecs.open(path.join(outdir, outname), 'w', 'utf-8')
try:
f.write(_toc_template % self.toc_Metadata(level, navpoints))
finally:
f.close()
def resize(): # for resizing images to 256 by 256 and zooming in on the objects
for s in wanted_classes:
files = glob('data/overlays/' + labels[s]+'/*')
for f in tqdm(files):
images = glob(f+'/*')
for im in images:
# here I am maintianing the origional images and renaming them with a large_ prefix
actual = im
new = f+'/orig_' + im.split('/')[-1]
shutil.move(actual,new)
im = Image.open(new)
x,y = im.size
diff = (x-y)/2
im = im.crop((diff+100,100, x-diff-100, y-100)) # getting a square aspect ratio and zooming in on object by 100 pixels
im = ImageOps.fit(im, (256,256), Image.ANTIALIAS) # reshaping to 256 by 256
im.save(actual)
def load_orgimg(temp_line) :
global org_img
global org_file
global base_path
global org_width, org_height
# print "load_orgimg function!"
org_file = Image.open("%s/data/flickr/%s" %(aflw_path, temp_line), 'r' )
try:
org_img = org_file.load()
except IOError:
print "IOError happens!! because of Image load"
return 0
org_width, org_height = org_file.size
return 1
def load_orgimg(temp_line) :
global org_img
global org_file
global base_path
global org_width, org_height = org_file.size
return 1
def open_image_file(self, filename):
"""
Obtain a handle to an image file
@param filename: Name of the file
@type filename: C{str}
@return: Image file
@rtype: L{Image}
"""
if filename in self.cached_image_files:
im = self.cached_image_files[filename]
else:
im = Image.open(generic.find_file(filename))
self.cached_image_files[filename] = im
return im
def save_imgs(imgs, ret_size=False):
import Image
result = []
for img in imgs:
qiniu_key = upload_by_rawdata(img, len(img))
log.info('upload stream img to qiniu,return: %s' % (qiniu_key,))
img_width = 0
img_height = 0
if ret_size:
s = ''
for c in img.chunks():
s += c
imagefile = StringIO.StringIO(s)
im = Image.open(imagefile)
img_width, img_height = im.size
result.append({'img':'/'+qiniu_key.lstrip('/'),'img_width':img_width,'img_height':img_height})
return result
def resize_img(img_path, size=64,style='jpg', ch_width=200):
try:
img = Image.open(img_path)
(width,height) = img.size
new_width = ch_width
new_height = height * new_width / width
out = img.resize((new_width, new_height), Image.ANTIALIAS)
thumb_filename = gen_thumb_filename(img_path)
filename, ext = os.path.splitext(thumb_filename)
new_file_name = '%s.%s' % (filename, style)
#?????
filesize = os.path.getsize(img_path)/1024
if filesize > size:
quality = int(float(size) / float(filesize) * 100) - 1
else:
quality = 100
out.save(new_file_name, quality=quality)
return new_file_name
except Exception,e:
print Exception,':',e
def _get_data(url):
"""Helper function to get data over http or from a local file"""
if url.startswith('http://'):
# Try Python 2, 'r') as fid:
data = fid.read()
fid.close()
return data
def extract_line_count(filename, filename)
if six.PY2:
lines = open(example_file).readlines()
else:
lines = open(example_file, encoding='utf-8').readlines()
start_row = 0
if lines and lines[0].startswith('#!'):
lines.pop(0)
start_row = 1
line_iterator = iter(lines)
tokens = tokenize.generate_tokens(lambda: next(line_iterator))
check_docstring = True
erow_docstring = 0
for tok_type, 'DEDENT'):
continue
elif (tok_type == 'STRING') and check_docstring:
erow_docstring = erow
check_docstring = False
return erow_docstring+1+start_row, erow+1+start_row
def loadTexture(filename):
try:
from PIL.Image import open as imgopen
except ImportError, err:
from Image import open as imgopen
im = imgopen(filename)
try:
im = im.convert('RGB')
ix, iy, image = im.size[0], im.size[1], im.tobytes("raw", "RGBA", -1)
except SystemError:
ix, "RGBX", -1)
assert ix*iy*4 == len(image), """Unpacked image size for texture is incorrect"""
texID = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, texID)
glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
glTexParameteri(GL_TEXTURE_2D, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, 3, ix, GL_RGBA, image)
return texID
#Used to help sort edges in ccw order
def get_colors(f,'float')/255.0
res = []
for rgb in data:
res.append(list(rgb))
if do_shuffle:
from numpy.random import shuffle
shuffle(res)
return res
def printOut():
# print image
printer.printimage(Image.open('FFA_print.png'), True)
printer.setSize('S')
printer.justify('C')
printer.println(motto)
# printer.println(' ')
printer.justify('C')
printer.boldOn()
printer.println(event)
printer.boldOff()
printer.justify('C')
# printer.println(motto)
printer.println(' ')
# printer.writeBytes(0x1B,0x21,0x1)
printer.println(mill)
printer.println(website)
printer.println(' ')
printer.println(' ')
printer.Feed(3)
# Called when button is briefly tapped.
def printOut():
# print image
printer.printimage(Image.open('vbotPrint.png'), True)
printer.setSize('M')
printer.justify('C')
printer.println(mill)
printer.setSize('S')
printer.println(tag)
printer.println(hours)
printer.println(' ')
printer.boldOn()
printer.println(website)
printer.boldOff()
printer.writeBytes(0x1B, 0x21, 0x1)
printer.println(' ')
printer.println(contact)
printer.println(' ')
printer.println(' ')
printer.Feed(3)
# Called when button is briefly tapped.
def printOut():
# print image
printer.printimage(Image.open('4hlogo_sm3.png'), True)
printer.setSize('S')
printer.println(pledge)
# printer.println(' ')
printer.justify('C')
printer.boldOn()
printer.println(event)
printer.boldOff()
printer.justify('C')
# printer.println(motto)
printer.println(' ')
# printer.writeBytes(0x1B,0x1)
printer.println(mill)
printer.println(' ')
printer.println(' ')
printer.Feed(3)
# Called when button is briefly tapped.
def printOut():
printer.justify('C')
printer.boldOn()
printer.println(event)
printer.boldOff()
# print image
printer.printimage(Image.open('4hlogo_sm3.png'), True)
printer.justify('L')
# printer.setSize('M')
# printer.println(Title)
printer.setSize('S')
printer.println(pledge)
# printer.println(' ')
printer.justify('C')
# printer.println(motto)
printer.println(' ')
# printer.writeBytes(0x1B,0x1)
printer.println(mill)
printer.println(' ')
printer.println(' ')
printer.Feed(3)
# Called when button is briefly tapped.
def getverify(name):
# ????
img = Image.open(name)
# ??????
imgry = img.convert('L')
# ????????????threshold????
out = imgry.point(table, '1')
# out.save('b'+name)
out = removedot(out)
# ????
out.save('o'+name)
# ??
text = image_to_string(out)
# ????
text = text.strip()
text = text.upper()
for r in rep:
text = text.replace(r, rep[r])
# out.save(text+'.jpg')
# print text
return text
def convert(dir,width,height):
file_list = os.listdir(dir)
print(file_list)
for filename in file_list:
path = ''
path = dir+filename
im = Image.open(path)
out = im.resize((256,Image.ANTIALIAS)
print "%s has been resized!"%filename
out.save(path)
def convert(width,height):
im = Image.open("C:\\workspace\\PythonLearn1\\test_1.jpg")
(x, y)= im.size
x_s = width
y_s = y * x_s / x
out = im.resize((x_s, y_s), Image.ANTIALIAS)
out.save("C:\\workspace\\PythonLearn1\\test_1_out.jpg")
def resizePhoto(photo):
thumbnail = photo.replace('.jpg', '.thumbnail.jpg')
try:
im = Image.open(photo)
im.thumbnail((380, 500), Image.ANTIALIAS)
im.save(thumbnail, "JPEG")
return thumbnail
except IOError:
print "cannot create thumbnail for '%s'" % photo
return False
def getRGBTupleFromImg(file_obj, coords=(0,0)):
"""
Extract an #RRGGBB color string from given pixel coordinates
in the given file-like object.
"""
pil_img = Image.open(file_obj)
pil_img = pil_img.convert('RGB')
rgb = pil_img.getpixel(coords)
return rgb
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。