## How to Handle Broken Images

If your website is displaying many images and some of their are from different sources, eventually you will run into a situation when some of the images no longer exists. They are either move to different path or got deleted altogether.

This is what you will start seeing something like below in your website.

This is very annoying to users and it needs to be fixed on topmost priority.

Here are some of the ways to fix broken images.

### Remove img tag itself.

This is the simplest and most effective way of doing it.

<img src="Error.src" onerror="this.style.display='none'"/>

Another way of doing same thing

<img src="Error.src" onerror="this.parentNode.removeChild(this);">

This will remove img tag itself and user will never know if any image was to be displayed here, Only issue being, if you have referred image in your content, user might get confused.

### Display Backup Image

Implementing this is also very easy but for various reasons I dont link this option.

<img src="Error.src" onerror="this.src='http://example.com/existent-image.jpg'"/>

This option remove awkwardness looking broken image picture, however it will be replace it will backup image. Humanly it’s not possible to set up back up image for each image so mostly, there will be one backup image for all images. This reduces the awkwardness of broken image but it replaces it with backup image. This highlights the broken image issue and if image is referred in content, it does not help user with anything.

## How to Create Custom Query for WordPress

WordPress has a default query which fetches posts and display it in descending manner. If you are working on any WordPress customisation, you would come across a requirement to fetch WordPress posts in customised manner such as Fetching last 10 posts, Fetching post having specific category or tag.

Fortunately, we dont have to write MySQL level queries to get required data (and that what makes WordPress special), we can call a WP_Query function by passing required fields as input, we can get required data. This logic has two parts.

1. Query : The query will select WordPress posts from the MySQL database based on our instructions.
2. Loop : It will output the post information on the page. Each instance of output array will have attributes such as post thumbnail, title, date, and author etc.

// The Query
$the_query = new WP_Query($args );

// The Loop
if ( $the_query->have_posts() ) { echo '<ul>'; while ($the_query->have_posts() ) {
$the_query->the_post(); echo '<li>' . get_the_title() . '</li>'; } echo '</ul>'; /* Restore original Post Data */ wp_reset_postdata(); } else { // no posts found }  You can customized the query as per your requirement. <?php // Creating array$args = array(
'posts_per_page' => 15,
'orderby' => 'date',
'order' ='ASC'
);
// Initiate the custom query
$custom_query = new WP_Query($args );

?>

By Default, it will search for posts, if you want to search for specific custom post type, you can simply add a parameter in array

<?php

// Creating array
$args = array( 'post_type' => 'vehicle', 'posts_per_page' => 15, 'orderby' => 'date', 'order' ='ASC' ); // Initiate the custom query$custom_query = new WP_Query( $args ); ?> ## How to Check if a File Exists using Python Recently I was working on file generation using python, before generating any file, I had to check if file exists or not, to check if file exists or not, I had to find a way to do in in program. As usual, this task is very easy using python. Checking if file exists or not can be done in multiple ways using python, here is one using “os” module os.path module has functions such as isfile, isdir and exists which helps us check if file or directory exists or not.  ################################################################################################ # name: file_exists_01.py # desc: Check if file exists # date: 2019-02-13 # Author: conquistadorjd ################################################################################################ import os input_file_path = '/home/conquistador/code/github/python-01-utilities/file/' input_file_name = 'file_exists_01.py' file_exists = os.path.isfile(input_file_path+input_file_name) print('file_exists :', file_exists) input_file_name = 'file_exists_99.py' file_exists = os.path.isfile(input_file_path+input_file_name) print('file_exists :', file_exists) input_file_name = 'file_exists_01.py' dir_exists = os.path.isdir(input_file_path+input_file_name) print('dir_exists :', dir_exists) dir_exists = os.path.isdir(input_file_path) print('dir_exists :', dir_exists) input_file_path = '/home/conquistador/code/github/python-01-utilities/fil e/' dir_exists = os.path.isdir(input_file_path) print('dir_exists :', dir_exists) input_file_path = '/home/conquistador/code/github/python-01-utilities/file/' exists = os.path.exists(input_file_path) print('exists :', exists) exists = os.path.exists(input_file_path+input_file_name) print('exists :', exists) view raw file_exists_01.py hosted with ❤ by GitHub Here is the output $ python3.6 file_exists_01.py
file_exists : True
file_exists : False
dir_exists : False
dir_exists : True
dir_exists : False
exists : True
exists : True

