if so how can i avoid it?
check if the file exists before opening it, you can use:
var file = File.new()
#do stuff with the file here
#say user file not found
Also how to limit the input to images only?
var allowed_file_ext = ["jpg","png","bmp"]
var file_name = "foo.jpg"
var ext = file_name.split(".")[-1] #split the filename and returns array. [-1] will give you the last item of the array, in this case "jpg"
if ext in allowed_file_ext: #jpg is an element of allowed_file_ext
#not valid file extension
be aware that file_name.split(".")[-1] could throw an error if the user inputs a filename without file extension. but i think you are able to change the code accordingly ;)