Resolution sorting with Ruby and RMagick

    Good day. Reading the Habr, I came across the article “Sorting images by resolution using Python and PIL” (later the article “Sorting images by resolution ... on the PowerShell scene” appeared ), read the comments and wanted to write something similar in Ruby.
    image

    Please do not judge me, but only criticize! In fact, I just recently started to learn Ruby, or rather, this is my first program, so any errors found will only be beneficial. The program is written in Ruby using the RMagick library. How the program works:

    1) The user enters the path to the directory with pictures (jpg, png, gif expands elementarily - (jpg | png | gif | other formats)
    2) Then the path to the folder in which subdirectories with a name equal to the resolution of the pictures will be created.
    3) Next, the program “runs” recursively through the directories with pictures, finding files with the extension jpg | png | gif, determines the resolution and checks for the presence of the directory with the corresponding resolution in the name, if it does not, it creates it.
    4) Copies a file, counts the number of copied files.

    The Ruby code looks a little prettier - my opinion. I think some people will be interested in comparing the similar Ruby and Python code, only in my program copying files instead of moving them.

    What has not been done: check for the existence of the copied file, and if it exists, rename it.

    Copy Source | Copy HTML
    1. require 'find'
    2. require 'fileutils'
    3. require 'RMagick'
    4.  
    5.  
    6. def image_sort(unsort_path, sort_path)
    7.   count =  0
    8.   if !File.directory?(sort_path)
    9.     FileUtils.mkdir sort_path
    10.   end
    11.   if File.directory?(unsort_path)
    12.   Find.find(unsort_path) { |fname|
    13.     if /\.(jpg|png|gif)$/i =~ fname
    14.       count += 1
    15.       img = Magick::Image::read(fname).first
    16.       wh_dir_name = img.columns.to_s + 'x' + img.rows.to_s
    17.       if !File.directory?(sort_path + wh_dir_name)
    18.         FileUtils.mkdir sort_path + wh_dir_name
    19.       end
    20.       FileUtils.cp(fname, sort_path + wh_dir_name)
    21.       puts fname + ' copied'
    22.     end
    23.   }
    24.   else
    25.     puts unsort_path + ' not found'
    26.   end
    27.   puts count.to_s + ' file(s) copied'
    28. end
    29.  
    30. puts 'Path to pictures: '
    31. pd = gets
    32. pd.chomp!
    33. puts 'Path to new sort directory: '
    34. sd = gets
    35. sd.chomp!
    36. image_sort( pd, sd )


    Result:
    image
    image
    It so happened that the pictures for the test had different sizes.

    Also popular now: