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.

Here is simple structure to help you understand custom WP_Query

// 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.

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.

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

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.

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.

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

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.

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

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.

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.

In this article we will see how to read file using pillow and get basic attributes.

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

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
filename : /home/conquistador/code/github/python-01-utilities/image/input/01_read_image.jpg
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.

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.