Essay -Python batch conversion image format

Imageio libraries: Imageio. Readthedocs. IO/en/stable/I… Supported image formats: imageio. Readthedocs. IO/en/stable/f…

It is very convenient to convert images in batches using Python. Here, we use the small Python library Imageio to achieve the image format conversion.

Note: The following code does the conversion in the simplest case.

  • Code:
import os
import imageio


def image_format_converter(img_src, img_dst, dst_format='jpg') :
	""" "Convert the image in the img_src directory to the dst_format format (JPG format by default), and save the image to the img_dst directory img_src: the original image directory. When passing a parameter, note that it ends with a '/'. For example :'./test_image/' img_dst: the directory to save the image after the transformation. When passing a parameter, note that it ends with a '/'. Dst_format: the format of the image you want to convert to. The default format is JPG. """
    img_list = os.listdir(img_src)
    if not os.path.exists(img_dst):
        os.makedirs(img_dst)
    for img in img_list:
        img_name = img[:img.rindex('. ')] # Capture the image name without formatting (.png,.bmp, etc.)
        im = imageio.imread(img_src + img)
        imageio.imwrite(img_dst + img_name + '. ' + dst_format, im)
        print("{} converted format to {} successfully!".format(img, dst_format))
        

if __name__ == "__main__":
    image_format_converter('./test_images/'.'./test_images/jpg/'.'jpg')

Copy the code

Creation is not easy, like words add a focus a like, ❤ thank you thank ❤