Skip to content

Instantly share code, notes, and snippets.

@andyhuey
Last active December 19, 2024 19:41
Show Gist options
  • Save andyhuey/1953835b0dbe83fecbd516eb646c6c9c to your computer and use it in GitHub Desktop.
Save andyhuey/1953835b0dbe83fecbd516eb646c6c9c to your computer and use it in GitHub Desktop.
A script to convert EPUB files to CBZ (for the specific case of an EPUB with image files following a specific pattern)
# A script to convert EPUB files to CBZ
# (for the specific case of an EPUB with image files following a specific pattern)
# (written with some help from ChatGPT)
# Check if the EPUB file path is provided as a command-line argument
if ($args.Count -eq 0) {
Write-Host "Usage: .\epub2cbz.ps1 <path-to-epub-file>" -ForegroundColor Yellow
return
}
# Get the EPUB file path from the command-line argument
$epubFilePath = $args[0]
# Check if the file exists
if (-Not (Test-Path $epubFilePath)) {
Write-Host "The specified EPUB file does not exist." -ForegroundColor Red
return
}
# Define temporary folder and output file paths
$tempFolder = "${env:TEMP}\EPUB_Extraction"
$outputCBZ = (Join-Path (Split-Path $epubFilePath -Parent) (([IO.Path]::GetFileNameWithoutExtension($epubFilePath)) + "-new.cbz"))
# Ensure the temp folder is empty
if (Test-Path $tempFolder) {
Remove-Item -Recurse -Force $tempFolder
}
New-Item -ItemType Directory -Path $tempFolder | Out-Null
# Step 1: Extract the EPUB file to the temp folder
# [System.IO.Compression.ZipFile]::ExtractToDirectory($epubFilePath, $tempFolder)
Expand-Archive -Path $epubFilePath -DestinationPath $tempFolder
# Check if extraction was successful
if (-Not (Test-Path (Join-Path $tempFolder "OEBPS\images"))) {
Write-Host "Extraction failed or the OEBPS\images folder is missing." -ForegroundColor Red
return
}
# Step 2: Create the CBZ file from the images
$imageFolder = Join-Path $tempFolder "OEBPS\images"
$imageFiles = @()
$imageFiles += Get-ChildItem -Path $imageFolder -Filter "cover.jpeg" -Recurse | Sort-Object Name
$imageFiles += Get-ChildItem -Path $imageFolder -Filter "img*.jpeg" -Recurse | Sort-Object Name
if ($imageFiles.Count -eq 0) {
Write-Host "No cover.jpeg or img*.jpeg files found in the images folder." -ForegroundColor Yellow
return
}
# Compress the selected files into a CBZ
Compress-Archive @($imageFiles.FullName) -DestinationPath $outputCBZ -Force
if (-Not (Test-Path $outputCBZ)) {
Write-Host "Failed to create the CBZ file." -ForegroundColor Red
return
}
# Step 3: Clean up the temp folder
Remove-Item -Recurse -Force $tempFolder
# Notify the user of success
Write-Host "CBZ file created successfully: $outputCBZ" -ForegroundColor Green
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment