Advertisement
here2share

# fix_corrupt_images.py

Sep 19th, 2023
896
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.01 KB | None | 0 0
  1. # fix_corrupt_images.py ZZZ had imagined this should be a way to fix corrupted jpg images, but no...
  2.  
  3. import os
  4. from tkinter import *
  5. from tkinter import filedialog, messagebox
  6. from PIL import Image, ImageTk, ImageDraw
  7.  
  8. root = Tk()
  9. root.title("Fix_Corrupt_Images")
  10. ww = 300
  11. hh = 80
  12. root.geometry(f"{ww}x{hh}+0+0")
  13. canvas = Canvas(root, width=ww, height=hh)
  14. canvas.pack(side="bottom", pady=3, fill='both', expand=1)
  15.  
  16. canvas.create_text(ww//2, 20, text="Select Image To Commence", font='ariel 14', fill='darkgreen')
  17.  
  18. human = """QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890!@#$%^&*()[]{}+`~_ \|;:'\",.<>/?\xa0"""# fn_resize.py
  19.  
  20. def resize(x, y, area, new_area):
  21.     ratio = (new_area / area) ** 0.5
  22.     w_new = int(x * ratio)
  23.     h_new = int(y * ratio)
  24.     if w_new > h_new:
  25.         while (w_new + 1) * h_new < new_area:
  26.             w_new += 1
  27.     else:
  28.         while w_new * (h_new + 1) < new_area:
  29.             h_new += 1
  30.     return w_new, h_new, [w_new * h_new]
  31.  
  32. def open_image(img):
  33.     """
  34.     Open the image in a new window of size same as the image size
  35.     """
  36.     size = img.size
  37.     window = Toplevel()
  38.     window.geometry(f"{size[0]}x{size[1]}+-10+0")
  39.  
  40.     tk_img = ImageTk.PhotoImage(img)
  41.     img_box = Label(window, image=tk_img, anchor='nw')
  42.     img_box.image = tk_img
  43.     img_box.pack()
  44.  
  45.     # add event listener for dragging the image within the window
  46.     def on_button_press(event):
  47.         img_box._drag_data = event.x, event.y
  48.  
  49.     def on_button_release(event):
  50.         img_box._drag_data = None
  51.  
  52.     def on_motion(event):
  53.         if img_box._drag_data:
  54.             x, y = img_box._drag_data
  55.             dx = event.x - x
  56.             dy = event.y - y
  57.             img_box.place(x=img_box.winfo_x() + dx, y=img_box.winfo_y() + dy)
  58.  
  59.     img_box.bind('<ButtonPress-1>', on_button_press)
  60.     img_box.bind('<ButtonRelease-1>', on_button_release)
  61.     img_box.bind('<B1-Motion>', on_motion)
  62.  
  63. def select_file():
  64.     filename = filedialog.askopenfilename()
  65.     file, ext = os.path.splitext(filename)
  66.     if not filename:
  67.         return
  68.     if not any([k == ext.lower() for k in ('.jpg', '.jpeg')]):
  69.         return
  70.        
  71.     with open(filename, 'rb') as f:
  72.         # Reading the compressed data into a bytes object
  73.         bytecode_str = f.read()
  74.  
  75.     # Find the start of the image data section
  76.     start = bytecode_str.find(b'\xff\xda') + 2 # skip over the header bytes
  77.  
  78.     # Read the width and height data from the image header
  79.     header = bytecode_str[:start]
  80.     height_index = header.find(b'\xff\xc0') + 5
  81.     width_index = height_index + 2
  82.     width = (header[width_index] << 8) + header[width_index + 1]
  83.     height = (header[height_index] << 8) + header[height_index + 1]
  84.  
  85.     # Calculate the number of pixels in the image
  86.     num_pixels = width * height
  87.  
  88.     # Extract the image data section
  89.     image_data = bytecode_str[:]
  90.  
  91.     # Extract the RGB values for each pixel in the image data section
  92.     rgb_values = []
  93.     i = 0
  94.     while 1:
  95.         try:
  96.             r = image_data[i * 3]
  97.             g = image_data[i * 3 + 1]
  98.             b = image_data[i * 3 + 2]
  99.         except:
  100.             break
  101.         if all([-1 < i < 256 for i in (r, g, b)]):
  102.             rgb_values.append((r, g, b))
  103.         i += 1
  104.    
  105.     resize_width, resize_height, _ = resize(width, height, num_pixels, len(rgb_values))
  106.     print(width, height, num_pixels)
  107.     print(resize_width, resize_height, resize_width*resize_height, len(rgb_values))
  108.            
  109.     # Create new image with extracted dimensions and RGB data
  110.     img = Image.new(mode="RGB", size=(resize_width, resize_height))
  111.     try:
  112.         img.putdata(rgb_values)
  113.     except:
  114.         img = Image.new(mode="RGB", size=(width, height))
  115.         img.putdata(rgb_values)    
  116.  
  117.     # display the image for confirmation to save
  118.     open_image(img)
  119.    
  120.     # ask for permission to save the image
  121.     save = messagebox.askyesno("Save Image", "Do you want to save this image?")
  122.     if save:
  123.         # save image as jpg without overwriting any files
  124.         i = 0
  125.         while 1:
  126.             new_filename = file + str(i) + ".jpg"
  127.             if not os.path.isfile(new_filename):
  128.                 break
  129.             i += 1
  130.         img.save(new_filename)
  131.         messagebox.showinfo("Image Saved", f"The image has been saved as {new_filename}")
  132.  
  133. button = Button(canvas, text="Select Image", command=select_file)
  134. button.pack(side="bottom", pady=10)
  135.  
  136. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement