我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用Image.new()。
def gen_captcha(text, fnt, fnt_sz, file_name, fmt='JPEG'): """Generate a captcha image""" # randomly select the foreground color fgcolor = random.randint(0,0xffff00) # make the background color the opposite of fgcolor bgcolor = fgcolor ^ 0xffffff # create a font object font = ImageFont.truetype(fnt,fnt_sz) # determine dimensions of the text dim = font.getsize(text) # create a new image slightly larger that the text im = Image.new('RGB', (dim[0]+5,dim[1]+5), bgcolor) d = ImageDraw.Draw(im) x, y = im.size r = random.randint # draw 100 random colored boxes on the background for num in range(100): d.rectangle((r(0,x),r(0,y),r(0,x),r(0,y)),fill=r(0,0xffffff)) # add the text to the image d.text((3,3), text, font=font, fill=fgcolor) im = im.filter(ImageFilter.EDGE_ENHANCE_MORE) # save the image to a file im.save(file_name, format=fmt)
def new_image(self, **kwargs): back_color = kwargs.get("fill_color", "white") fill_color = kwargs.get("back_color", "black") if fill_color.lower() != "black" or back_color.lower() != "white": if back_color.lower() == "transparent": mode = "RGBA" back_color = None else: mode = "RGB" else: mode = "1" img = Image.new(mode, (self.pixel_size, self.pixel_size), back_color) self.fill_color = fill_color self._idr = ImageDraw.Draw(img) return img
def whitespace(image, size, whitespace=False, whitespace_color=None, **kwargs): if not whitespace: return image if whitespace_color is None: whitespace_color = FILER_WHITESPACE_COLOR if whitespace_color is None: whitespace_color = '#fff' old_image = image source_x, source_y = image.size target_x, target_y = size image = Image.new('RGBA', (target_x, target_y), whitespace_color) if source_x < target_x and source_y < target_y: # whitespace all around image.paste(old_image, ( (target_x - source_x) / 2, (target_y - source_y) / 2)) elif source_x < target_x: # whitespace on top and bottom only image.paste(old_image, ((target_x - source_x) / 2, 0)) elif source_y < target_y: # whitespace on sides only image.paste(old_image, (0, (target_y - source_y) / 2)) else: # no whitespace needed image = old_image return image
def processOutputLine(self, line): line = line[:-1] #print "[DemuxTask]", line MSG_NEW_FILE = "---> new File: " MSG_PROGRESS = "[PROGRESS] " MSG_NEW_MP2 = "++> Mpg Audio: PID 0x" MSG_NEW_AC3 = "++> AC3/DTS Audio: PID 0x" if line.startswith(MSG_NEW_FILE): file = line[len(MSG_NEW_FILE):] if file[0] == "'": file = file[1:-1] self.haveNewFile(file) elif line.startswith(MSG_PROGRESS): progress = line[len(MSG_PROGRESS):] self.haveProgress(progress) elif line.startswith(MSG_NEW_MP2) or line.startswith(MSG_NEW_AC3): try: self.currentPID = str(int(line.split(': PID 0x',1)[1].split(' ',1)[0],16)) except ValueError: print "[DemuxTask] ERROR: couldn't detect Audio PID (projectx too old?)"
def apply_watermark(im, mark, position, opacity=1): """Adds a watermark to an image.""" if opacity < 1: mark = reduce_opacity(mark, opacity) if im.mode != 'RGBA': im = im.convert('RGBA') # create a transparent layer the size of the image and draw the # watermark in that layer. layer = Image.new('RGBA', im.size, (0, 0, 0, 0)) if position == 'tile': for y in range(0, im.size[1], mark.size[1]): for x in range(0, im.size[0], mark.size[0]): layer.paste(mark, (x, y)) elif position == 'scale': # scale, but preserve the aspect ratio ratio = min( float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1]) w = int(mark.size[0] * ratio) h = int(mark.size[1] * ratio) mark = mark.resize((w, h)) layer.paste(mark, (round((im.size[0] - w) / 2), round((im.size[1] - h) / 2))) else: layer.paste(mark, position) # composite the watermark with the layer return Image.composite(layer, im, layer)
def did_load(self): toolImagenames = {'Dot':'dots', 'Undo':'undo', 'New':'new', 'Save':'save', 'Prev':'preview', 'Zoom':'zoom', 'Load':'load', 'Grd':'grid', 'Lin':'lines', 'Exit': 'exit', 'Lvl': 'zoomlevel', 'Dith': 'dither_off', 'Char':'charinfo', 'Pan': 'pan', 'Bru1':'brush_1_on', 'Bru2':'brush_2', 'Bru6':'brush_6', 'BruC':'brush_char', 'Redo':'redo', 'MirX':'flipx', 'MirY':'flipy', 'Pan':'pan', 'PPos':'preview_position', 'Sel':'selection','Up':'offset_up','Down':'offset_down','Left':'offset_left' ,'Right':'offset_right','Prg':'prg','Koa':'koala'} #counter = 0 for subby in self.subviews[0].subviews: #print "subview " + str(counter) + ": " + subby.title #counter += 1 fileName = 'icons/tool_' + toolImagenames[subby.title] + '_64.png' subby.background_image = ui.Image.named(fileName) subby.title = "" # Automatically assigns functions to toolbar buttons with same name
def eval_black_white(self): new = Image.new("RGB", (140, 75)) pix = new.load() orgpix = self.img.load() thresh = 4 for x in range(new.size[0]): for y in range(new.size[1]): rgb = orgpix[x, y] r, g, b = rgb pix[x, y] = (255, 255, 255) if r > max(b, g) + thresh: pix[x, y] = (0, 0, 0) if g < min(r, b): pix[x, y] = (0, 0, 0) if g > max(r, b) + thresh: pix[x, y] = (0, 0, 0) if b > max(r, g) + thresh: pix[x, y] = (0, 0, 0) self.img = new self.pixels = self.img.load()
def test_bw(self): image = Image.new('RGB', (800, 600)) processed = processors.colorspace(image, bw=True) self.assertEqual(processed.mode, 'L') image = Image.new('RGBA', (800, 600)) processed = processors.colorspace(image, bw=True) self.assertEqual(processed.mode, 'LA') image = Image.new('L', (800, 600)) processed = processors.colorspace(image, bw=True) self.assertEqual(processed.mode, 'L') image = Image.new('LA', (800, 600)) processed = processors.colorspace(image, bw=True) self.assertEqual(processed.mode, 'LA')
def create_wallpaper(screen, urls, size=(100, 100), randomise=False): if randomise: random.shuffle(urls) wallpaper = Image.new("RGB", screen, "blue") width = int(math.ceil(float(screen[0]) / size[0])) height = int(math.ceil(float(screen[1]) / size[1])) offset = [0,0] for i in xrange(height): y = size[1] * i for j in xrange(width): x = size[0] * j photo = load_photo(urls.pop()) if photo.size != size: photo = photo.resize(size, Image.BICUBIC) wallpaper.paste(photo, (x, y)) del photo return wallpaper
def mark(self, path, position=POSITION_BOTTOM_RIGHT): '''????????''' try: img = Image.open(path) except IOError: return None if img.size[0] < self._mosaic.size[0]: print 'width', img.size[0], self._mosaic.size[0] return None if img.size[1] < self._mosaic.size[1]: print 'height', img.size[1], self._mosaic.size[1] return None img_area = img.size[0] * img.size[1] mosaic_area = self._mosaic.size[0] * self._mosaic.size[1] ratio = 4 if img_area < mosaic_area * ratio: return None self._locate(img, position) layer = Image.new('RGBA', img.size, (0, 0, 0, 0)) layer.paste(self._mosaic, self.box) return Image.composite(layer, img, layer)
def generate_clouds(self): y = self.cloud_height while self.cloud_height < self.bounds.h * 2: q = min(self.climb, DIFFICULTY_Q) min_dist = int(MAX_CLOUD_DIST * q / DIFFICULTY_Q) max_dist = int(MAX_CLOUD_DIST / 2 + min_dist / 2) self.cloud_height += random.randint(min_dist, max_dist) rect = Rect(random.random() * (self.bounds.w - 150), self.cloud_height, 0, 0) cloud = Cloud(rect, self) if random.random() < ENEMY_DENSITY: #generate new enemy rect = Rect(0, 0, 64, 64) rect.center(cloud.frame.center()) rect.y = cloud.frame.top() - 15 enemy = Enemy(rect, self) enemy.velocity = cloud.velocity
def end_game(self): self.game_state = GAME_DEAD self.player.velocity = Point(0, 0) death_loc = self.player.frame.center() death_loc.y = max(death_loc.y, 80) self.player.die() del self.player self.player = None score = int(self.climb / 10) if self.high_scores.is_high_score(player_name, score): self.smoke_special.frame.center(death_loc) self.smoke_special.configure(frame_count=0, is_done=False) #console.hud_alert('New high score!') # for debugging purposes run_in_thread(high_score_sounds) fmt = 'Congratulations {}:\nYou have a new high score!' self.high_score_msg = fmt.format(player_name) else: self.smoke_normal.frame.center(death_loc) self.smoke_normal.configure(frame_count=0, is_done=False)
def simpleDraw(text,width=100,height=40,bgcolor=(255,255,255)): '''????''' #?????? image = Image.new('RGB',(width,height),bgcolor) #???? font = ImageFont.truetype('FreeSans.ttf',30) #???? fontcolor = (0,0,0) #??draw???draw???????? draw = ImageDraw.Draw(image) #???,(0,0)????? draw.text((0,0),'1234',font=font,fill=fontcolor) #??draw del draw #?????? image.save('1234_1.jpeg')
def __fixup(self, im1): # convert image to suitable mode if isinstance(im1, _Operand): # argument was an image. if im1.im.mode in ("1", "L"): return im1.im.convert("I") elif im1.im.mode in ("I", "F"): return im1.im else: raise ValueError, "unsupported mode: %s" % im1.im.mode else: # argument was a constant if _isconstant(im1) and self.im.mode in ("1", "L", "I"): return Image.new("I", self.im.size, im1) else: return Image.new("F", self.im.size, im1)
def invert(image): "Invert a channel" image.load() return image._new(image.im.chop_invert()) ## # Compare images, and return lighter pixel value # (max(image1, image2)). # <p> # Compares the two images, pixel by pixel, and returns a new image # containing the lighter values. # # @param image1 First image. # @param image1 Second image. # @return An image object.
def lighter(image1, image2): "Select the lighter pixels from each image" image1.load() image2.load() return image1._new(image1.im.chop_lighter(image2.im)) ## # Compare images, and return darker pixel value # (min(image1, image2)). # <p> # Compares the two images, pixel by pixel, and returns a new image # containing the darker values. # # @param image1 First image. # @param image1 Second image. # @return An image object.
def _pilbitmap_check(): global _pilbitmap_ok if _pilbitmap_ok is None: try: im = Image.new("1", (1,1)) Tkinter.BitmapImage(data="PIL:%d" % im.im.id) _pilbitmap_ok = 1 except Tkinter.TclError: _pilbitmap_ok = 0 return _pilbitmap_ok # -------------------------------------------------------------------- # PhotoImage ## # Creates a Tkinter-compatible photo image. This can be used # everywhere Tkinter expects an image object. If the image is an RGBA # image, pixels having alpha 0 are treated as transparent.
def init_set(): global canvas_width, canvas_height, white, black, red, master, size, user_close, image1, draw, w, b canvas_width = 560 canvas_height = 560 white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) master = Tk() master.title("Draw digit") size = 28, 28 user_close = 0 image1 = Image.new("RGB", (canvas_width, canvas_height), black) draw = ImageDraw.Draw(image1) w = Canvas(master, width=canvas_width, height=canvas_height + 20) b = Button(master, text="Predict", command=call_predict) # Callback function when the user clicks on "Predict" button
def extractFunction(font_loc): white = (255, 255, 255) # use a truetype font font = ImageFont.truetype(font_loc, 280) im = Image.new("RGB", (280, 280), white) draw = ImageDraw.Draw(im) for code in range(ord('a'), ord('z') + 1): w, h = draw.textsize(chr(code), font=font) im = Image.new("RGB", (w, h), white) draw = ImageDraw.Draw(im) draw.text((0, 0), chr(code), font=font, fill="#000000") convert_im(code, im) #im.save(chr(code) + str(time.time()) + ".png") for code in range(ord('A'), ord('Z') + 1): w, h = draw.textsize(chr(code), font=font) im = Image.new("RGB", (w, h), white) draw = ImageDraw.Draw(im) draw.text((0, 0), chr(code), font=font, fill="#000000") convert_im(code, im) #im.save(chr(code) + str(time.time()) + ".png")
def image_saver(config, imageName='webgobbler.bmp', generateSingleImage=False): ''' Continuously generate new images (using the assembler_superpose) and save them into a file. config (an applicationConfig object) : the program configuration imageName (string): name of image to save (eg."toto.jpeg","dudu.png"...) generateSingleImage (bool): If True, will generate a single image. ''' log = logging.getLogger('image_saver') a = assembler_superpose(pool=imagePool(config=config), config=config) a.start() try: while True: log.info("Generating a new image to %s" % imageName) a.superposeB() # Evolve current image a.saveImageTo(imageName) if generateSingleImage: break log.info("Will generate a new image in %d seconds." % config["program.every"]) time.sleep(config["program.every"]) finally: a.shutdown() a.join()
def __init__(self): self._image = pilImage.new('RGB', (X, Y), colors[white]) self._draw = ImageDraw.Draw(self._image) for font in 'Tahoma Verdana Arial Helvetica'.split(): try: font = ImageFont.truetype(font + '.ttf', 12) except (AttributeError, IOError): font = None if font: break else: try: font = ImageFont.load_default() except (AttributeError, IOError): font = None self._font = font
def termPrintln(self, text): if(self.terminalCursor>9): self.terminalCursor = 0 self.terminalBuffer = [""]*20 self.refresh() self.termPrint(text) self.terminalCursor += 1 ## Print new text in place of current line (Low Refresh Rate) # @param self The object pointer. # @param text The text to print to the screen. # @remark # To use this function in your program: # @code # ... # screen.termReplaceLastLine("Replaced!") # @endcode
def plot_mouse_traffic(mouse_data): picture = Image.new("RGB", (1600, 800), "white") pixels = picture.load() click_size = 4 x, y = INIT_X, INIT_Y for data_point in mouse_data: status = data_point[0] x = x + data_point[1] y = y + data_point[2] if (status == 1): for i in range(-1*click_size, click_size): for j in range(-1*click_size, click_size): pixels[x + i , y + j] = (0, 0, 0, 0) else: pixels[x, y] = (255, 0, 0, 0) print('Saving picture...') picture.save("mouse_traffic.png", "PNG")
def ca_data(height,width,dorandom,rulenum): # Create the first row, either randomly, or with a single 1 if dorandom: first_row = [randint(0,1) for i in range(width)] else: first_row = [0]*width first_row[width/2] = 1 results = [first_row] # Convert the rule number to a list of outcomes. rule = [(rulenum/pow(2,i)) % 2 for i in range(8)] for i in range(height-1): data = results[-1] # Determine the new row based on the old data. We first make an # integer out of the value of the old row and its two neighbors # and then use that value to get the outcome from the table we # computed earlier new = [rule[4*data[(j-1)%width]+2*data[j]+data[(j+1)%width]] for j in range(width)] results.append(new) return results
def pil_render(data,height,width,fname="bs.png"): import Image, ImageDraw img = Image.new("RGB",(width,height),(255,255,255)) draw = ImageDraw.Draw(img) for y in range(height): for x in range(width): if data[y][x]: draw.point((x,y),(0,0,0)) img.save(fname,"PNG") return
def pil_render_lines(lines,height=300,width=300,fname="bs.png"): import Image,ImageDraw img = Image.new("RGB",(width,height),(255,255,255)) draw = ImageDraw.Draw(img) for line in lines: draw.line(line,(0,0,0)) img.save(fname,"PNG") #os.system("display %s" % fname) # use ImageMagick to display return
def windRoseImageSetup(self): """Create image object to draw on.""" try: self.image = Image.open(self.image_back_image) except IOError as e: self.image = Image.new("RGB", (self.image_width, self.image_height), self.image_back_box_color)
def displayCalibrationMsg(): textImage = Image.new('1', (width,height)) draw = ImageDraw.Draw(textImage) draw.text((x, top), 'Hello World!', font=smallFont, fill=255) draw.text((x, top + 25), 'Calibrating...', font=smallFont, fill=255) disp.image(textImage) disp.display()
def displayReadyToBrew(): textImage = Image.new('1', (width,height)) draw = ImageDraw.Draw(textImage) draw.text((x, top), 'Ready', font=smallFont, fill=255) draw.text((x, top + 25), 'to brew.', font=smallFont, fill=255) disp.image(textImage) disp.display()
def displayTimer(): currentTime = time.time() - start h, rem = divmod(currentTime, 3600) m, s = divmod(rem, 60) textImage = Image.new('1', (width,height)) draw = ImageDraw.Draw(textImage) draw.rectangle((0,0,width,height), outline=0, fill=0) draw.text((x, top),"{:0>2}:{:02.0f}".format(int(m), s), font=font, fill=255) disp.image(textImage) disp.display()
def displayPressing(): textImage = Image.new('1', (width,height)) draw = ImageDraw.Draw(textImage) draw.text((x, top), 'Pressing...', font=smallFont, fill=255) disp.image(textImage) disp.display()
def __init__(self, job): self.job = job job.Menus = self s = self.job.project.menutemplate.settings self.color_headline = tuple(s.color_headline.getValue()) self.color_button = tuple(s.color_button.getValue()) self.color_highlight = tuple(s.color_highlight.getValue()) self.spu_palette = [ 0x60, 0x60, 0x60 ] + s.color_highlight.getValue() ImagePrepareTask(job) nr_titles = len(job.project.titles) job.titles_per_menu = s.cols.getValue()*s.rows.getValue() job.nr_menus = ((nr_titles+job.titles_per_menu-1)/job.titles_per_menu) #a new menu_count every 4 titles (1,2,3,4->1 ; 5,6,7,8->2 etc.) for menu_count in range(1 , job.nr_menus+1): num = str(menu_count) spuxmlfilename = job.workspace+"/spumux"+num+".xml" menubgpngfilename = job.workspace+"/dvd_menubg"+num+".png" highlightpngfilename = job.workspace+"/dvd_highlight"+num+".png" MenuImageTask(job, menu_count, spuxmlfilename, menubgpngfilename, highlightpngfilename) png2yuvTask(job, menubgpngfilename, job.workspace+"/dvdmenubg"+num+".yuv") menubgm2vfilename = job.workspace+"/dvdmenubg"+num+".mv2" mpeg2encTask(job, job.workspace+"/dvdmenubg"+num+".yuv", menubgm2vfilename) menubgmpgfilename = job.workspace+"/dvdmenubg"+num+".mpg" menuaudiofilename = s.menuaudio.getValue() MplexTask(job, outputfile=menubgmpgfilename, inputfiles = [menubgm2vfilename, menuaudiofilename], weighting = 20) menuoutputfilename = job.workspace+"/dvdmenu"+num+".mpg" spumuxTask(job, spuxmlfilename, menubgmpgfilename, menuoutputfilename)
def decrypt(ciphername,password): cipher = open(ciphername,'r') ciphertext = cipher.read() obj2 = AES.new(password, AES.MODE_CBC, 'This is an IV456') decrypted = obj2.decrypt(ciphertext) decrypted = decrypted.replace("n","") newwidth = decrypted.split("w")[1] newheight = decrypted.split("h")[1] heightr = "h" + str(newheight) + "h"
def case1(): h = 60 w = h * 4 image = Image.new('RGB', (w, h), (255, 255, 0)) fonts = ImageFont.truetype("arial.ttf", 36) draw = ImageDraw.Draw(image) for x in range(w): for y in range(h): draw.point((x, y), fill=rndcolor()) for t in range(4): # draw.text((60*t+10,10),rndchar(),font=fonts,fill=rndcolor2()) draw.text((60 * t + 10, 10), rndchar(), font=fonts, fill=rndcolor2()) image = image.filter(ImageFilter.BLUR) image.save("data/1.jpg", 'jpeg')
def makeimg(size): if settings.CAPTCHA_BACKGROUND_COLOR == "transparent": image = Image.new('RGBA', size) else: image = Image.new('RGB', size, settings.CAPTCHA_BACKGROUND_COLOR) return image
def captcha_refresh(request): """ Return json with new captcha for ajax refresh request """ was_limited = getattr(request, 'limited', False) if was_limited: return HttpResponseForbidden() if not request.is_ajax(): raise Http404 new_key = CaptchaStore.pick() to_json_response = { 'key': new_key, 'image_url': captcha_image_url(new_key), } return HttpResponse(json.dumps(to_json_response), content_type='application/json')
def draw_text_with_halo(img, position, text, font, col, halo_col): halo = Image.new('RGBA', img.size, (0, 0, 0, 0)) ImageDraw.Draw(halo).text(position, text, font = font, fill = halo_col) blurred_halo = halo.filter(ImageFilter.BLUR) ImageDraw.Draw(blurred_halo).text(position, text, font = font, fill = col) return Image.composite(img, blurred_halo, ImageChops.invert(blurred_halo))