Home > Software design >  How to check for different file format extensions and accept valid ones?
How to check for different file format extensions and accept valid ones?

Time:07-25

I want help to make the python script below check for different picture format extensions on the uploaded image file such as the following strings:

"JPG", "JPEG", "jpg", "jpeg", "png", "PNG", "bmp", "BMP", "gif", "GIF", "tiff", "TIFF", "webp", "WEBP"

then accept anyone available based on string comparison, then reject anything (file) outside it. My code is below:

from tkinter import *
from tkinter import filedialog as fd
import os
from PIL import Image


root=Tk()
root.geometry("400x400")
root.title("Image_Conversion_App")


def jpg_to_ico():
    filename=fd.askopenfilename()
    if filename.endswith("JPG"):
        Image.open(filename).save("sample1.ico")
    else:
        Label_2=Label(root,text="Error!", width=20,fg="red", font=("bold",15))
        Label_2.place(x=80,y=280)

def png_to_ico():
    filename=fd.askopenfilename()
    if filename.endswith(".PNG"):
        Image.open(filename).save("sample2.ico")
    else:
        Label_2=Label(root,text="Error!", width=20,fg="red", font=("bold",15))
        Label_2.place(x=80,y=280)

Label_1=Label(root,text="Browse A File", width=20, font=("bold",15))
Label_1.place(x=80,y=80)

Label_3=Label(root, text="</Eddy/> \n", width=80, font=("bold",8))
Label_3.place(x=10,y=365)


Button(root,text="JPG_to_ICO", width=20, height=2, bg="brown",fg="white", command=jpg_to_ico).place(x=120,y=120)
Button(root,text="PNG_to_ICO", width=20, height=2, bg="brown",fg="white", command=png_to_ico).place(x=120,y=220)

root.mainloop()

The code above works well but only if the uploaded picture file extension ends with **.JPG or .PNG**, anything outside it is error as you can see in the code.

CodePudding user response:

you can declare a set of allowed extensions like this:

ALLOWED_EXTENSIONS = {"jpg", "jpeg", "png", "bmp", "gif", "tiff", "webp"}

You will also need a function to check the file extension:

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

And now you can make your convert function look like this:

def convert_to_ico():
    filename = fd.askopenfilename()
    if allowed_file(filename):
        Image.open(filename).save('picture.ico')
    else:
        Label_2=Label(root,text="Error!", width=20,fg="red", font=("bold",15))
        Label_2.place(x=80,y=280)

And as a result, you do not need a bunch of different buttons, you need one button that converts any of the allowed formats. You don't need many features because they all do the same thing. This digging can be done the way you do, i.e. :

btn = Button(root,text="Convert to .ICO", width=20, height=2, bg="brown",fg="white",command=convert_to_ico)
btn.place(x=120,y=120)

P.S. Based in part on Flask File Uploads Guide

As an alternative, I can offer you the setting of the file selection window. See:

filename = fd.askopenfilename(
        filetypes=[
            (f"{ext.upper()} Images", f"*.{ext}") for ext in ALLOWED_EXTENSIONS 
        ]
    )

Thus, the user will not be able to select a file with an unresolved extension.

You can read about it here

  • Related