If you use isfile() on directory, outcome will be False, you need to use isfile or isdir as per requirement. Alternatively, you can use exists function as well, this returns True if input file or directory path is valid. Please refer to os.path documentation for further details.

Here is another way to check if file exists or not using pathlib module.

 ################################################################################################ # name: file_exists_02.py # desc: Check if file exists # date: 2019-02-13 # Author: conquistadorjd ################################################################################################ from pathlib import Path input_file_path = '/home/conquistador/code/github/python-01-utilities/file/' input_file_name = 'file_exists_01.py' var = Path(input_file_path) print('var : ', var.is_file()) var = Path(input_file_path+input_file_name) print('var : ', var.is_file()) var = Path(input_file_path) print('var : ', var.is_dir()) var = Path(input_file_path+input_file_name) print('var : ', var.is_dir()) var = Path(input_file_path) print('var : ', var.exists()) var = Path(input_file_path+input_file_name) print('var : ', var.exists())

view raw
file_exists_02.py
hosted with ❤ by GitHub

Output is

$python3.6 file_exists_02.py var : False var : True var : True var : False var : True var : True Both the modules have similar features, you can choose whichever is convenient to you. ## How to crop image using Python Image cropping is very easy using python library Pillow. Following is simple program to crop image in required parts. Most important part of cropping is to know pixel size of your image, you can crop required portion using .crop method of Image module of Pillow. Sample program  ################################################################################################ # name: 06_crop_image_01.py # desc: # date: 2019-02-10 # Author: conquistadorjd ################################################################################################ from PIL import Image, ImageDraw print('*** Program Started ***') # image_font_path = 'imagepath_input = '/home/conquistador/code/github/python-01-utilities/image/fonts/' image_path_input = '/home/conquistador/code/github/python-01-utilities/image/input/' image_path_output = '/home/conquistador/code/github/python-01-utilities/image/output/' image_name_input = '06_crop_image_01_input.jpg' ###################################################### im = Image.open(image_path_input + image_name_input) im_width, im_height = im.size print('im.size', im.size) ###################################################### Left half of the image im = im.crop((0, 0, im_width/2,im_height)) # (left, upper, right, lower)-tuple. image_name_output = '06_crop_image_01_output_01.jpg' im.save(image_path_output + image_name_output) print('im.size', im.size) ###################################################### right half of the image im = Image.open(image_path_input + image_name_input) im = im.crop((im_width/2, 0, im_width, im_height)) image_name_output = '06_crop_image_01_output_02.jpg' im.save(image_path_output + image_name_output) print('im.size', im.size) ###################################################### right top half of the image im = Image.open(image_path_input + image_name_input) im = im.crop((im_width/2, 0, im_width, im_height/2)) image_name_output = '06_crop_image_01_output_03.jpg' im.save(image_path_output + image_name_output) print('im.size', im.size) print('*** Program Ended ***') view raw 06_crop_image_01.py hosted with ❤ by GitHub Please note that crop takes tuple having four values as input. These four values represent left, upper, right, lower point . Original image Left Half of the image Right Half of the image Top Right corner of the image Here is the output of the program, please note the pixel size of each cropped image. $ python3.6 06_crop_image_01.py
*** Program Started ***
im.size (1920, 1318)
im.size (960, 1318)
im.size (960, 1318)
im.size (960, 659)
*** Program Ended ***

## How to compress images using Python

