Python Pillow – Working with Alpha Channels

Python Pillow – Working with Alpha Channels ”; Previous Next An alpha channel in an image is a component that represents the level of transparency or opacity for each pixel. It is commonly used in RGBA images, where each pixel is defined by its Red, Green, Blue, and Alpha values. This channel determines how much of the background shows through an image. In simple terms we can say a pixel with an alpha value of 0 is fully transparent and while a pixel with an alpha value of 255 is fully opaque. Here are visual representations of an image with different transparency levels − The following are the breakdown of key concepts related to alpha channels in Pillow − RGBA Mode Images with an alpha channel are often represented in the RGBA mode. Each pixel in an RGBA image has four components i.e. Red, Green, Blue and Alpha. Transparency Levels The alpha channel values typically range from 0 to 255. 0 indicates complete transparency i.e. fully see-through or invisible. 255 indicate complete opacity i.e. fully opaque or not see-through. Accessing Alpha Channel We can access the alpha channel using the split() function of the Pillow Image module. This function is used to separate the individual color channels of an image. It breaks down an image into its constituent channels by allowing us to access and manipulate each channel separately. Splitting channels with split() function provides the flexibility to work with and manipulate individual color or alpha channels separately by enabling precise image adjustments and processing. When the split() function is called on an image object, it returns a tuple of individual channel images. For an RGBA image, the tuple includes the Red, Green, Blue, and Alpha channels. For grayscale or single-channel images split() function still returns four identical copies of the same channel. By accessing the alpha channel specifically, you can manipulate the transparency of an image directly. The following is the syntax and parameters of the of the split() function − r,g,b,a = image.split() Where, image − This is the image object opened using Image.open() function. r, g, b, a − These variables receive the separate bands representing Red, Green, Blue and Alpha i.e. transparency of channels respectively. Example In this example we are using the split() function to split and access the alpha channel. from PIL import Image # Open an image img_obj = Image.open(”Images/colordots.png”) #Split the image into RGBA channels red, green, blue, alpha = img_obj.split() # Alpha (transparency) channel alpha.show() Input RGBA Image to be used Output alpha channel Creating an Image with Alpha Channel To create an image with an alpha channel, we can use the new() function. This function provides options like mode, width, height and the RGBA values for customizing the image. The last argument”s last value defines the transparency i.e. alpha of the image. Example In this example we will create an image with alpha channel using the new() funtion. from PIL import Image # Create an RGBA image with Semi-transparent green image = Image.new(”RGBA”, (700, 300), (10, 91, 51, 100)) # Display the resultant image with alpha channel image.show() On executing the above program you will get output RGBA like below − Modifying Alpha Channels The individual alpha values for pixels can be set using the putpixel() function to apply modifications to the alpha channel of an image. The putpixel() function of the Python Pillow is used to change the color of a single pixel at a specified position within an image. This function allows us to directly modify the color of a specific pixel by providing its coordinates and the desired color. The below is the syntax and parameters of the putpixel() function. image.putpixel((x, y), color) image − This is the image object opened using Image.open() function. (x, y) − These are the coordinates of the pixel where we want to set the color. x represents the horizontal position and y represents the vertical position. color − The color value that we want to assign to the specified pixel. The format of the color value depends on the image mode. Example In this example we are using the putpixel() function of the pillow library for modifying the alpha values for pixels of the given input image. from PIL import Image # Open an image image = Image.open(“Images/colordots.png”) width, height = image.size # Modify alpha values of pixels for y in range(height): for x in range(width): r, g, b, a = image.getpixel((x, y)) image.putpixel((x, y), (r, g, b, int(a * 0.5))) # Reduce alpha by 50% # Display the modified image image.show() Input Image Output modified image Note The putpixel() function directly modifies the image in memory. It is useful for making small modifications to individual pixels. For large-scale pixel operations or more complex manipulations we have to consider using other Pillow functions that operate on larger regions or entire images for better performance. Composite Images with Alpha Channel The Image.alpha_composite() function is used to composite two images with alpha channels. This function blends the images based on their alpha channels. Example In this example we are using the Image.alpha_composite() function for blending two images based on their alpha channels. from PIL import Image # Open two images img1 = Image.open(”Images/tp_logo.png”) img2 = Image.open(”Images/colordots_2.png”) # Composite the images composite = Image.alpha_composite(img1, img2) # Display the result composite.show() Input Images − Output alpha composited image − Saving Images with Alpha Channel To preserve transparency,

Python Pillow – Image Sequences

Python Pillow – Image Sequences ”; Previous Next Introduction to Image Sequences Image sequences in Pillow (Python Imaging Library) refer to a collection of individual images displayed in a specific order to create an animation. The popular file formats of the image sequences are GIFs, APNG (Animated Portable Network Graphics), FLI/FLC, TIFF files(with more than one frame), and more. The Python Pillow library provides the ImageSequence module to work with image sequences and animated pictures. The main feature of this ImageSequence module is, its ability to iterate over the frames of an image sequence. We can do this by using the ImageSequence.Iterator class which acts as a wrapper for image sequences and simplifies the process of accessing individual frames. Reading Image Sequences Reading image sequences is a fundamental operation when working with animations or multi-frame images. You can open and read an image sequences using the Image.open() method in the Python Pillow (PIL) library. Example Here”s an example demonstrating how to read image sequences using the Python Pillow Image.open() method. from PIL import Image, ImageSequence # Open the image sequence file image = Image.open(“Images/Book_animation.gif”) # Display the opened image image.show() Output While executing the above code we get the following output − When an image sequence file is opened, PIL automatically loads the first frame. To access other frames in the sequence, we need to iterate through them using the ImageSequence.Iterator class, which provides a convenient way to loop through all the frames in the image sequence. Accessing Frames in an Image Sequence The ImageSequence.Iterator() class in Python Pillow allows us iterate over the frames of an image sequence. It accepts an image object as a parameter and implements an iterator object that can be used by a user to iterate over an image sequence. We can use the operator to access individual frames in the sequence or we can use the for loop to iterate over all of the frames. The syntax for using the ImageSequence.Iterator() class is as follows − image_object = PIL.ImageSequence.Iterator(image) where image_object is the iterator used to loop over the frames of the image sequence, and image is our input image object (an instance of PIL.Image.) To work with ImageSequence.Iterator in Pillow, follow these steps Import necessary modules such as Image and ImageSequence. Load the first image in the sequence using the Image.open() method. Iterate through the frames using PIL.ImageSequence.Iterator() class. Within the loop, process or manipulate each frame as needed, which can include any of the following operations such as resizing, adding text, applying filters, or other image manipulation techniques available in Pillow. Save the processed frames as separate images, using the save() method. Example Below is an example that demonstrates using ImageSequence.Iterator() class to iterate over the frames of an image sequence. from PIL import Image, ImageSequence # Open an image sequence file image = Image.open(“Images/Book_animation.gif”) index = 0 # Iterate through the frames for frame in ImageSequence.Iterator(image): # Process or manipulate the current frame here frame.convert(”RGB”).save(“output_image/frame % d.jpg” % index) index += 1 print(“All frames of the ImageSequence are saved separately.”) Output All frames of the ImageSequence are saved separately. When you execute the above code, all frames of the image sequence are saved separately in your working directory. We can also access various properties of individual frames within an image sequence. For example we can retrieve the duration of each frame which determines how long it is displayed in an animation. Creating Image Sequences While the primary use of the Image Sequence module is to extract frames from existing sequences we can also create our own image sequences. Learn more about Creating Animated GIFs here. Example Here is a basic example that demonstrating how to create a GIF image sequence from a list of image. from PIL import Image # Create a list of image objects images = [Image.open(f”Images/split{i}.jpg”) for i in range(1,4)] # Save the image sequence as a GIF images[0].save( “output_image/creating_animation.gif”, save_all=True, append_images=images[1:], duration=200, loop=0 ) print(“Image sequence created and saved as creating_animation.gif”) Output Image sequence created and saved as creating_animation.gif Modifying and Saving Image Sequences Image sequences can be manipulated and saved just like regular images. For modifying the image sequences you can use the all_frames() method from the Pillow”s ImageSequence module. This method applies a specified function to all frames in the image sequence and returns a list containg the all separated frames. By using this method, we can iterate over each frame in an image sequence and apply the necessary transformations. Following is the syntax of the ImageSequence.all_frames() method − PIL.ImageSequence.all_frames(im,func) Where, im − An image sequence. func − A function to apply to all of the image frames. After making changes to an image sequence we can save it as a new image sequence or a different format depending on our needs. Example This example demonstrates how to add text to each frame of an image sequence and save the modified sequence. from PIL import Image, ImageSequence, ImageDraw # Open the image sequence im = Image.open(”Images/book_animation.gif”) # Define a function to add text to each frame def add_text(im_frame): draw = ImageDraw.Draw(im_frame) draw.text((150, 100), “Tutorialspoint”, fill=”green”) return im_frame # Apply the add_text function to all frames in the image sequence ims = ImageSequence.all_frames(im, add_text) # Save the modified frames as a new GIF ims[0].convert(”RGB”).save(”output_image/modified_image_sequences.gif”, save_all=True, append_images=ims[1:]) print(”Text added to each frame of the given ImageSequence.”) Output Text added to each frame of the given ImageSequence. Conclusion Pillow”s Image Sequence module is a powerful tool for working with image sequences

Python Pillow – Creating Thumbnails

Python Pillow – Creating Thumbnails ”; Previous Next Thumbnails are typically used for displaying image previews or smaller representations of the original image. They are useful for optimizing web pages and improving the loading speed of image-heavy applications. Pillow provides a convenient way to generate thumbnails from images. Here are some key points about thumbnails in Pillow. Preservation of Aspect Ratio − When creating a thumbnail Pillow maintains the aspect ratio of the original image. This means that the width and height of the thumbnail are adjusted in proportion to the original image so the image does not appear distorted. Reduced File Size − Thumbnails are smaller in size compared to the original image. This reduction in size is useful for optimizing web pages or displaying images in constrained spaces such as in galleries or lists. Convenience − It simplifies the process of creating thumbnails. It resizes the image while preserving the aspect ratio and it provides an easy way to save the resized image to a file. Quality Control − We can control the quality of the thumbnail using various parameters such as the size, filter type for resizing and compression settings if we are saving the thumbnail in a compressed format like JPEG. In pillow we have the method namely thumbnail() which allows us to specify the dimensions and shape for the thumbnail image. We can create the thumbnails in two different shapes one is square and the other is circle. Creating square Thumbnails In this chapter we are going to see how to create a square thumbnail by using the thumbnail() method of the pillow library. The syntax and parameters for thumbnail() method is as follows. image.thumbnail(size, resample=Image.BOX) Where, size (required) − This parameter specifies the dimensions i.e. width and height for the thumbnail as a tuple (width, height). We can also specify just one dimension and the other dimension will be automatically calculated to maintain the aspect ratio. resample (optional) − This parameter defines the resampling filter to use when resizing the image. It can be one of the following constants − Image.NEAREST (default) − Nearest-neighbor sampling. Image.BOX − Box sampling, which is similar to the nearest-neighbor but generally gives slightly smoother results. Image.BILINEAR − Bilinear interpolation. Image.HAMMING − Hamming-windowed sinc interpolation. Image.BICUBIC − Bicubic interpolation. Image.LANCZOS − Lanczos-windowed sinc interpolation. Example In this example we are creating the square thumbnail by using the thumbnail() method by specifying the width and height parameters of the thumbnail to the resize parameter. from PIL import Image #Open the image image = Image.open(“Images/tutorialspoint.png”) #Define the thumbnail size as a tuple (width, height) thumbnail_size = (200, 200) #Create a thumbnail image.thumbnail(thumbnail_size, resample = Image.BOX ) image.save(“output Image/square_thumbnail_image.png”) image.show() Output Example Here is another example of creating a square thumbnail with width 100 and height as 100 by using the thumbnail() module. from PIL import Image #Open the image image = Image.open(“Images/butterfly.jpg”) #Define the thumbnail size as a tuple (width, height) thumbnail_size = (100, 100) #Create a thumbnail image.thumbnail(thumbnail_size, resample = Image.Resampling.BILINEAR) image.save(“output Image/square_thumbnail_image.png”) image.show() Output Creating circle Thumbnails In the above section, we have gone through what is thumbnail and how to create the square thumbnail using the pillow thumbnail() method. Now, we are going to see the circle thumbnail creation. Circle thumbnails means the thumbnail will be in the circle shape. The syntax and parameters of the thumbnail() method for creating the circle thumbnail are same as the square thumbnail. Here are the steps to be followed to create the circular thumbnail. Import the necessary modules Image and ImageDraw from the Pillow library. Use the Image.open() method to load the original image. Determine the dimensions of the original image using the size attribute. Create a new object from the mask image using the ImageDraw.Draw() method. Draw an ellipse on the mask image using the draw.ellipse() method. Centering the image to the center of the ellipse. Create a new image with the same dimensions as the original image with a transparent background using the Image.new() method. Use the save() method to save the circle thumbnail image. Use the show() method to display the created circle thumbnail image. Example In this example we are creating the circular thumbnail by using the thumbnail() method of the pillow library. #importing the required libraries from PIL import Image, ImageDraw #open image file img = Image.open(”Images/butterfly.jpg”) #resize image img.thumbnail((2000, 2000)) #create circular mask mask = Image.new(”L”, img.size, 0) draw = ImageDraw.Draw(mask) draw.ellipse((center[0] – radius, center[1] – radius, center[0] + radius, center[1] + radius), fill = 255) #apply mask to image result = Image.new(”RGBA”, img.size, (255, 255, 255, 0)) result.paste(img, (0, 0), mask) #save circular thumbnail image result.save(”OutputImages/circular_thumbnail1.png”) #showing the image using show() function result.show() Image to be used Output Print Page Previous Next Advertisements ”;

Python Pillow – Cutting and Pasting Images

Python Pillow – Cutting and Pasting Images ”; Previous Next Cutting Images Pillow (Python Imaging Library) allows us to extract a rectangular region from an image. The extracted region of the image is also known as a bounding box from an image. In The crop() method of the Image module creates a new image that represents the specified region of the original image. This method allows us to specify the coordinates of the bounding box for the region we want to crop. Here is the syntax and usage of the ”crop()” method in Pillow − Image.crop(box) Where, box − This is a tuple specifying the rectangular region we want to extract. The box parameter should be a tuple of four values: (left, upper, right, lower). left is the x-coordinate of the left edge of the bounding box. upper is the y-coordinate of the upper edge of the bounding box. right is the x-coordinate of the right edge of the bounding box. lower is the y-coordinate of the lower edge of the bounding box. Example In this example we are cropping a rectangular portion as per our requirement using the crop() method of the Image module. from PIL import Image #Open the image image = Image.open(“Images/book.jpg”) #Define the bounding box for cropping box = (100, 100, 200, 200) #(left, upper, right, lower) #Crop the image using the defined bounding box cropped_image = image.crop(box) #Save or display the cropped image cropped_image.save(“output Image/cropped_image.jpg”) cropped_image.show() Image to be cropped Output Example Here this is another example for cropping a rectangular part of the image by using the crop() method. from PIL import Image #Open the image image = Image.open(“Images/rose.jpg”) #Define the bounding box for cropping box = (10, 10, 200, 200) #(left, upper, right, lower) #Crop the image using the defined bounding box cropped_image = image.crop(box) #Save or display the cropped image cropped_image.save(“output Image/cropped_image.jpg”) cropped_image.show() Input Image Output Pasting Images Pasting images using Python Pillow allows us to extract a region of interest from one image and paste it onto another. This process is useful for tasks like image cropping, object extraction and compositing. The paste() method in Pillow (Python Imaging Library) allows us to paste one image onto another at a specified position. It”s a commonly used method for compositing images, adding watermarks or overlaying one image on top of another. The below is the syntax and parameters of the paste() function − PIL.Image.paste(im, box, mask=None) im − This is the source image i.e., the image we want to paste onto the current image. box − This parameter specifies the position where we want to paste the source image. It can be a tuple of coordinates ”(left, upper, right, lower)”. The source image will be pasted inside the bounding box defined by these coordinates. mask (optional) − If this parameter provided then it can be an image that defines a transparency mask. The pasted image will be masked according to the transparency values in the mask image. Example Here is an example of how to use the paste() method to paste one image onto another. from PIL import Image #Open the background image background = Image.open(“Images/bw.png”) #Open the image to be pasted image_to_paste = Image.open(“Images/tutorialspoint.png”) #Define the position where the image should be pasted position = (100, 100) #Paste the image onto the background background.paste(image_to_paste, position) #Save the modified image background.save(“OutputImages/paste1.jpg”) background.show() Image to be used Output Print Page Previous Next Advertisements ”;

Python Pillow – Concatenating two Images

Python Pillow – Concatenating two Images ”; Previous Next Concatenating two images with Pillow typically refers to combining or joining two separate images to create a single image either horizontally or vertically. This process allows us to merge the content of the two images into a larger image. Pillow is a Python Imaging Library (PIL) which provides various methods and functions to perform image manipulation including image concatenation. When concatenating images we can choose to stack them on top of each other vertical concatenation or place them side by side horizontal concatenation. There are no direct methods in pillow to concatenate the images but we can perform that by using the paste() method in python. Here is a step-by-step guide on how to perform concatenation of two Images. Import the necessary modules. Load the two images that we want to concatenate. Decide whether we want to concatenate the images horizontally or vertically. Save the concatenated image to a file. Optionally we can display the concatenated image. This step is useful for visualizing the result but it”s not required. Following is the input images used in all the examples of this chapter. Example In this example we are concatenating two input images horizontally. from PIL import Image image1 = Image.open(“Images/butterfly.jpg”) image2 = Image.open(“Images/flowers.jpg”) result = Image.new(“RGB”, (image1.width + image2.width, image1.height)) result.paste(image1, (0, 0)) result.paste(image2, (image1.width, 0)) result.save(“output Image/horizontal_concatenated_image.png”) result.show() Output Example Here in this example we are concatenating the given two input images vertically. from PIL import Image image1 = Image.open(“Images/butterfly.jpg”) image2 = Image.open(“Images/flowers.jpg”) result = Image.new(“RGB”, (image1.width, image1.height + image2.height)) result.paste(image1, (0, 0)) result.paste(image2, (0, image1.height)) result.save(“output Image/vertical_concatenated_image.png”) result.show() Output Print Page Previous Next Advertisements ”;

Python Pillow – Writing text on image

Python Pillow – Writing text on image ”; Previous Next Adding text to images is a common image processing task that involves overlaying text onto an image. This can be done for various purposes such as adding captions, labels, watermarks or annotations to images. When adding text to images we can typically specify the text content, font, size, color and position. In Pillow (PIL) We can use the text() method from the ImageDraw module to add text to an image. The text() method The text() method allows us to specify the position, text content, font and color of the text we want to add. Syntax The below is the basic syntax and parameters for using the text() method − PIL.ImageDraw.Draw.text(xy, text, fill=None, font=None, anchor=None, spacing=0, align=”left”) xy − The position where the text should be placed. It should be a tuple ”(x, y)” representing the coordinates. text − The text content that we want to add to the image. fill (optional) − The color of the text. It can be specified as a tuple ”(R, G, B)” for RGB colors a single integer for grayscale colors or as a named color. font (optional) − The font to use for the text. We can specify the font using ”ImageFont.truetype()” or ”ImageFont.load()”. anchor (optional) − Specifies how the text should be anchored. Options include “left”, “center”, “right”, “top”, “middle” and “bottom”. spacing (optional) − Specifies the spacing between lines of text. Use positive values to increase spacing or negative values to reduce spacing. align (optional) − Specifies the horizontal alignment of the text within the bounding box. Options include “left”, “center” and “right”. Following is the input image used in all the examples of this chapter. Example In this example we are adding the text Tutorialspointto the input image using the text() method of the Image module. from PIL import Image, ImageDraw, ImageFont #Open an image image = Image.open(“Images/book.jpg”) #Create a drawing object draw = ImageDraw.Draw(image) #Define text attributes text = “Tutorialspoint” font = ImageFont.truetype(“arial.ttf”, size=30) text_color = (255, 0, 0) #Red position = (50, 50) #Add text to the image draw.text(position, text, fill=text_color, font=font) #Save or display the image with the added text image.save(“output Image/textoutput.jpg”) opentext = Image.open(“output Image/textoutput.jpg”) opentext.show() Output Example Here this is another example of adding text to the image by using the text() method of the ImageDraw module. from PIL import Image, ImageDraw, ImageFont #Open an image image = Image.open(“Images/book.jpg”) #Create a drawing object draw = ImageDraw.Draw(image) #Define text attributes text = “Have a Happy learning” font = ImageFont.truetype(“arial.ttf”, size=10) text_color = (255, 0, 255) position = (150, 100) #Add text to the image draw.text(position, text, fill=text_color, font=font) #Save or display the image with the added text image.save(“output Image/textoutput.jpg”) opentext = Image.open(“output Image/textoutput.jpg”) opentext.show() Output Print Page Previous Next Advertisements ”;

Python Pillow – ImageDraw Module

