Resim Yeniden Boyutlandırma PS Betiği [Kayıpsız Büyütme/Küçültme]

Programlama ve Script dilleri konusunda bilgi paylaşım alanıdır.
Cevapla
Kullanıcı avatarı
TRWE_2012
Zettabyte1
Zettabyte1
Mesajlar: 15764
Kayıt: 25 Eyl 2013, 13:38
cinsiyet: Erkek
Teşekkür etti: 2768 kez
Teşekkür edildi: 5751 kez

Resim Yeniden Boyutlandırma PS Betiği [Kayıpsız Büyütme/Küçültme]

Mesaj gönderen TRWE_2012 »

Merhabalar

Ekran Görüntüsü :
Resim
KOD İÇERİĞİ : ( resize-img_v2.ps1 )

Kod: Tümünü seç

# ============================================================
# RESIZE-IMG v2.1 - Resim Boyutlandırma Aracı (Geliştirilmiş)
# Windows PowerShell Versiyonu (PS 5.1 ve 7.x Uyumlu)
# ============================================================
# Kullanım Örnekleri :
# Klasör vererek (otomatik isimlendirme)
#.\resize-img_v2.1.ps1 -InputFile "C:\resim.png" -Width 1366 -Height 768 -OutputFile "C:\Masaüstü"

# Dosya vererek
#.\resize-img_v2.1.ps1 -InputFile "C:\resim.png" -Width 1366 -Height 768 -OutputFile "C:\Masaüstü\yeni.jpg"

# Parametresiz (interaktif)
#.\resize-img_v2.1.ps1
# ============================================================

# ============================================================

# ============================================================
# PARAMETRE TANIMLARI (EN BAŞTA OLMALI!)
# ============================================================
param(
    [string]$InputFile  = "",
    [string]$Width      = "",
    [string]$Height     = "",
    [string]$KeepAspect = "",
    [string]$Quality    = "",
    [string]$OutputFile = ""
)

# ============================================================
# YARDIMCI FONKSİYONLAR
# ============================================================

# Hata göster ve çık
function Exit-With-Error {
    param([string]$Message, [int]$Code = 1)
    Write-Host ""
    Write-Host "HATA: $Message" -ForegroundColor Red
    Write-Host ""
    Read-Host "Çıkmak için ENTER..."
    exit $Code
}

# Boyut formatlama
function Format-FileSize {
    param([long]$bytes)
    if ($bytes -lt 1KB) { return "$bytes B" }
    elseif ($bytes -lt 1MB) { return "{0:N2} KB" -f ($bytes / 1KB) }
    else { return "{0:N2} MB" -f ($bytes / 1MB) }
}

# Türkçe karakter desteği
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8

# ============================================================
# BAŞLIK
# ============================================================
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host "   RESIZE-IMG v2.1 - Resim Boyutlandırma Aracı" -ForegroundColor Cyan
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host ""

# ============================================================
# PARAMETRE KONTROLÜ VE İNTERAKTİF MOD
# ============================================================
if ([string]::IsNullOrWhiteSpace($InputFile) -or 
    [string]::IsNullOrWhiteSpace($Width) -or 
    [string]::IsNullOrWhiteSpace($Height)) {
    
    if ([string]::IsNullOrWhiteSpace($InputFile)) {
        $InputFile = (Read-Host "Girdi dosyasının tam yolu").Trim()
    }
    if ([string]::IsNullOrWhiteSpace($Width)) {
        $Width = (Read-Host "Genişlik (piksel)").Trim()
    }
    if ([string]::IsNullOrWhiteSpace($Height)) {
        $Height = (Read-Host "Yükseklik (piksel)").Trim()
    }
}

# Opsiyonel parametreler (boşsa sor)
if ($KeepAspect -notin @("y","n","Y","N") -and [string]::IsNullOrWhiteSpace($KeepAspect)) {
    $ans = (Read-Host "Oran korunsun mu? (y/n, varsayılan: n)").Trim()
    $KeepAspect = if ([string]::IsNullOrWhiteSpace($ans)) { "n" } else { $ans }
} elseif ($KeepAspect -notin @("y","n","Y","N")) {
    $KeepAspect = "n"
}

if ([string]::IsNullOrWhiteSpace($Quality)) {
    $ans = (Read-Host "Kalite (1-100 veya '-', varsayılan: -)").Trim()
    $Quality = if ([string]::IsNullOrWhiteSpace($ans)) { "-" } else { $ans }
}

if ([string]::IsNullOrWhiteSpace($OutputFile)) {
    $OutputFile = (Read-Host "Çıktı dosya yolu (boş bırakılırsa otomatik)").Trim()
}

