Save imported image in the same format (WIP)
[master-thesis.git] / Parasitemia / ParasitemiaUI / PiaZ.fs
index 0215254..8498c64 100644 (file)
@@ -2,7 +2,6 @@
 module ParasitemiaUI.PiaZ
 
 open System
-open System.Windows
 open System.IO
 open System.IO.Compression
 
@@ -10,7 +9,6 @@ open Emgu.CV
 open Emgu.CV.Structure
 
 open Newtonsoft.Json
-open Newtonsoft.Json.Converters
 
 open Types
 
@@ -45,9 +43,10 @@ type DocumentData =
         images : SourceImage list
     }
 
-let mainEntryName = "info.json"
-let imageExtension = ".tiff"
-let currentFileVersion = 2
+let MAIN_ENTRY_NAME = "info.json"
+let DEFAULT_IMAGE_EXTENSION = ".tiff"
+let JSON_EXTENSION = ".json"
+let CURRENT_FILE_VERSION = 3
 
 /// <summary>
 /// Save a document in a give file path. The file may already exist.
@@ -56,35 +55,45 @@ let currentFileVersion = 2
 /// <param name="data"></param>
 /// <exception cref="System.IOException">If the file cannot be written</exception>
 let save (filePath : string) (data : DocumentData) =
-    use file = ZipFile.Open(filePath, ZipArchiveMode.Update)
+    use file = ZipFile.Open (filePath, ZipArchiveMode.Update)
 
+    // We only delete JSON files and removed images.
     for e in List.ofSeq file.Entries do // 'ofSeq' to not iterate a collection currently modified.
-        e.Delete()
+        if Path.GetExtension e.Name = JSON_EXTENSION || data.images |> List.exists (fun img -> img.OriginalName = e.Name) |> not then
+            e.Delete ()
 
     // Main JSON file.
-    let mainEntry = file.CreateEntry(mainEntryName, CompressionLevel.Fastest)
-    use mainEntryWriter = new StreamWriter(mainEntry.Open())
-    mainEntryWriter.Write(JsonConvert.SerializeObject({ patientID = data.patientID; fileVersion = currentFileVersion }))
+    let mainEntry = file.CreateEntry (MAIN_ENTRY_NAME, CompressionLevel.Fastest)
+    use mainEntryWriter = new StreamWriter (mainEntry.Open ())
+    mainEntryWriter.Write (JsonConvert.SerializeObject ({ patientID = data.patientID; fileVersion = CURRENT_FILE_VERSION }))
 
-    // Write each images and the associated information.
+    // Write each images and the associated information as a JSON file.
     for srcImg in data.images do