Python Pillow – ImageDraw Module ”; Previous Next Drawing on images in Pillow involves using the Pillow library (Python Imaging Library) to add various visual elements such as lines, shapes, text and more to an existing image. This is a common image processing task used for tasks like image annotation, creating visualizations, adding labels or captions highlighting areas of interest and more. We can use the ImageDraw module in Pillow to create a drawing object and then use various methods of this object to draw on the image. We can use the line(), rectangle(), ellipse(), text() and other methods to draw various elements on the image. Drawing Text on the Image To draw or write text on an image we can use the ImageDraw.Draw() function in the Pillow library, this method creates a drawing object that allows us to perform drawing operations on images. Syntax The following is the syntax and parameters of the Draw() method − PIL.ImageDraw.Draw(image, mode=None) Where, image − This parameter represents the image on which we want to perform drawing operations. It”s an instance of a Pillow Image object. mode (optional) − This parameter specifies the mode in which drawing will occur. The available modes are − 1 − 1-bit pixels (monochrome) L − 8-bit pixels, black and white RGB − 3×8-bit pixels, true color RGBA − 4×8-bit pixels with transparency CMYK − 4×8-bit pixels in the CMYK color space HSV − 3×8-bit pixels in the HSV color space Input image to be used for the below two examples. Example In this example we are using the Draw() method of the ImageDraw module to add text on the image. from PIL import Image, ImageDraw, ImageFont #Open an image image = Image.open(“Images/faces.jpg”) #Create a drawing object draw = ImageDraw.Draw(image) #Define text attributes text = “Welcome to Tutorialspoint” font = ImageFont.truetype(“arial.ttf”, size=30) text_color = (0, 0, 255) #Blue text_position = (50, 50) #Add text to the image draw.text(text_position, text, fill=text_color, font=font) #Save or display the image with the added drawing elements image.save(“output Image/drawnimage.jpg”) #Open the output drawn image opendraw = Image.open(“output Image/drawnimage.jpg”) opendraw.show() Output Example Here this is another example using the Draw() method for adding text at the middle of the image. from PIL import Image, ImageDraw, ImageFont #Open an image image = Image.open(“Images/faces.jpg”) #Create a drawing object draw = ImageDraw.Draw(image) #Define text attributes text = “Welcome to Tutorialspoint” font = ImageFont.truetype(“arial.ttf”, size=30) text_color = (255, 0, 0) #Add text to the image draw.text(xy=(25, 160), text = text, font = font, fill= text_color) #Save or display the image with the added drawing elements image.save(“output Image/drawnimage.jpg”) #Open the output drawn image opendraw = Image.open(“output Image/drawnimage.jpg”) opendraw.show() Output Drawing Rectangle on the Image In the Pillow library (PIL) the PIL.ImageDraw.Draw.rectangle() method is used to draw a rectangle on an image using a specified outline and fill color. This method is part of the ImageDraw module and is typically called on an ImageDraw object created using PIL.ImageDraw.Draw(). Syntax The following is the syntax and parameters of the PIL.ImageDraw.Draw.rectangle() method − ImageDraw.Draw.rectangle(xy, outline=None, fill=None, width=0) Where, xy − This parameter specifies the coordinates of the rectangle as a tuple of two points. Each point is represented as (x1, y1) and (x2, y2) in which (x1, y1) is the upper-left corner and (x2, y2) is the lower-right corner of the rectangle. outline − This parameter is optional and specifies the color of the outline of the rectangle. We can provide a color as a string e.g., “red” or “#FF0000” or as a tuple representing an RGB color (e.g., (255, 0, 0)). If set to None no outline will be drawn. fill − This parameter is optional and specifies the color to fill the rectangle. Like the outline parameter we can specify the fill color as a string or an RGB tuple. If set to None the rectangle will not be filled. width − This is an optional parameter to specify the width of the outline of the rectangle. By default it is 0 which means the rectangle will be filled without an outline. Input image to be used for the below two examples. Example In this example we are drawing a rectangle on the given input image by using the PIL.ImageDraw.Draw.rectangle() method. from PIL import Image, ImageDraw #Open an image image = Image.open(“Images/bw.png”) #Create a drawing object draw = ImageDraw.Draw(image) #Define the coordinates for the rectangle xy = [(100, 100), (200, 200)] #Draw a filled red rectangle draw.rectangle(xy, outline=”blue”, fill=”red”, width = 3) #Save or display the modified image image.save(“output Image/output.jpg”) image.show() Output Example Here this is another example of drawing the rectangle with the specifying the outline as Blue and fill parameter as None. from PIL import Image, ImageDraw #Open an image image = Image.open(“Images/bw.png”) #Create a drawing object draw = ImageDraw.Draw(image) #Define the coordinates for the rectangle xy = [(100, 100), (200, 200)] #Draw a filled red rectangle draw.rectangle(xy, outline= “Blue”, fill= None, width = 2) #Save or display the modified image image.save(“output Image/output.jpg”) image.show() Output Drawing Line on the Image PIL.ImageDraw.Draw.line() is a method provided by the Python Imaging Library (PIL) or the Pillow library. Pillow is a more modern and actively maintained fork of PIL that is used to draw a line on an image. This method is part of the ImageDraw module within PIL/Pillow which is used for drawing shapes, text, and other graphics on images. Syntax Here the below is the syntax of the PIL.ImageDraw.Draw.line() method −

Python Pillow – Creating a Watermark

Python Pillow – Creating a Watermark ”; Previous Next What is Watermark? A watermark is a recognizable and often transparent image or text that is superimposed onto another image, document or object to indicate ownership, authorship or origin. Watermarks are typically used to protect intellectual property and content which prevent unauthorized use or distribution and provide attribution. They serve various purposes as mentioned below − Copyright Protection − Artists, photographers and content creators often use watermarks to protect their intellectual property by marking their work with their name, logo or copyright information. This helps deter unauthorized use or distribution of their content. Branding − Companies and organizations use watermarks to brand their images or documents with their logos, names or slogans. This reinforces their brand identity and makes it clear where the content originated. Document Verification − Watermarks can be used on official documents such as certificates to prevent forgery or unauthorized reproduction. For example diplomas or notarized documents may have watermarks. Security − In currency and other security documents intricate and often invisible watermarks are used to deter counterfeiting. These watermarks are difficult to reproduce accurately making it easier to detect counterfeit bills or documents. Image Attribution − In the context of stock photography and image licensing watermarks can be used to display a preview of the image with a watermark. When a user purchases the image they receive a version without the watermark. Digital Media − In the digital world watermarks are often used on images and videos shared online to protect content. They can also be used to give credit to the original creator. Watermarks can take various forms such as text, logos, patterns or even invisible data embedded within the content. They are typically placed in a manner that is difficult to remove without compromising the quality of the content and their purpose is to provide a visual or digital indicator of authenticity or ownership. Creating the text watermark Now let”s explore how to create a text watermark by using the pillow library. In pillow there is no direct method to create the watermarks but we can achieve it by using the ImageDraw, ImageFont and Image methods. Following is the input image used in all the examples of this chapter. Example In this example we are creating the text Tutorialspoint as the watermark by using the pillow library. from PIL import Image, ImageDraw, ImageFont original_image = Image.open(“Images/butterfly.jpg”) draw = ImageDraw.Draw(original_image) watermark_text = “Tutorialspoint” font_size = 20 font = ImageFont.truetype(“arial.ttf”, font_size) text_color = (255, 255, 255) #White color (RGB) text_width, text_height = draw.textsize(watermark_text, font) image_width, image_height = original_image.size margin = 10 #Margin from the right and bottom edges position = (image_width – text_width – margin, image_height – text_height – margin) draw.text(position, watermark_text, font=font, fill=text_color) original_image.save(“output Image/watermarked_image.png”) original_image.show() Output Creating the image Watermark Previously we created the text watermark on an image, in the same way we can create an image as the watermark by using the ImageDraw, copy and paste methods available in pillow. Example In this example we are creating the Tutoriaslpoint logo image as the watermark by the methods available in pillow. from PIL import Image original_image = Image.open(“Images/butterfly.jpg”) watermark = Image.open(“Images/tutorialspoint.png”) #Use the appropriate image file for your watermark #Resize the watermark image to a specific width or height target_width = 200 #Adjust this to our preferred size aspect_ratio = float(target_width) / watermark.width target_height = int(watermark.height * aspect_ratio) watermark = watermark.resize((target_width, target_height), Image.ANTIALIAS) watermarked_image = original_image.copy() #Adjust the position where you want to place the watermark (e.g., bottom right corner) position = (original_image.width – watermark.width, original_image.height – watermark.height) watermarked_image.paste(watermark, position, watermark) watermarked_image.save(“output Image/watermarked_image.jpg”) watermarked_image.show() Output Print Page Previous Next Advertisements ”;

Python Pillow – Rolling an Image

Python Pillow – Rolling an Image ”; Previous Next Pillow (Python Imaging Library) allows us to roll or shift the image”s pixel data within the image. This operation moves the pixel data either horizontally (left or right) or vertically (up or down) to create a rolling effect. There is no direct method in pillow to roll or shift the image pixel data but it can be performed by using the copy and paste operations on the image. The below are the steps to be followed to perform rolling of the image. Import the necessary modules. Next load the image that we want to roll. Define the rolling offset − The rolling offset determines how much we want to shift the image. A positive value for the offset will shift the image right i.e. horizontal rolling or down i.e. vertical rolling and a negative value will shift the image left or up. We can choose the offset value based on our desired rolling effect. Create a new image with the same size as the original. This new image will serve as the canvas for the rolled result. Perform the rolling operations i.e. either horizontal rolling or vertical rolling. Save the rolled image to a file. Optionally display the rolled image. This step is useful for visualizing the result but it”s not necessary. Following is the input image used in all the examples of this chapter. Example In this example we are performing the horizontal rolling on the input image by specifying the horizontal offset as 50. from PIL import Image image = Image.open(“Images/flowers.jpg”) horizontal_offset = 50 #Change this value as needed rolled_image = Image.new(“RGB”, image.size) for y in range(image.height): for x in range(image.width): new_x = (x + horizontal_offset) % image.width pixel = image.getpixel((x, y)) rolled_image.putpixel((new_x, y), pixel) rolled_image.save(“output Image/horizontal_rolled_image.png”) rolled_image.show() Output Example In this example we are rolling the image vertically by specifying the offset value as 50. from PIL import Image image = Image.open(“Images/flowers.jpg”) vertical_offset = 50 #Change this value as needed rolled_image = Image.new(“RGB”, image.size) for x in range(image.width): for y in range(image.height): new_y = (y + vertical_offset) % image.height pixel = image.getpixel((x, y)) rolled_image.putpixel((x, new_y), pixel) rolled_image.save(“output Image/vertical_rolled_image.png”) rolled_image.show() Output Print Page Previous Next Advertisements ”;

Python Pillow – Identifying Image Files

Python Pillow – Identifying Image Files ”; Previous Next Identifying image files using the Python Pillow (PIL) library involves checking file extensions to determine if a file is likely an image or not. While Pillow itself doesn”t have a built-in method to identify image files and we can use functions of os module such as listdir(), path.splitext(), path.is_image_file(), path.join() to filter files based on their extensions as per our user requirements. Python”s os.path module does not provide a direct is_image_file() function for identifying image files. Instead we can typically use the Pillow library (PIL) to check if a file is an image. However we can create a custom is_image_file() function using os.path in combination with Pillow to check if a file appears to be an image based on its extension. Here”s an example of how we can use os.path to check file extensions and determine if a file is likely an image file − We define the is_image_file() function which first checks if the file”s extension appears to be a common image format (defined in ”image_extensions”). If the file extension is not recognized, it”s assumed not to be an image file. For recognized image file extensions the function attempts to open the file as an image using Pillow”s Image.open(). If this operation succeeds without errors then the function returns True indicating that the file is a valid image. If there is an issue opening the file the function returns False. This approach combines os.path for extracting file extensions and Pillow for checking whether the file is a valid image. Example import os from PIL import Image def is_image_file(file_path): image_extensions = {“.jpg”, “.jpeg”, “.png”, “.gif”, “.bmp”, “.tiff”, “.ico”} #Add more extensions as needed _, file_extension = os.path.splitext(file_path) #Check if the file extension is in the set of image extensions return file_extension.lower() in image_extensions file_path = “Images/butterfly.jpg” if is_image_file(file_path): print(“This is an image file.”) Image.open(file_path) else: print(“This is not an image file.”) Output This is an image file. Example In this example we are passing the file extension as pdf, as it is not a image file extension the result will be not a image file. import os from PIL import Image def is_image_file(file_path): image_extensions = {“.jpg”, “.jpeg”, “.png”, “.gif”, “.bmp”, “.tiff”, “.ico”} #Add more extensions as needed _, file_extension = os.path.splitext(file_path) #Check if the file extension is in the set of image extensions return file_extension.lower() in image_extensions file_path = “Images/butterfly.pdf” if is_image_file(file_path): print(“This is an image file.”) Image.open(file_path) else: print(“This is not an image file.”) Output This is not an image file. Print Page Previous Next Advertisements ”;