# ============================================================
# 1. GİRDİ DOSYASI KONTROLÜ
# ============================================================
if ([string]::IsNullOrWhiteSpace($InputFile)) {
    Exit-With-Error -Message "Girdi dosyası belirtilmedi." -Code 3
}

if (-not (Test-Path -Path $InputFile -PathType Leaf)) {
    Exit-With-Error -Message "Dosya bulunamadı: '$InputFile'" -Code 3
}

# ============================================================
# 2. GENİŞLİK / YÜKSEKLİK DOĞRULAMA
# ============================================================
$w = 0
$h = 0
if (-not [int]::TryParse($Width, [ref]$w) -or $w -le 0) {
    Exit-With-Error -Message "Geçersiz genişlik değeri: '$Width' (pozitif tam sayı olmalı)" -Code 2
}
if (-not [int]::TryParse($Height, [ref]$h) -or $h -le 0) {
    Exit-With-Error -Message "Geçersiz yükseklik değeri: '$Height' (pozitif tam sayı olmalı)" -Code 2
}

# ============================================================
# 3. UZANTI KONTROLÜ
# ============================================================
$inExt = [System.IO.Path]::GetExtension($InputFile).TrimStart(".").ToLowerInvariant()
if ($inExt -notin @("png", "jpg", "jpeg", "webp")) {
    Exit-With-Error -Message "Desteklenmeyen girdi uzantısı: '.$inExt' (png|jpg|jpeg|webp)" -Code 5
}

# ============================================================
# 4. KALİTE DOĞRULAMA
# ============================================================
$qualityOption = @()
if ($Quality -ne "-" -and -not [string]::IsNullOrWhiteSpace($Quality)) {
    $qVal = 0
    if (-not [int]::TryParse($Quality, [ref]$qVal) -or $qVal -lt 1 -or $qVal -gt 100) {
        Exit-With-Error -Message "Kalite 1-100 aralığında olmalı veya '-' olmalı. Girilen: '$Quality'" -Code 6
    }
    $qualityOption = @("-quality", $qVal.ToString())
}

# ============================================================
# 5. IMAGEMAGICK TESPİTİ (GELİŞTİRİLDİ)
# ============================================================
$imCmd = $null

# Önce PATH'te ara
try {
    $cmd = Get-Command -Name "magick" -ErrorAction Stop
    $imCmd = $cmd.Source
    Write-Host "ImageMagick bulundu (PATH): $imCmd" -ForegroundColor Gray
} catch {
    # PATH'te yoksa, bilinen kurulum yollarını dene
    $commonPaths = @(
        "C:\Program Files\ImageMagick*\magick.exe",
        "C:\Program Files (x86)\ImageMagick*\magick.exe",
        "$env:LOCALAPPDATA\ImageMagick*\magick.exe"
    )
    foreach ($pattern in $commonPaths) {
        $found = Get-Item -Path $pattern -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -First 1
        if ($found) {
            $imCmd = $found.FullName
            Write-Host "ImageMagick bulundu (kurulum): $imCmd" -ForegroundColor Gray
            break
        }
    }
}

if (-not $imCmd -or -not (Test-Path $imCmd)) {
    Exit-With-Error -Message "ImageMagick bulunamadı! Lütfen https://imagemagick.org adresinden yükleyin ve 'Add to PATH' seçeneğini işaretleyin." -Code 4
}

# ============================================================
# 6. ÇIKTI DOSYA YOLU HESAPLAMA (KRİTİK DÜZELTME)
# ============================================================
# Kullanıcı bir KLASÖR yolu verdiyse, otomatik dosya ismi oluştur
# Kullanıcı bir DOSYA yolu verdiyse, onu kullan
# Kullanıcı boş bıraktıysa, girdiyle aynı dizine otomatik isim oluştur

$autoGenerate = $false

if ([string]::IsNullOrWhiteSpace($OutputFile)) {
    # Boş bırakıldı → otomatik
    $autoGenerate = $true
} elseif (Test-Path -Path $OutputFile -PathType Container) {
    # Bir klasör → içine otomatik dosya oluştur
    Write-Host "UYARI: Çıktı olarak bir klasör belirtildi. Dosya otomatik isimlendirilecek." -ForegroundColor Yellow
    $autoGenerate = $true
} elseif (-not (Test-Path -Path $OutputFile)) {
    # Dosya yok ama klasör de değil → muhtemelen yeni dosya yolu
    # Ama uzantısı yoksa veya geçersizse kontrol et
    $outExt = [System.IO.Path]::GetExtension($OutputFile).TrimStart(".").ToLowerInvariant()
    if ([string]::IsNullOrWhiteSpace($outExt)) {
        Write-Host "UYARI: Çıktı dosyasının uzantısı belirtilmemiş. Otomatik uzantı eklenecek." -ForegroundColor Yellow
        $autoGenerate = $true
    }
}

