A Better Way to Write Scripts

During graduation season, I took some photos with my classmates. The photos shared later were in the HEIC format, which can be opened directly on the computer. However, the iCloud album only supports the jpg format for uploading photos. Even if these photos were taken with an iPhone, they cannot be uploaded directly. There was no choice but to manually convert the photo format. There are many online tools for converting HEIC to JPG, but they can only upload one by one, and then download one by one. This obviously is not a good solution for situations where a large number of photos need to be processed. Therefore, the natural plan was to write a script for conversion.

Of course, now with ChatGPT, there's no need to write scripts personally. Just throw the problem at it, and we only need to do the code moving work.

It looks very good. Copy it locally, replace the path and run it, only to find that the script cannot run properly. The reason is that the Pillow library used does not support HEIC format pictures. Continue to hand the problem over to it, and it recommended a pyheif library for me to handle. However, this library requires the MSVC toolchain to compile and install, and it always fails to install on my computer. After trying several of its recommended dependent libraries, none of them could be installed. I was taught a tough lesson by Python's low portability of cross-platform installation and building. It would be too exaggerated to configure an environment or a container just to write a script.

So I used F#, which I've been learning recently, to replace it. Continue to hand the problem over to ChatGPT. After copying and pasting the code and running it a few times, the task was successfully completed.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#r "nuget:Magick.NET-Q16-AnyCPU"

open System.IO
open ImageMagick

let convertHEICtoJPG (inputPath: string) (outputPath: string) =
    let image = new MagickImage(inputPath)
    image.Format <- MagickFormat.Jpg
    image.Write(outputPath)

// Get all HEIC files in the current directory
let heicFiles = Directory.GetFiles(@"/path/to/you", "*.heic")

// Traverse each HEIC file and convert it
for heicFile in heicFiles do
    let jpgFile = Path.ChangeExtension(heicFile, ".jpg")
    convertHEICtoJPG heicFile jpgFile
    printfn "Conversion completed:%s -> %s" heicFile jpgFile

Compared to Python, using F# to write scripts is actually simple and convenient enough. It can be written in a single fsx file, or you can directly copy the written code to the fsi interactive command line to execute the code segment by segment, which is very convenient. Especially for script code with external dependent libraries, using F# or C# scripts, this one line of code references dependent libraries, which is much more useful than globally installing a dependency in the command line. (At least there won't be installation failure problems)