Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # fix_corrupt_images.py ZZZ had imagined this should be a way to fix corrupted jpg images, but no...
- import os
- from tkinter import *
- from tkinter import filedialog, messagebox
- from PIL import Image, ImageTk, ImageDraw
- root = Tk()
- root.title("Fix_Corrupt_Images")
- ww = 300
- hh = 80
- root.geometry(f"{ww}x{hh}+0+0")
- canvas = Canvas(root, width=ww, height=hh)
- canvas.pack(side="bottom", pady=3, fill='both', expand=1)
- canvas.create_text(ww//2, 20, text="Select Image To Commence", font='ariel 14', fill='darkgreen')
- human = """QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890!@#$%^&*()[]{}+`~_ \|;:'\",.<>/?\xa0"""# fn_resize.py
- def resize(x, y, area, new_area):
- ratio = (new_area / area) ** 0.5
- w_new = int(x * ratio)
- h_new = int(y * ratio)
- if w_new > h_new:
- while (w_new + 1) * h_new < new_area:
- w_new += 1
- else:
- while w_new * (h_new + 1) < new_area:
- h_new += 1
- return w_new, h_new, [w_new * h_new]
- def open_image(img):
- """
- Open the image in a new window of size same as the image size
- """
- size = img.size
- window = Toplevel()
- window.geometry(f"{size[0]}x{size[1]}+-10+0")
- tk_img = ImageTk.PhotoImage(img)
- img_box = Label(window, image=tk_img, anchor='nw')
- img_box.image = tk_img
- img_box.pack()
- # add event listener for dragging the image within the window
- def on_button_press(event):
- img_box._drag_data = event.x, event.y
- def on_button_release(event):
- img_box._drag_data = None
- def on_motion(event):
- if img_box._drag_data:
- x, y = img_box._drag_data
- dx = event.x - x
- dy = event.y - y
- img_box.place(x=img_box.winfo_x() + dx, y=img_box.winfo_y() + dy)
- img_box.bind('<ButtonPress-1>', on_button_press)
- img_box.bind('<ButtonRelease-1>', on_button_release)
- img_box.bind('<B1-Motion>', on_motion)
- def select_file():
- filename = filedialog.askopenfilename()
- file, ext = os.path.splitext(filename)
- if not filename:
- return
- if not any([k == ext.lower() for k in ('.jpg', '.jpeg')]):
- return
- with open(filename, 'rb') as f:
- # Reading the compressed data into a bytes object
- bytecode_str = f.read()
- # Find the start of the image data section
- start = bytecode_str.find(b'\xff\xda') + 2 # skip over the header bytes
- # Read the width and height data from the image header
- header = bytecode_str[:start]
- height_index = header.find(b'\xff\xc0') + 5
- width_index = height_index + 2
- width = (header[width_index] << 8) + header[width_index + 1]
- height = (header[height_index] << 8) + header[height_index + 1]
- # Calculate the number of pixels in the image
- num_pixels = width * height
- # Extract the image data section
- image_data = bytecode_str[:]
- # Extract the RGB values for each pixel in the image data section
- rgb_values = []
- i = 0
- while 1:
- try:
- r = image_data[i * 3]
- g = image_data[i * 3 + 1]
- b = image_data[i * 3 + 2]
- except:
- break
- if all([-1 < i < 256 for i in (r, g, b)]):
- rgb_values.append((r, g, b))
- i += 1
- resize_width, resize_height, _ = resize(width, height, num_pixels, len(rgb_values))
- print(width, height, num_pixels)
- print(resize_width, resize_height, resize_width*resize_height, len(rgb_values))
- # Create new image with extracted dimensions and RGB data
- img = Image.new(mode="RGB", size=(resize_width, resize_height))
- try:
- img.putdata(rgb_values)
- except:
- img = Image.new(mode="RGB", size=(width, height))
- img.putdata(rgb_values)
- # display the image for confirmation to save
- open_image(img)
- # ask for permission to save the image
- save = messagebox.askyesno("Save Image", "Do you want to save this image?")
- if save:
- # save image as jpg without overwriting any files
- i = 0
- while 1:
- new_filename = file + str(i) + ".jpg"
- if not os.path.isfile(new_filename):
- break
- i += 1
- img.save(new_filename)
- messagebox.showinfo("Image Saved", f"The image has been saved as {new_filename}")
- button = Button(canvas, text="Select Image", command=select_file)
- button.pack(side="bottom", pady=10)
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement