This document discusses using Python to generate random and dynamic images through CGI scripts. It begins with an overview and introduction to Python CGI programming and the Python Imaging Library (PIL). It then demonstrates a simple Python CGI script that serves a static image file. Next, it shows a random image script that selects a random image file from a directory. The document also covers using PIL to dynamically generate images and build a script that generates a random gradient image. It concludes by discussing building more advanced dynamic image scripts that accept arguments and graph log files.
The goal of this presentation is to broaden your knowledge of Python, exploring some concepts and techniques you might have never heard about. I won't go into too much detail, the goal is only to inspire you to research those features and patterns.
The basics of Python are rather straightforward. In a few minutes you can learn most of the syntax. There are some gotchas along the way that might appear tricky. This talk is meant to bring programmers up to speed with Python. They should be able to read and write Python.
Introduction to the Python programming language (version 2.x)
Ambient intelligence: technology and design
http://bit.ly/polito-ami
Politecnico di Torino, 2015
The goal of this presentation is to broaden your knowledge of Python, exploring some concepts and techniques you might have never heard about. I won't go into too much detail, the goal is only to inspire you to research those features and patterns.
The basics of Python are rather straightforward. In a few minutes you can learn most of the syntax. There are some gotchas along the way that might appear tricky. This talk is meant to bring programmers up to speed with Python. They should be able to read and write Python.
Introduction to the Python programming language (version 2.x)
Ambient intelligence: technology and design
http://bit.ly/polito-ami
Politecnico di Torino, 2015
This is the presentation for the three-session intermediate Python programming course which I developed and successfully presented for the CoderDojo workshop held in Microsoft Silicon Valley in March 2016.
Python 101++: Let's Get Down to Business!Paige Bailey
You've started the Codecademy and Coursera courses; you've thumbed through Zed Shaw's "Learn Python the Hard Way"; and now you're itching to see what Python can help you do. This is the workshop for you!
Here's the breakdown: we're going to be taking you on a whirlwind tour of Python's capabilities. By the end of the workshop, you should be able to easily follow any of the widely available Python courses on the internet, and have a grasp on some of the more complex aspects of the language.
Please don't forget to bring your personal laptop!
Audience: This course is aimed at those who already have some basic programming experience, either in Python or in another high level programming language (such as C/C++, Fortran, Java, Ruby, Perl, or Visual Basic). If you're an absolute beginner -- new to Python, and new to programming in general -- make sure to check out the "Python 101" workshop!
Teach your kids how to program with Python and the Raspberry PiJuan Gomez
RaspberryPis are the new frontier in enabling kids (and curious adults) to get access to an affordable and easy-to-program platform to build cool things. Over a million of these nifty little devices have been sold in less than a year and part of their popularity has been due to how easy it is to start programming on them.
In this session you'll learn how to get started with the Raspberry PI, initial set-up, configuration and some tips and tricks. Then we'll have a brief introduction to basic Python and we'll write a few simple programs that run on the RaspberryPI. The last section of the session will be dedicated to PyGame, we'll learn about surfaces, events, inputs, sprites, etc and demonstrate how to build very simple games that are as much fun for kids to write, than to play!
Odessapy2013 - Graph databases and PythonMax Klymyshyn
Page 10 "Я из Одессы я просто бухаю." translation: I'm from Odessa I just drink. Meaning his drinking a lot of "Vodka" ^_^ (@tuc @hackernews)
This is local meme - when someone asking question and you will look stupid in case you don't have answer.
How represent the digital image in Matlab
https://www.youtube.com/watch?v=-6U8le3HQlI
https://www.slideshare.net/mustafa_92/working-with-images-inmatlabgraphics-251331243
https://github.com/Mustafa-nafaa/Multimedia-TechnologyLab/tree/main/Week2:Image%20Representation
What Is Image Data?
Data Types in MATLAB
Supported Image Formats
Read image from graphics file
Information about graphics file
Write image to graphics file
Convert RGB image or colormap to grayscale
Image Histogram in MATLAB
Resize image in MATLAB
Image representation, sampling and quantization
Sampling image in MATLAB
quantization image in MATLAB
imread() – reading an image with different postfixes
imresize() – resizing an image to any given size
figure – opening a new graphical window
subplot(#of row, # of col, location) – showing different plots/images in one graphical window
imshow() – displaying an image
Imquantize- (A,levels) quantizes image
What is sampling?
What is spatial resolution?
What is quantization?
What is grey-level resolution
This is the presentation for the three-session intermediate Python programming course which I developed and successfully presented for the CoderDojo workshop held in Microsoft Silicon Valley in March 2016.
Python 101++: Let's Get Down to Business!Paige Bailey
You've started the Codecademy and Coursera courses; you've thumbed through Zed Shaw's "Learn Python the Hard Way"; and now you're itching to see what Python can help you do. This is the workshop for you!
Here's the breakdown: we're going to be taking you on a whirlwind tour of Python's capabilities. By the end of the workshop, you should be able to easily follow any of the widely available Python courses on the internet, and have a grasp on some of the more complex aspects of the language.
Please don't forget to bring your personal laptop!
Audience: This course is aimed at those who already have some basic programming experience, either in Python or in another high level programming language (such as C/C++, Fortran, Java, Ruby, Perl, or Visual Basic). If you're an absolute beginner -- new to Python, and new to programming in general -- make sure to check out the "Python 101" workshop!
Teach your kids how to program with Python and the Raspberry PiJuan Gomez
RaspberryPis are the new frontier in enabling kids (and curious adults) to get access to an affordable and easy-to-program platform to build cool things. Over a million of these nifty little devices have been sold in less than a year and part of their popularity has been due to how easy it is to start programming on them.
In this session you'll learn how to get started with the Raspberry PI, initial set-up, configuration and some tips and tricks. Then we'll have a brief introduction to basic Python and we'll write a few simple programs that run on the RaspberryPI. The last section of the session will be dedicated to PyGame, we'll learn about surfaces, events, inputs, sprites, etc and demonstrate how to build very simple games that are as much fun for kids to write, than to play!
Odessapy2013 - Graph databases and PythonMax Klymyshyn
Page 10 "Я из Одессы я просто бухаю." translation: I'm from Odessa I just drink. Meaning his drinking a lot of "Vodka" ^_^ (@tuc @hackernews)
This is local meme - when someone asking question and you will look stupid in case you don't have answer.
How represent the digital image in Matlab
https://www.youtube.com/watch?v=-6U8le3HQlI
https://www.slideshare.net/mustafa_92/working-with-images-inmatlabgraphics-251331243
https://github.com/Mustafa-nafaa/Multimedia-TechnologyLab/tree/main/Week2:Image%20Representation
What Is Image Data?
Data Types in MATLAB
Supported Image Formats
Read image from graphics file
Information about graphics file
Write image to graphics file
Convert RGB image or colormap to grayscale
Image Histogram in MATLAB
Resize image in MATLAB
Image representation, sampling and quantization
Sampling image in MATLAB
quantization image in MATLAB
imread() – reading an image with different postfixes
imresize() – resizing an image to any given size
figure – opening a new graphical window
subplot(#of row, # of col, location) – showing different plots/images in one graphical window
imshow() – displaying an image
Imquantize- (A,levels) quantizes image
What is sampling?
What is spatial resolution?
What is quantization?
What is grey-level resolution
Bitmap make our app more beautiful and there are some risk as well if we do not handle it correctly. There are many things about the bitmap that we have to know to understand how it works.
High Performance Images: Beautiful Shouldn't Mean SlowGuy Podjarny
(slides from the O'Reilly webcast, see recording here: http://www.oreilly.com/pub/e/3425)
The web is becoming increasingly image rich. Between high-resolution mobile screens, Pinterest-style design and big background graphics, the average image payload has more than doubled in the last three years. While visually appealing, these images carry a substantial performance cost, and — if not optimized correctly — can make a web experience slow and painful, no matter how beautiful it is.
These slides discuss how you can provide the eye-pleasing experience you want without sacrificing your site's performance. You'll learn about the three primary aspects of image optimization:
Image Compression: How to best encode your images, delivering the same picture with the fewest bytes.
Image Loading: Once your files are as small as they can be, we'll cover the best ways to make them show up quickly in the browser.
Image Operations: Different tools and techniques for integrating image optimization on your site.
These are the slides for a presentation I gave on creating vector scalable assets for iOS apps.
The accompanying code is at https://github.com/mindbrix/UIImage-PDF
Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014Chris Adamson
Graphics on iOS and OS X isn't just about stroking shapes and paths in Core Graphics and trying to figure out OpenGL. The Core Image framework gives you access to about 100 built-in filters, providing everything from photographic effects and color manipulation to face-finding and QR Code generation. It can leverage the power of the GPU to provide performance fast enough to perform complex effects work on real-time video capture. But even if you're not writing the next Final Cut Pro or Photoshop, it's easy to call in Core Image for simple tasks, like putting a blur in part of your UI for transitions or privacy reasons. In this session, we'll explore the many ways Core Image can make your app sizzle
could you draw uml diagram for this code from PIL import Image, Im.pdfmurtuzadahadwala3
could you draw uml diagram for this code
from PIL import Image, ImageTk # used Python Imaging Library (PIL) modules
import numpy as np # fundamental Python module for scientific computing
import os # os module is used for file and directory operations
# tkinter and its modules are used for creating a graphical user interface (gui)
import tkinter as tk
from tkinter import filedialog, messagebox
# Declaration and initialization of the global variables used in this program
# -------------------------------------------------------------------------------
# get the current directory where this program is placed
current_directory = os.path.dirname(os.path.realpath(__file__))
image_file_path = current_directory + '/thumbs_up.bmp' # default image
# Main function where this program starts execution
# -------------------------------------------------------------------------------
def start():
# create a window for the graphical user interface (gui)
gui = tk.Tk()
# set the title of the window
gui.title('Image Operations')
# set the background color of the window
gui['bg'] = 'SeaGreen1'
# create and place a frame on the window with some padding for all four sides
frame = tk.Frame(gui)
# using the grid method for layout management
frame.grid(row = 0, column = 0, padx = 15, pady = 15)
# set the background color of the frame
frame['bg'] = 'DodgerBlue4'
# read and display the default image which is a thumbs up emoji
gui_img = ImageTk.PhotoImage(file = image_file_path)
gui_img_panel = tk.Label(frame, image = gui_img)
# columnspan = 5 -> 5 columns as there are 5 buttons
gui_img_panel.grid(row = 0, column = 0, columnspan = 5, padx = 10, pady = 10)
# create and place five buttons below the image (button commands are expressed
# as lambda functions for enabling input arguments)
# ----------------------------------------------------------------------------
# the first button enables the user to open and view an image from a file
btn1 = tk.Button(frame, text = 'Open Image', width = 10)
btn1['command'] = lambda:open_image(gui_img_panel)
btn1.grid(row = 1, column = 0)
# create and place the second button that shows the image in grayscale
btn2 = tk.Button(frame, text = 'Grayscale', bg = 'gray', width = 10)
btn2.grid(row = 1, column = 1)
btn2['command'] = lambda:display_in_grayscale(gui_img_panel)
# create and place the third button that shows the red channel of the image
btn3 = tk.Button(frame, text = 'Red', bg = 'red', width = 10)
btn3.grid(row = 1, column = 2)
btn3['command'] = lambda:display_color_channel(gui_img_panel, 'red')
# create and place the third button that shows the green channel of the image
btn4 = tk.Button(frame, text = 'Green', bg = 'SpringGreen2', width = 10)
btn4.grid(row = 1, column = 3)
btn4['command'] = lambda:display_color_channel(gui_img_panel, 'green')
# create and place the third button that shows the blue channel of the image
btn5 = tk.Button(frame, text = 'Blue', bg = 'DodgerBlue2', width = 10)
btn5.grid(row = 1, column = 4)
btn5['command'.
1. Random and Dynamic Images
using Python CGI
Steven Kryskalla
September 14 2005
skryskalla@gmail.com
http://lost-theory.org
2. Overview
• Intro
• Simple Python CGI
• Random Image Script
• Python’s Graphics Libraries (PIL)
• Dynamic Image Script
• Slightly more advanced Python CGI
• A small surprise…
3. Intro
• CGI Programming with Python
• Python Graphics Libraries (PIL)
• Goals:
– Create a random image script
– Create a dynamic image script
– Learn about Python’s features as a web
scripting language
– Learn a little about Python’s graphics
capabilities
4. Simple Python CGI
• Like any other language
• Generate content from scripts
• Python’s built in CGI test server:
python -c "import CGIHTTPServer;CGIHTTPServer.test()"
• First goal: write a random image script
• First step: redirecting a static image to the
browser
– Duplicate the behavior of a normal server
5. Simple Python CGI
• Set the Content-type
• Pipe image to browser:
if __name__ == "__main__":
print "Content-type: image/pngn"
print file(r"c:pythonrandom_img1.png", "rb").read()
6. Simple Python CGI
• What if we are serving multiple file types?
• Lookup the file’s extension to get the content-
type
.png .png .jpg .jpeg .gif
ext2conttype = {"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"png": "image/png",
"gif": "image/gif"}
def content_type(filename):
return ext2conttype[filename[filename.rfind(".")+1:].lower()]
if __name__ == "__main__":
imgpath = r“c:pythonrandom_img3.jpg"
print "Content-type: %sn“ % (content_type(imgpath))
print file(imgpath, "rb").read()
7. Random Image Script
• We can serve up an image file
• We can find the content type of any image
• Pick a random image
– os.listdir()
– Filter out the non-images
– random.choice() on the remaining
images
8. Random Image Script
from os import listdir
from random import choice
ext2conttype = {"jpg": "image/jpeg",
"jpeg": "image/jpeg",
"png": "image/png",
"gif": "image/gif"}
def content_type(filename):
return ext2conttype[filename[filename.rfind(".")+1:].lower()]
def isimage(filename):
"""true if filename's extension is in content-type lookup"""
filename = filename.lower()
return filename[filename.rfind(".")+1:] in ext2conttype
def random_file(dir):
"""returns the filename of a randomly chosen image in dir"""
images = [f for f in listdir(dir) if isimage(f)]
return choice(images)
if __name__ == "__main__":
dir = "c:pythonrandom_img“
r = random_file(dir)
print "Content-type: %sn" % (content_type(r))
print file(dir+r, "rb").read()
9. Random Image Script
• Not that useful…
• Improvements, etc.
– Serve multiple directories of images
– Randomly serve other kinds of files
– Use as a starting point for a dynamic image
script
10. Python’s Graphics Libraries
• Many to choose from:
– PIL
– Agg
– Gnuplot
– ImageMagick
–…
• PIL
• Is there more interest in this?
14. PIL
• Create a dynamic image
script
• No CGI yet
• Creates a random gradient
15. PIL
import Image,ImageDraw
from random import randint as rint
def randgradient():
img = Image.new("RGB", (300,300), "#FFFFFF")
draw = ImageDraw.Draw(img)
r,g,b = rint(0,255), rint(0,255), rint(0,255)
dr = (rint(0,255) - r)/300.
dg = (rint(0,255) - g)/300.
db = (rint(0,255) - b)/300.
for i in range(300):
r,g,b = r+dr, g+dg, b+db
draw.line((i,0,i,300), fill=(int(r),int(g),int(b)))
img.save("img.png", "PNG")
if __name__ == "__main__":
randgradient()
16. Dynamic Image Script
• Now add CGI
• Don’t write to a file
• Use cStringIO for a file-like object
17. import Image,ImageDraw
+ import cStringIO
from random import randint as rint
def randgradient():
img = Image.new("RGB", (300,300), "#FFFFFF")
draw = ImageDraw.Draw(img)
r,g,b = rint(0,255), rint(0,255), rint(0,255)
dr = (rint(0,255) - r)/300.
dg = (rint(0,255) - g)/300.
db = (rint(0,255) - b)/300.
for i in range(300):
r,g,b = r+dr, g+dg, b+db
draw.line((i,0,i,300), fill=(int(r),int(g),int(b)))
+ f = cStringIO.StringIO()
+ img.save(f, "PNG")
print "Content-type: image/pngn"
+ f.seek(0)
print f.read()
if __name__ == "__main__":
randgradient()
18. Slightly More Advanced CGI
• More useful
applications of
dynamic images:
– CAPTCHAs
– Resize images for
web photo gallery
– Sparklines
– Dynamic graphs of
log files
19. Slightly More Advanced CGI
• Dynamically graph log files
• Accept arguments through the query string
(from forms, user input, etc.)
• cgi module
– cgi.FieldStorage()
20. Slightly More Advanced CGI
• Read values out of the FieldStorage
• If a value is not present we can return an
error message or use a default value
if __name__ == "__main__":
form = cgi.FieldStorage()
if "filename" in form:
if "color" in form:
graph(form["filename"].value, form["color"].value)
else:
graph(form["filename"].value, "55d")
else:
print "Content-type: text/htmln"
print """<html><body>No input file given</body></html>"""
21. Slightly More Advanced CGI
• The script is now usable with forms
• Simple form:
<html>
<head><title>Graph Log File</title></head>
<body>
<br>
<form action="/cgi-bin/dynimg3.py">
<input maxlength="100" size="55" name="filename" value="">
<select name="color">
<option value="FF3333">Red
<option value="33FF33">Green
<option value="3333FF">Blue
<option value="33AAAA">Teal
</select>
<input type="submit" value="Graph!">
</form>
</body>
</html>
22. Conclusion
• Python’s features make it a great CGI
language
– Web frameworks extend its usefulness even
more
• Solid image & graphics libraries allow for
quick writing of useful visual output