if ($autoGenerate) {
    $dir = if ([string]::IsNullOrWhiteSpace($OutputFile)) { 
        [System.IO.Path]::GetDirectoryName($InputFile) 
    } else { 
        $OutputFile 
    }
    $baseName = [System.IO.Path]::GetFileNameWithoutExtension($InputFile)
    $outFile = Join-Path -Path $dir -ChildPath "${baseName}_${w}x${h}.${inExt}"
    Write-Host "Otomatik çıktı dosyası: $outFile" -ForegroundColor Gray
} else {
    $outFile = $OutputFile
}

# Çıktı dizini yoksa oluştur
$outDir = [System.IO.Path]::GetDirectoryName($outFile)
if (-not [string]::IsNullOrWhiteSpace($outDir) -and -not (Test-Path -Path $outDir -PathType Container)) {
    New-Item -ItemType Directory -Path $outDir -Force | Out-Null
    Write-Host "Çıktı dizini oluşturuldu: $outDir" -ForegroundColor Gray
}

# ============================================================
# 7. RESIZE ARGÜMANI
# ============================================================
if ($KeepAspect -eq "y" -or $KeepAspect -eq "Y") {
    $resizeArg = "${w}x${h}"
    Write-Host "Mod: Oran korunacak" -ForegroundColor Gray
} else {
    $resizeArg = "${w}x${h}!"
    Write-Host "Mod: Tam boyut (oran korunmayabilir)" -ForegroundColor Gray
}

# ============================================================
# 8. DÖNÜŞTÜRME İŞLEMİ (HATA MESAJI GÖSTERİLİYOR)
# ============================================================
Write-Host ""
Write-Host "İşlem başlıyor..." -ForegroundColor Cyan
Write-Host "  Girdi    : $InputFile" -ForegroundColor White
Write-Host "  Boyut    : ${w}x${h}" -ForegroundColor White
Write-Host "  Kalite   : $(if($qualityOption.Count -gt 0){$qualityOption[1]}else{'varsayılan'})" -ForegroundColor White
Write-Host "  Çıktı    : $outFile" -ForegroundColor White
Write-Host ""

$imArgs = @($InputFile, "-resize", $resizeArg) + $qualityOption + @($outFile)

try {
    # Hata çıktısını yakala
    $errorOutput = & $imCmd @imArgs 2>&1
    
    if ($LASTEXITCODE -eq 0) {
        Write-Host "============================================================" -ForegroundColor Green
        Write-Host "   İŞLEM BAŞARILI" -ForegroundColor Green
        Write-Host "============================================================" -ForegroundColor Green
        Write-Host "Kaydedildi: $outFile" -ForegroundColor Green
        
        if (Test-Path -Path $outFile -PathType Leaf) {
            $outSize = (Get-Item -Path $outFile).Length
            Write-Host "Dosya boyutu: $(Format-FileSize $outSize)" -ForegroundColor Gray
        }
    } else {
        Write-Host "ImageMagick hata çıktısı:" -ForegroundColor Red
        Write-Host $errorOutput -ForegroundColor Red
        Write-Host ""
        Exit-With-Error -Message "ImageMagick dönüşüm işlemi başarısız oldu (Çıkış kodu: $LASTEXITCODE)" -Code 7
    }
} catch {
    Write-Host "Beklenmeyen hata: $($_.Exception.Message)" -ForegroundColor Red
    Exit-With-Error -Message "Dönüştürme sırasında hata oluştu." -Code 8
}

Write-Host ""
Read-Host "Çıkmak için ENTER..."
Betiğin çalışması için gereksinim :

Betiğin içinde "ImageMagick Kurulum Yolu Otomatik Bulma" kod bloğu vardır.

Kod: Tümünü seç

# PATH'te yoksa, bilinen kurulum yollarını tarar
$commonPaths = @(
    "C:\Program Files\ImageMagick*\magick.exe",
    "C:\Program Files (x86)\ImageMagick*\magick.exe"
)
Yani sisteminizde "ImageMagick" yazılımı yüklü olmalıdır.

Güle güle kullanın.

NOT :

Ekran görüntüsünde işlem yapılan duvar kağıdı...

Resim-659_1366x768.png [ DumluPınar BaşKomutanlık Meydan Savaşı'nı anlatan askeri harita ]
Resim
Yapay Zeka Craiyon (Görsel oluşturma yüksek zekası) ile asıl resmin 3D Kabartma Versiyonu'dur.
Cevapla

“Programlama ve Script dilleri” sayfasına dön