generated from MaxGripe/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.fs
83 lines (65 loc) · 2.42 KB
/
Program.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
open System
open System.Drawing
open System.Drawing.Imaging
open System.IO
let borderSizePercentage = 0.05
let getImageFormat (extension: string) =
match extension.ToLower() with
| ".jpg"
| ".jpeg" -> ImageFormat.Jpeg
| ".png" -> ImageFormat.Png
| ext -> failwithf "Only PNG and JPG files are supported. Given file extension: %s" ext
let saveImage (newImage: Image) (path: string) (format: ImageFormat) =
let saveAsJpeg () =
let jpegCodec =
ImageCodecInfo.GetImageDecoders()
|> Array.find (fun codec -> codec.FormatID = ImageFormat.Jpeg.Guid)
use encoderParams = new EncoderParameters(1)
use encoderParam = new EncoderParameter(Encoder.Quality, 100L)
encoderParams.Param.[0] <- encoderParam
newImage.Save(path, jpegCodec, encoderParams)
let saveActions =
match format with
| f when f = ImageFormat.Jpeg -> saveAsJpeg
| _ -> (fun () -> newImage.Save(path, format))
saveActions ()
let addWhiteBorderAndReplace (inputFile: string) =
let format = getImageFormat (Path.GetExtension(inputFile))
use image = Image.FromFile(inputFile)
let borderSize =
int (
float (min image.Width image.Height)
* borderSizePercentage
)
let newWidth = image.Width + (2 * borderSize)
let newHeight = image.Height + (2 * borderSize)
use newImage = new Bitmap(newWidth, newHeight)
use graphics = Graphics.FromImage(newImage)
graphics.Clear(Color.White)
graphics.DrawImage(image, borderSize, borderSize, image.Width, image.Height)
if format = ImageFormat.Jpeg then
image.PropertyItems
|> Array.iter newImage.SetPropertyItem
image.Dispose()
let tempFileName = Path.GetRandomFileName()
let tempFilePath = Path.Combine(Path.GetDirectoryName(inputFile), tempFileName)
saveImage newImage tempFilePath format
File.Replace(tempFilePath, inputFile, null)
[<EntryPoint>]
let main argv =
match argv with
| [| filePath |] ->
try
addWhiteBorderAndReplace filePath
printfn "White border added to the file: %s" filePath
0
with
| :? FileNotFoundException ->
printfn "File not found: %s" filePath
1
| ex ->
printfn "Error processing file: %s" ex.Message
1
| _ ->
printfn "Please provide the path to the file as an argument."
1