Python Library Pillow can be used very effectively to compress images. While doing some research on this I found that .JPG files can be compress very effectively however this does not work well with .PNG files. Here is sample program to reduce file size of an image.

 ################################################################################################ # name: 05_compress_image_01.py # desc: Compress image file using python # date: 2019-02-10 # Author: conquistadorjd ################################################################################################ from PIL import Image, ImageDraw, ImageFont import os print('*** Program Started ***') image_font_path = '/home/conquistador/code/github/python-01-utilities/image/fonts/' image_path_input = '/home/conquistador/code/github/python-01-utilities/image/input/' image_path_output = '/home/conquistador/code/github/python-01-utilities/image/output/' # image_name_input = '05_compress_image_01_input.png' image_name_input = '05_compress_image_01_input.jpg' im = Image.open(image_path_input + image_name_input) print('Input file size : ', im.size ) print('Input file name : ', image_name_input ) print('Input Image Size : ', os.path.getsize (image_path_input + image_name_input)) # image_name_output = '05_compress_image_01_output.png' image_name_output = '05_compress_image_01_output.jpg' im.save(image_path_output + image_name_output ,optimize=True,quality=50) print('Output file size : ', im.size ) print('Output file name : ', image_name_output) print('Output Image Size : ', os.path.getsize (image_path_output + image_name_output)) print('*** Program Ended ***')

Output of the program while using .JPG file as input and output

$python3.6 05_compress_image_01.py *** Program Started *** Input file size : (5456, 3632) Input file name : 05_compress_image_01_input.jpg Input Image Size : 1611664 Output file size : (5456, 3632) Output file name : 05_compress_image_01_output.jpg Output Image Size : 443479 *** Program Ended *** Output of the program while using .PNG files as input and output $ python3.6 05_compress_image_01.py
*** Program Started ***
Input file size : (1920, 1282)
Input file name : 05_compress_image_01_input.png
Input Image Size : 3683320
Output file size : (1920, 1282)
Output file name : 05_compress_image_01_output.png
Output Image Size : 3619363
*** Program Ended ***



As you can see, while using .PNG files for input and output, there is hardly any change in file size however when you used .JPG files, output files is of 27% of original file size. Your percentage reduction might be different based on the file that you have used.

Please note input and out file dimensions, number of pixels stays the same.

## How to resize image using Python

Python library Pillow can be used to resize images. Please note resize does not mean compressing image. Yes, reducing pixels can lead to reduction in file size in terms of KBs however it will not be significant. If you need to compress image, please check How to compress image using python.

While resizing the image file, you need to maintain the aspect ration, else image might get distorted, we will see an example of the same.

Here is sample program to resize.

 ################################################################################################ # name: 04_resize_image_01.py # desc: reducing the file size and keeping same aspect ratio # date: 2019-02-10 # Author: conquistadorjd ################################################################################################ from PIL import Image, ImageDraw print('*** Program Started ***') # image_font_path = 'imagepath_input = '/home/conquistador/code/github/python-01-utilities/image/fonts/' image_path_input = '/home/conquistador/code/github/python-01-utilities/image/input/' image_path_output = '/home/conquistador/code/github/python-01-utilities/image/output/' image_name_input = '04_resize_image_01_input.jpg' ###################################################### im = Image.open(image_path_input + image_name_input) im_width, im_height = im.size print('im.size', im.size) im = im.resize((int(im_width/2), int(im_height/2)), Image.ANTIALIAS) # im = im.resize((im_width,im_height), Image.LANCZOS) print('im.size', im.size) image_name_output = '04_resize_image_01_output.jpg' im.save(image_path_output + image_name_output) print('*** Program Ended ***')

here is the output

$python3.6 04_resize_image_01.py *** Program Started *** im.size (1920, 1318) im.size (960, 659) *** Program Ended *** Here we have maintained the aspect ratio so the files will look similar Input Output Now lets look at resize by not maintaining the aspect ratio  ################################################################################################ # name: 04_resize_image_02.py # desc: reducing the file size but changing the aspect ratio # date: 2019-02-10 # Author: conquistadorjd ################################################################################################ from PIL import Image, ImageDraw print('*** Program Started ***') # image_font_path = 'imagepath_input = '/home/conquistador/code/github/python-01-utilities/image/fonts/' image_path_input = '/home/conquistador/code/github/python-01-utilities/image/input/' image_path_output = '/home/conquistador/code/github/python-01-utilities/image/output/' image_name_input = '04_resize_image_01_input.jpg' ###################################################### im = Image.open(image_path_input + image_name_input) im_width, im_height = im.size print('im.size', im.size) im = im.resize(( 500,480 ), Image.ANTIALIAS) # im = im.resize((im_width,im_height), Image.LANCZOS) print('im.size', im.size) image_name_output = '04_resize_image_02_output.jpg' im.save(image_path_output + image_name_output) print('*** Program Ended ***') Output of the program $ python3.6 04_resize_image_02.py
*** Program Started ***
im.size (1920, 1318)
im.size (500, 480)
*** Program Ended ***

You can see the issue with changing of aspect ratio.

Input

Output

Size comparison

## How to add text on image using Python

As a part of image processing, we sometimes need to write text on the image file. Pillow is a python library which can be used to add text on images using python. Using Pillow, which us a fork of PIL, is very easy for these kind of image processing activities.

Let us have a look at adding simple text on image file.

 ################################################################################################ # name: 03_add_text_to_image_01.py # desc: # date: 2019-02-10 # Author: conquistadorjd ################################################################################################ from PIL import Image, ImageDraw, ImageFont print('*** Program Started ***') image_font_path = '/home/conquistador/code/github/python-01-utilities/image/fonts/' image_path_input = '/home/conquistador/code/github/python-01-utilities/image/input/' image_path_output = '/home/conquistador/code/github/python-01-utilities/image/output/' image_name_input = '03_add_text_to_image_01_input.jpg' ######################################################################## Writing simple text on file im = Image.open(image_path_input + image_name_input) position = (50, 50) message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit" # initialise the drawing context with the image object as background draw = ImageDraw.Draw(im) draw.text(position, message) im.show() image_name_output = '03_add_text_to_image_01_input_01.jpg' im.save(image_path_output + image_name_output) print('*** Program Ended ***')

Please note that text location is determined by parameter position, its tuple with two parameters and it represents x and y axis position. In below example I have used position = (50, 50).

Now if you are wondering what these values represent, these are pixel numbers with (0,0) being top left corner.  If you image size is (640, 480) and you want to put any character exactly at center, you need to provide position as (320,240). Hope this clarifies the parameter

Here is the output

As you can see the text added does not look good sine we have not added any formatting to text.  Now let us look at formatted text  on image. Here is program with additional parameters for font

 ################################################################################################ # name: 03_add_text_to_image_02.py # desc: # date: 2019-02-10 # Author: conquistadorjd ################################################################################################ from PIL import Image, ImageDraw, ImageFont print('*** Program Started ***') image_font_path = '/home/conquistador/code/github/python-01-utilities/image/fonts/' image_path_input = '/home/conquistador/code/github/python-01-utilities/image/input/' image_path_output = '/home/conquistador/code/github/python-01-utilities/image/output/' image_name_input = '03_add_text_to_image_01_input.jpg' im = Image.open(image_path_input + image_name_input) position = (50, 50) message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit" font = ImageFont.truetype(image_font_path + 'Unkempt-Regular.ttf', size=24) color = (238, 242, 4) # initialise the drawing context with the image object as background draw = ImageDraw.Draw(im) draw.text(position, message, fill=color, font=font) im.show() image_name_output = '03_add_text_to_image_02_input_01.jpg' im.save(image_path_output + image_name_output) print('*** Program Ended ***')

Here we have added two additional parameters, font and color, you can plan your desired font into font directory and can use it for adding text to image file.

Note: I tried using this for non english text e.g. devnagari text but it did not work.

Here is the output.

## How to create blank image using Pillow, Python

Sometimes we need a blank image file to be created during execution of program, during processing required text or anything else can be added. Following is the sample program to create blank file using PIL, python.

