[python] Modify the file suffix and convert JPG to PNG/PNG to JPG

[python] Modify the file suffix and convert JPG to PNG/PNG to JPG

Preface

In this article, there are only two methods to convert JPG format images to PNG. The first is to use os.rename to directly modify the file suffix; the second is to use replace. Both are very versatile and can be used in almost all file formats. Conversion, but there are slight differences, so I won’t say much and will just open it up.

os.rename

import os
#注意文件路径格式中要用“C:/file/img.jpg”
#或“C:\\file\\img.jpg”
#或r‘C:\file\img.jpg’
filename = 'textx4.jpg'
transF = os.path.splitext(filename) 
#将文件名与后缀分开。transF[0]为文件名,transF[1] 为后缀             
new_name = transF[0] + '.png'   
os.rename(filename, new_name) 

If there are multiple files that you want to change to multiple suffixes, you can use the following batch operation:

import os
 
def Rename(filename):
    transF = os.path.splitext(file)
    if transF[1] == '.jpg':                   
        new_name = ext[0] + '.png'       
        os.rename(filename, new_name) 
    elif transF[1] == '.txt':
        new_name = ext[0] + '.py'
        os.rename(filename, new_name)

def transform(file_path):
    # 读取所有文件
    allFiles = os.listdir(file_path) 
    for file in allFiles:
        file_path1 = os.path.join(file_path, file) 
        if os.path.isdir(file_path1):  
            transform(file_path1)
        else:
            os.chdir(file_path)
            Rename(file) 
if __name__ == '__main__':        
	# 文件夹路径
	file_path = “C:/file”
	transform(file_path)

replace

Take the picture as an example, use opencv to save it as a picture, delete the transparency channel of the png picture, and convert it into a 3-channel png picture.

import cv2

def transFor(filename):                                      
    # img = cv2.imread(filename, 1)  
    filename = filename.replace(".JPG", ".png")   
    img = cv2.imread(filename, 1)           
    jpg_img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
    #下面注释的这行最后这个数字0表示压缩程度,取值0-10,越大图片越模糊
    # cv2.imwrite('textx2.png', jpg_img,[cv2.IMWRITE_PNG_COMPRESSION, 0])  
    cv2.imwrite('text1.png', jpg_img)            
    
if __name__ == '__main__': 
	filename = 'text.jpg'
	transFor(filename)

The difference between the two format conversions for pictures is as follows. The picture below shows the application of two methods to convert the same JPG format into png format. The left picture is method 1 and the right picture is method 2. It may be the reason for deleting a channel. I feel that method 2 is slightly more blurry.

Insert image description here

Guess you like

Origin blog.csdn.net/qq_43605229/article/details/124364887