-        let imgFilename = (string srcImg.num) + imageExtension
-        let imgEntry = file.CreateEntry(imgFilename, CompressionLevel.NoCompression) // FIXME: It seems a compression is applied to this file despite of the 'NoCompression' flag.
-        srcImg.img.ToBitmap().Save(imgEntry.Open(), System.Drawing.Imaging.ImageFormat.Tiff)
-
-        let imgJSONEntry = file.CreateEntry(imgFilename + ".json", CompressionLevel.Fastest)
-        use imgJSONFileWriter = new StreamWriter(imgJSONEntry.Open())
-        imgJSONFileWriter.Write(
-            JsonConvert.SerializeObject(
+        match srcImg.TempFile with
+        | Some imgTempFile ->
+            let imgEntry = file.CreateEntry (srcImg.OriginalName, CompressionLevel.NoCompression)
+            (File.Open (imgTempFile, FileMode.Open, FileAccess.Read)).CopyTo (imgEntry.Open ())
+            srcImg.TempFile <- None
+
+        | None -> ()
+
+        //let imgFilename = (string srcImg.Num) + DEFAULT_IMAGE_EXTENSION
+        //let imgEntry = file.CreateEntry (imgFilename, CompressionLevel.NoCompression)
+        //srcImg.Img.ToBitmap().Save (imgEntry.Open (), System.Drawing.Imaging.ImageFormat.Tiff)
+
+        let imgJSONEntry = file.CreateEntry (srcImg.OriginalName + JSON_EXTENSION, CompressionLevel.Fastest)
+        use imgJSONFileWriter = new StreamWriter (imgJSONEntry.Open ())
+        imgJSONFileWriter.Write (
+            JsonConvert.SerializeObject (
                 {
-                    num = srcImg.num
-                    name = srcImg.name
-                    RBCRadius = srcImg.config.RBCRadius.Pixel
-                    parameters = srcImg.config.Parameters
-                    dateLastAnalysis = srcImg.dateLastAnalysis
-                    rbcs = srcImg.rbcs
-                    healthyRBCBrightness = srcImg.healthyRBCBrightness
-                    infectedRBCBrightness = srcImg.infectedRBCBrightness
+                    num = srcImg.Num
+                    name = srcImg.Name
+                    RBCRadius = srcImg.Config.RBCRadius.Pixel
+                    parameters = srcImg.Config.Parameters
+                    dateLastAnalysis = srcImg.DateLastAnalysis
+                    rbcs = srcImg.RBCs
+                    healthyRBCBrightness = srcImg.HealthyRBCBrightness
+                    infectedRBCBrightness = srcImg.InfectedRBCBrightness
                 }
             )
         )
@@ -93,38 +102,44 @@ let updateDocumentData (fromVersion : int) (toVersion : int) (data : DocumentDat
     for v in fromVersion + 1 .. toVersion do
         match v with
         | 1 -> // Version 0 -> 1 : set initial brightness for rbc.
-            data.images |> List.iter (fun i -> i.healthyRBCBrightness <- 1.f; i.infectedRBCBrightness <- 1.f)
+            data.images |> List.iter (fun i -> i.HealthyRBCBrightness <- 1.f; i.InfectedRBCBrightness <- 1.f)
         | _ -> ()
     data
 
+exception VersionFileNewerException of int
+
 /// <summary>
 /// Load document from a give file path.
 /// </summary>
-/// <param name="filePath"></param>
+/// <param name="filePath">Path to the PiaZ file</param>
+/// <param name="defaultConfig"></param>
 /// <exception cref="System.IOException">If the file cannot be read</exception>
+/// <exception cref="VersionFileNewerException">If the file version is newer than the current supported version</exception>
 let load (filePath : string) (defaultConfig : ParasitemiaCore.Config.Config) : DocumentData =
-    use file = ZipFile.Open(filePath, ZipArchiveMode.Read)
+    use file = ZipFile.Open (filePath, ZipArchiveMode.Read)
+
+    let mainEntry = file.GetEntry (MAIN_ENTRY_NAME)
+    use mainEntryReader = new StreamReader (mainEntry.Open ())
+    let info = JsonConvert.DeserializeObject<JSONInformation> (mainEntryReader.ReadToEnd ())
 
-    let mainEntry = file.GetEntry(mainEntryName)
-    use mainEntryReader = new StreamReader(mainEntry.Open())
-    let info = JsonConvert.DeserializeObject<JSONInformation>(mainEntryReader.ReadToEnd())
+    if info.fileVersion > CURRENT_FILE_VERSION then
+        raise <| VersionFileNewerException info.fileVersion
 
-    updateDocumentData info.fileVersion currentFileVersion
+    updateDocumentData info.fileVersion CURRENT_FILE_VERSION
         {
             patientID = info.patientID
             images =
                 [
-                    let mutable imgNum = 0
                     for imgEntry in file.Entries do
-                        if imgEntry.Name.EndsWith(imageExtension) then
-                            use bitmap = new System.Drawing.Bitmap(imgEntry.Open(), false)
-                            let img = new Image<Bgr, byte>(bitmap)
-                            imgNum <- imgNum + 1
-                            let imgJSONEntry = file.GetEntry(imgEntry.Name + ".json")
-                            use imgJSONFileReader = new StreamReader(imgJSONEntry.Open())
-                            let imgInfo = JsonConvert.DeserializeObject<JSONSourceImage>(imgJSONFileReader.ReadToEnd())
-
-                            let config = defaultConfig.Copy()
+                        if imgEntry.Name.EndsWith JSON_EXTENSION |> not then
+                            use bitmap = new System.Drawing.Bitmap (imgEntry.Open (), false)
+                            let img = bitmap.ToImage<Bgr, byte> ()
+                            let imgJSONEntry = file.GetEntry (imgEntry.Name + JSON_EXTENSION)
+                            use imgJSONFileReader = new StreamReader (imgJSONEntry.Open ())
+                            let imgInfo = JsonConvert.DeserializeObject<JSONSourceImage> (imgJSONFileReader.ReadToEnd ())
+                            let imgNum = imgInfo.num
+
+                            let config = defaultConfig.Copy ()
                             config.Parameters <-
                                 {
                                     ParasitemiaCore.Config.defaultParameters with
@@ -132,16 +147,8 @@ let load (filePath : string) (defaultConfig : ParasitemiaCore.Config.Config) : D
                                 }
 
                             config.SetRBCRadius imgInfo.RBCRadius
-                            yield
-                                {
-                                    num = imgNum
-                                    name = imgInfo.name
-                                    config = config
-                                    dateLastAnalysis = imgInfo.dateLastAnalysis
-                                    img = img
-                                    rbcs = imgInfo.rbcs
-                                    healthyRBCBrightness = imgInfo.healthyRBCBrightness
-                                    infectedRBCBrightness = imgInfo.infectedRBCBrightness
-                                }
+
+                            SourceImage (imgNum, imgInfo.name, imgEntry.Name, config, imgInfo.dateLastAnalysis, FromMemory img, imgInfo.rbcs, HealthyRBCBrightness = imgInfo.healthyRBCBrightness, InfectedRBCBrightness = imgInfo.infectedRBCBrightness)
                 ]
+                |> List.sortBy (fun image -> image.Num)
         }
\ No newline at end of file