You can decide file size and color as per your requirement.

 ################################################################################################ # name: 02_create_blank_image.py # desc: Creates blank image files # date: 2019-02-10 # Author: conquistadorjd ################################################################################################ from PIL import Image, ImageDraw print('*** Program Started ***') # image_font_path = 'imagepath_input = '/home/conquistador/code/github/python-01-utilities/image/fonts/' # image_path_input = '/home/conquistador/code/github/python-01-utilities/image/input/' image_path_output = '/home/conquistador/code/github/python-01-utilities/image/output/' # image_name_input = '02_create_blank_image_01.jpg' image_name_output = '02_create_blank_image_01.jpg' mode = 'RGB' # for color image “L” (luminance) for greyscale images, “RGB” for true color images, and “CMYK” for pre-press images. size = (640, 480) color = (73, 109, 137) im = Image.new(mode, size, color) im.save(image_path_output + image_name_output ) im.show() print('*** Program Ended ***')

Here is the output image

## How to read image using Pillow, Python and get image attributes

Pillow is the friendly PIL fork. PIL is the Python Imaging Library. This is the first article in series of image processing articles using python.

Here is simplest program to read image file using pillow and get basic attributes

 ################################################################################################ # name: 01_read_image.py # desc: # date: 2019-02-10 # Author: conquistadorjd ################################################################################################ from PIL import Image print('*** Program Started ***') # image_font_path = 'imagepath_input = '/home/conquistador/code/github/python-01-utilities/image/fonts/' image_path_input = '/home/conquistador/code/github/python-01-utilities/image/input/' # image_path_output = '/home/conquistador/code/github/python-01-utilities/image/output/' image_name_input = '01_read_image.jpg' im = Image.open(image_path_input + image_name_input) print('im object: ', im) print('format : ' , im.format) print('size : ' , im.size) print('mode : ' , im.mode) print('filename : ' , im.filename) print('width : ' , im.width) print('height : ' , im.height) print('info : ' , im.info) # This will display image on screen # im.show() print('*** Program Ended ***')

view raw
hosted with ❤ by GitHub

Output of this program

*** Program Started ***
im object: <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=1920x1285 at 0x7F7FB79F6518>
format : JPEG
size : (1920, 1285)
mode : RGB
width : 1920
height : 1285
info : {'jfif': 257, 'jfif_version': (1, 1), 'jfif_unit': 0, 'jfif_density': (1, 1), 'progressive': 1, 'progression': 1}
*** Program Ended ***

## How to check file size in Python

Many times while doing file processing python, we need to know file size in bytes/KBs/MBs. You can get file size using multiple methods, following are two simple methods to get file size using os module.

I have run this file for two inputs,one is image and another is empty file.

 ################################################################################################ # name: file_size.py # desc: Getting gile size using python # date: 2019-02-10 # Author: conquistadorjd ################################################################################################ import io, os print('*** Program Started ***') image_path_input = '/home/conquistador/code/github/python-01-utilities/file/input/' image_name_input = 'file_size-01.jpg' #'file_size-02' if os.stat(image_path_input + image_name_input).st_size ==0 : print('Input file is empty') else : print('Input file is not empty') print('File size (in Bytes) : ',os.stat(image_path_input + image_name_input).st_size) print('File size (in Bytes) : ',os.path.getsize (image_path_input+image_name_input)) image_name_input = 'file_size-02' if os.stat(image_path_input + image_name_input).st_size ==0 : print('Input file is empty') else : print('Input file is not empty') print('File size (in Bytes) : ',os.stat(image_path_input + image_name_input).st_size) print('File size (in Bytes) : ',os.path.getsize (image_path_input+image_name_input)) print('*** Program Ended ***')

view raw
file_size.py
hosted with ❤ by GitHub

Here is the output of the program

\$ python3.6 file_size.py
*** Program Started ***
Input file is not empty
File size (in Bytes) : 147162
File size (in Bytes) : 147162
Input file is empty
File size (in Bytes) : 0
File size (in Bytes) : 0
*** Program Ended ***

Actual file size

I have added a check to see if file size is empty, you might need to check file size before doing any processing on files.