diff options
| author | 2026-11-08 04:19:33 +0000 | |
|---|---|---|
| committer | 2026-11-08 04:22:48 +0000 | |
| commit | a4aafb5caea268dae350bdaa6a9c53b65b00910e (patch) | |
| tree | b9f0b26d9c835963e7bb65ddc31ec4b49976d7d7 | |
| download | lab-03-a4aafb5caea268dae350bdaa6a9c53b65b00910e.tar.gz | |
| -rw-r--r-- | .gitignore | 5 | ||||
| -rw-r--r-- | README.org | 33 | ||||
| -rw-r--r-- | UNLICENSE | 24 | ||||
| -rw-r--r-- | app/Main.hs | 112 | ||||
| -rw-r--r-- | doc/biblio.bib | 13 | ||||
| -rw-r--r-- | doc/gost/gost-7-32-bibliography.sty | 57 | ||||
| -rw-r--r-- | doc/gost/gost-7-32-captions.sty | 28 | ||||
| -rw-r--r-- | doc/gost/gost-7-32-counters.sty | 44 | ||||
| -rw-r--r-- | doc/gost/gost-7-32-headings.sty | 106 | ||||
| -rw-r--r-- | doc/gost/gost-7-32-lists.sty | 17 | ||||
| -rw-r--r-- | doc/gost/gost-7-32-tables.sty | 29 | ||||
| -rw-r--r-- | doc/gost/gost-7-32-toc.sty | 34 | ||||
| -rw-r--r-- | doc/gost/gost-7-32.cls | 63 | ||||
| -rw-r--r-- | doc/ox-init.el | 30 | ||||
| -rw-r--r-- | doc/report.org | 352 | ||||
| -rw-r--r-- | doc/setup.org | 24 | ||||
| -rw-r--r-- | doc/spbstu-report.cls | 74 | ||||
| -rw-r--r-- | doc/task.org | 32 | ||||
| -rw-r--r-- | src/Lib.hs | 115 |
19 files changed, 1192 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f8778d5 --- /dev/null +++ b/.gitignore | |||
| @@ -0,0 +1,5 @@ | |||
| 1 | *.html | ||
| 2 | |||
| 3 | *.tex | ||
| 4 | .stack-work/ | ||
| 5 | *~ | ||
diff --git a/README.org b/README.org new file mode 100644 index 0000000..a7b5819 --- /dev/null +++ b/README.org | |||
| @@ -0,0 +1,33 @@ | |||
| 1 | #+title: File processing in Haskell | ||
| 2 | #+subtitle: Steganography | ||
| 3 | #+date: 2024H2 | ||
| 4 | |||
| 5 | * Task | ||
| 6 | :PROPERTIES: | ||
| 7 | :CUSTOM_ID: task | ||
| 8 | :END: | ||
| 9 | Create a project in stack. Write all pure functions to the library | ||
| 10 | =Lib.hs= and restrict access to auxiliary functions. Use do notation to | ||
| 11 | work with external files. Find a portrait of Pauli Wolfgang. Convert | ||
| 12 | the image to the =.bmp= format (24‑bit). Save to a file in the =.txt= | ||
| 13 | format: a fragment of his biography (at least 1000 characters without | ||
| 14 | spaces; the text should not end in the middle of a word or sentence). | ||
| 15 | Encode the text into an image using the Caesar cipher (the shift is | ||
| 16 | specified by the user). The key to the cipher is written in the file | ||
| 17 | name. Write a function that decodes the text from the image using the | ||
| 18 | key from the file name and saves the result to a separate text file. | ||
| 19 | Create functions that encrypt the text in the last bit of each byte, | ||
| 20 | the last two bits of each byte, …, all the bits in a byte. Provide | ||
| 21 | examples of image distortions in the report. | ||
| 22 | |||
| 23 | * Documentation | ||
| 24 | :PROPERTIES: | ||
| 25 | :CUSTOM_ID: documentation | ||
| 26 | :END: | ||
| 27 | The exported report can be found at [[https://git.michalec.dev/files/uni/term-05/func-prog/lab-03/report.pdf][this link]]. | ||
| 28 | |||
| 29 | * Unlicense | ||
| 30 | :PROPERTIES: | ||
| 31 | :CUSTOM_ID: unlicense | ||
| 32 | :END: | ||
| 33 | #+include: UNLICENSE verse | ||
diff --git a/UNLICENSE b/UNLICENSE new file mode 100644 index 0000000..efb9808 --- /dev/null +++ b/UNLICENSE | |||
| @@ -0,0 +1,24 @@ | |||
| 1 | This is free and unencumbered software released into the public domain. | ||
| 2 | |||
| 3 | Anyone is free to copy, modify, publish, use, compile, sell, or | ||
| 4 | distribute this software, either in source code form or as a compiled | ||
| 5 | binary, for any purpose, commercial or non-commercial, and by any | ||
| 6 | means. | ||
| 7 | |||
| 8 | In jurisdictions that recognize copyright laws, the author or authors | ||
| 9 | of this software dedicate any and all copyright interest in the | ||
| 10 | software to the public domain. We make this dedication for the benefit | ||
| 11 | of the public at large and to the detriment of our heirs and | ||
| 12 | successors. We intend this dedication to be an overt act of | ||
| 13 | relinquishment in perpetuity of all present and future rights to this | ||
| 14 | software under copyright law. | ||
| 15 | |||
| 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | ||
| 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
| 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | ||
| 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR | ||
| 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, | ||
| 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | ||
| 22 | OTHER DEALINGS IN THE SOFTWARE. | ||
| 23 | |||
| 24 | For more information, please refer to <https://unlicense.org/> | ||
diff --git a/app/Main.hs b/app/Main.hs new file mode 100644 index 0000000..9b2267a --- /dev/null +++ b/app/Main.hs | |||
| @@ -0,0 +1,112 @@ | |||
| 1 | module Main | ||
| 2 | ( main | ||
| 3 | ) where | ||
| 4 | |||
| 5 | import Codec.Picture | ||
| 6 | import qualified Data.Vector.Unboxed as VU | ||
| 7 | import Lib | ||
| 8 | import Shell.Utility.Log (info, notice) | ||
| 9 | import Shell.Utility.Verbosity | ||
| 10 | import System.Environment (getArgs, getProgName) | ||
| 11 | import System.Exit (die) | ||
| 12 | import System.IO () | ||
| 13 | import Text.Read (readMaybe) | ||
| 14 | |||
| 15 | run :: Int -> Int -> Verbosity -> IO () | ||
| 16 | run caesarShift bitsPerByte verbosity = do | ||
| 17 | let sourceTextPath = "./res/biblio.txt" | ||
| 18 | let sourceImagePath = "./res/img.bmp" | ||
| 19 | let encryptedTextPath = | ||
| 20 | "./tmp/biblio-" ++ show caesarShift ++ ".txt" | ||
| 21 | let encodedImagePath = | ||
| 22 | "./tmp/img-" ++ show bitsPerByte ++ "-" ++ show caesarShift ++ ".bmp" | ||
| 23 | let decodedTextPath = "./tmp/biblio.txt" | ||
| 24 | notice verbosity $ "Reading text from file `" ++ sourceTextPath ++ "'...\n" | ||
| 25 | inputText <- readFile sourceTextPath | ||
| 26 | info verbosity $ | ||
| 27 | "Text sample (10 symbols): \"" ++ take 10 inputText ++ "\"\n" | ||
| 28 | notice verbosity $ "Encrypting text...\n" | ||
| 29 | let encryptedText = encryptCaesar caesarShift inputText | ||
| 30 | info verbosity $ | ||
| 31 | "Encrypted text sample (10 symbols): \"" ++ take 10 encryptedText ++ "\"\n" | ||
| 32 | notice verbosity $ | ||
| 33 | "Writing encrypted text to file `" ++ encryptedTextPath ++ "'...\n" | ||
| 34 | writeFile encryptedTextPath encryptedText | ||
| 35 | notice verbosity $ "Text saved to `" ++ encryptedTextPath ++ "'\n" | ||
| 36 | notice verbosity $ "Converting text to bits...\n" | ||
| 37 | let encryptedTextBits = textToBits encryptedText | ||
| 38 | info verbosity $ | ||
| 39 | "Encrypted data sample (10 bits): " ++ | ||
| 40 | show (take 10 $ VU.toList encryptedTextBits) ++ "\n" | ||
| 41 | notice verbosity $ "Encoding encrypted data into image...\n" | ||
| 42 | notice verbosity $ "Reading image from file `" ++ sourceImagePath ++ "'...\n" | ||
| 43 | readSourceImageResult <- readImage sourceImagePath | ||
| 44 | case readSourceImageResult of | ||
| 45 | Left err -> error $ "Error reading image: " ++ err | ||
| 46 | Right dynImg -> do | ||
| 47 | let img = convertRGB8 dynImg | ||
| 48 | let width = imageWidth img | ||
| 49 | let height = imageHeight img | ||
| 50 | let totalBits = width * height * 3 * bitsPerByte | ||
| 51 | let bits = | ||
| 52 | encryptedTextBits VU.++ | ||
| 53 | VU.replicate (totalBits - VU.length encryptedTextBits) 0 | ||
| 54 | let resultImage = | ||
| 55 | generateImage (encodePixel bitsPerByte img bits) width height | ||
| 56 | notice verbosity $ | ||
| 57 | "Writing image to file `" ++ encodedImagePath ++ "'...\n" | ||
| 58 | saveBmpImage encodedImagePath (ImageRGB8 resultImage) | ||
| 59 | notice verbosity $ "Image saved to `" ++ encodedImagePath ++ "'\n" | ||
| 60 | notice verbosity $ "Decoding data from image...\n" | ||
| 61 | case extractShift encodedImagePath of | ||
| 62 | Just extractedCaesarShift -> do | ||
| 63 | info verbosity $ | ||
| 64 | "Cipher key extracted from file name: " ++ | ||
| 65 | show extractedCaesarShift ++ "\n" | ||
| 66 | notice verbosity $ | ||
| 67 | "Reading image from file `" ++ encodedImagePath ++ "'...\n" | ||
| 68 | readEncodedImageResult <- readImage encodedImagePath | ||
| 69 | case readEncodedImageResult of | ||
| 70 | Left err -> error $ "Error reading image: " ++ err | ||
| 71 | Right dynImg -> do | ||
| 72 | let img = convertRGB8 dynImg | ||
| 73 | let bits = VU.fromList $ extractBitsFromImage bitsPerByte img | ||
| 74 | info verbosity $ | ||
| 75 | "Data sample (10 bits): " ++ show (take 10 $ VU.toList bits) ++ "\n" | ||
| 76 | notice verbosity $ "Converting text to bits...\n" | ||
| 77 | let encryptedTextFromImage = takeWhile (/= '\NUL') (bitsToText bits) | ||
| 78 | info verbosity $ | ||
| 79 | "Decoded text sample (10 symbols): \"" ++ | ||
| 80 | take 10 encryptedTextFromImage ++ "\"\n" | ||
| 81 | notice verbosity $ "Decrypting text...\n" | ||
| 82 | let decryptedText = | ||
| 83 | decryptCaesar extractedCaesarShift encryptedTextFromImage | ||
| 84 | info verbosity $ | ||
| 85 | "Decrypted text sample (10 symbols): \"" ++ | ||
| 86 | take 10 decryptedText ++ "\"\n" | ||
| 87 | notice verbosity $ | ||
| 88 | "Writing decrypted text to file `" ++ decodedTextPath ++ "'...\n" | ||
| 89 | writeFile decodedTextPath decryptedText | ||
| 90 | notice verbosity $ "Text saved to `" ++ decodedTextPath ++ "'\n" | ||
| 91 | Nothing -> error "Unable to extract cipher key from image filename!" | ||
| 92 | |||
| 93 | main :: IO () | ||
| 94 | main = do | ||
| 95 | args <- getArgs | ||
| 96 | case args of | ||
| 97 | (arg1:arg2:_) -> do | ||
| 98 | let shift = | ||
| 99 | case readMaybe arg1 :: Maybe Int of | ||
| 100 | Just i -> i | ||
| 101 | Nothing -> error "First argument (SHIFT) is not an integer!" | ||
| 102 | let bits = | ||
| 103 | case readMaybe arg2 :: Maybe Int of | ||
| 104 | Just i | ||
| 105 | | 1 <= i && i <= 8 -> i | ||
| 106 | | otherwise -> | ||
| 107 | error "Second argument (BITS) is out of range [1, 8]!" | ||
| 108 | Nothing -> error "Second argument (BITS) is not an integer!" | ||
| 109 | run shift bits verbose | ||
| 110 | _ -> do | ||
| 111 | arg0 <- getProgName | ||
| 112 | die $ "Usage: " ++ arg0 ++ " SHIFT BITS" | ||
diff --git a/doc/biblio.bib b/doc/biblio.bib new file mode 100644 index 0000000..bfdf8b3 --- /dev/null +++ b/doc/biblio.bib | |||
| @@ -0,0 +1,13 @@ | |||
| 1 | @article{LucianoPrichett1987, | ||
| 2 | author = {Luciano, D. and Prichett, G.}, | ||
| 3 | title = {Cryptology: From Caesar Ciphers to Public-Key Cryptosystems}, | ||
| 4 | location = {The College Mathematics Journal}, | ||
| 5 | year = 1987, | ||
| 6 | urldate = {2014-11-23} | ||
| 7 | } | ||
| 8 | |||
| 9 | @online{JuicyPixels, | ||
| 10 | title = {Hackage -- JuicyPixels: Picture loading/serialization}, | ||
| 11 | url = {https://hackage.haskell.org/package/JuicyPixels}, | ||
| 12 | urldate = {2014-11-23} | ||
| 13 | } | ||
diff --git a/doc/gost/gost-7-32-bibliography.sty b/doc/gost/gost-7-32-bibliography.sty new file mode 100644 index 0000000..dca60fa --- /dev/null +++ b/doc/gost/gost-7-32-bibliography.sty | |||
| @@ -0,0 +1,57 @@ | |||
| 1 | \ProvidesPackage{gost-7-32-bibliography}[2022/01/28 GOST 7.32-2017] | ||
| 2 | |||
| 3 | \def\UrlBreaks{\do\/\do-} | ||
| 4 | \RequirePackage{url} | ||
| 5 | |||
| 6 | \newdimen\bibindent | ||
| 7 | \renewenvironment{thebibliography}[1]{ | ||
| 8 | \chapter*{\bibname}\addcontentsline{toc}{chapter}{\bibname}% | ||
| 9 | \list{\@biblabel{\@arabic\c@enumiv}}% | ||
| 10 | {\settowidth\labelwidth{\@biblabel{#1}}% | ||
| 11 | \leftmargin\labelwidth | ||
| 12 | \advance\leftmargin\labelsep | ||
| 13 | \@openbib@code | ||
| 14 | \usecounter{enumiv}% | ||
| 15 | \let\p@enumiv\@empty | ||
| 16 | \renewcommand\theenumiv{\@arabic\c@enumiv}}% | ||
| 17 | \sloppy\clubpenalty4000\widowpenalty4000% | ||
| 18 | \sfcode`\.\@m | ||
| 19 | }{ | ||
| 20 | \setcounter{totalbib}{\c@enumiv}% | ||
| 21 | \def\@noitemerr | ||
| 22 | {\@latex@warning{Empty `thebibliography' environment}}% | ||
| 23 | \endlist | ||
| 24 | } | ||
| 25 | \renewcommand\@biblabel{}% | ||
| 26 | \setlength\bibindent{1.5em} | ||
| 27 | |||
| 28 | % Точки после номеров в библиографии. Несовместимо с natbib! -- Коротков И. | ||
| 29 | %\makeatletter | ||
| 30 | \renewcommand*{\@biblabel}[1]{\hfill#1.} | ||
| 31 | |||
| 32 | |||
| 33 | % | ||
| 34 | % Remove References header completely | ||
| 35 | % Stolen from original article.cls | ||
| 36 | % | ||
| 37 | \makeatletter | ||
| 38 | \renewenvironment{thebibliography}[1]{% | ||
| 39 | % \usection{\refname}% | ||
| 40 | % \@mkboth{\MakeUppercase\refname}{\MakeUppercase\refname}% | ||
| 41 | \list{\@biblabel{\@arabic\c@enumiv}}% | ||
| 42 | {\settowidth\labelwidth{\@biblabel{#1}}% | ||
| 43 | \leftmargin\labelwidth | ||
| 44 | \advance\leftmargin\labelsep | ||
| 45 | \@openbib@code | ||
| 46 | \usecounter{enumiv}% | ||
| 47 | \let\p@enumiv\@empty | ||
| 48 | \renewcommand\theenumiv{\@arabic\c@enumiv}}% | ||
| 49 | \sloppy | ||
| 50 | \clubpenalty4000 | ||
| 51 | \@clubpenalty \clubpenalty | ||
| 52 | \widowpenalty4000% | ||
| 53 | \sfcode`\.\@m} | ||
| 54 | {\def\@noitemerr | ||
| 55 | {\@latex@warning{Empty `thebibliography' environment}}% | ||
| 56 | \endlist} | ||
| 57 | \makeatother | ||
diff --git a/doc/gost/gost-7-32-captions.sty b/doc/gost/gost-7-32-captions.sty new file mode 100644 index 0000000..3720026 --- /dev/null +++ b/doc/gost/gost-7-32-captions.sty | |||
| @@ -0,0 +1,28 @@ | |||
| 1 | \ProvidesPackage{gost-7-32-captions}[2022/01/28 GOST 7.32-2017] | ||
| 2 | |||
| 3 | \RequirePackage{caption} | ||
| 4 | \RequirePackage{subcaption} | ||
| 5 | |||
| 6 | % | ||
| 7 | % Table caption aligned to the left with dash as a separator | ||
| 8 | % | ||
| 9 | \captionsetup[table]{labelsep=endash, justification=centering, singlelinecheck=off} | ||
| 10 | |||
| 11 | % | ||
| 12 | % Dash as separator in figure caption and centering | ||
| 13 | % | ||
| 14 | \captionsetup[figure]{labelsep=endash, justification=centering} | ||
| 15 | \addto\captionsrussian{\renewcommand{\figurename}{Рис.}} | ||
| 16 | |||
| 17 | % | ||
| 18 | % Listing caption | ||
| 19 | % | ||
| 20 | \captionsetup[listing]{labelsep=endash, skip=-0.5em, singlelinecheck=off, position=above} | ||
| 21 | \addto\captionsrussian{\captionsetup[listing]{name=Рис.}} | ||
| 22 | \makeatletter | ||
| 23 | \AtBeginDocument{% | ||
| 24 | \let\c@figure\c@listing | ||
| 25 | \let\thefigure\thelisting | ||
| 26 | \let\ftype@listing\ftype@figure | ||
| 27 | } | ||
| 28 | \makeatother | ||
diff --git a/doc/gost/gost-7-32-counters.sty b/doc/gost/gost-7-32-counters.sty new file mode 100644 index 0000000..ee95480 --- /dev/null +++ b/doc/gost/gost-7-32-counters.sty | |||
| @@ -0,0 +1,44 @@ | |||
| 1 | \ProvidesPackage{gost-7-32-counters}[2022/01/29 GOST 7.32-2017] | ||
| 2 | |||
| 3 | % | ||
| 4 | % Values for capital russian letters counter | ||
| 5 | % | ||
| 6 | \makeatletter | ||
| 7 | \newcommand\AlphRus[1]{% | ||
| 8 | \expandafter \@AlphRus \csname c@#1\endcsname | ||
| 9 | } | ||
| 10 | |||
| 11 | \newcommand\@AlphRus[1]{% | ||
| 12 | \ifcase #1% | ||
| 13 | \or А\or Б\or В\or Г\or Д\or Е\or Ж\or И\or К\or | ||
| 14 | Л\or М\or Н\or П\or Р\or С\or Т\or У\or Ф\or | ||
| 15 | Х\or Ц\or Ш\or Щ\or Э\or Ю\or Я% | ||
| 16 | \else \@ctrerr | ||
| 17 | \fi | ||
| 18 | } | ||
| 19 | \makeatother | ||
| 20 | |||
| 21 | % | ||
| 22 | % Values for lowercase russian letters counter | ||
| 23 | % | ||
| 24 | \makeatletter | ||
| 25 | \newcommand\alphRus[1]{% | ||
| 26 | \expandafter \@alphRus \csname c@#1\endcsname | ||
| 27 | } | ||
| 28 | |||
| 29 | \newcommand\@alphRus[1]{% | ||
| 30 | \ifcase #1% | ||
| 31 | \or а\or б\or в\or г\or д\or е\or ж\or и\or к\or | ||
| 32 | л\or м\or н\or п\or р\or с\or т\or у\or ф\or | ||
| 33 | х\or ц\or ш\or щ\or э\or ю\or я% | ||
| 34 | \else \@ctrerr | ||
| 35 | \fi | ||
| 36 | } | ||
| 37 | \makeatother | ||
| 38 | |||
| 39 | % Increment figure counter when using lstlisting | ||
| 40 | % \let\oldlstlisting\lstlisting | ||
| 41 | % \renewcommand{\lstlisting}[1][]{% | ||
| 42 | % \refstepcounter{figure} | ||
| 43 | % \oldlstlisting[#1] | ||
| 44 | % } | ||
diff --git a/doc/gost/gost-7-32-headings.sty b/doc/gost/gost-7-32-headings.sty new file mode 100644 index 0000000..033f4a8 --- /dev/null +++ b/doc/gost/gost-7-32-headings.sty | |||
| @@ -0,0 +1,106 @@ | |||
| 1 | \ProvidesPackage{gost-7-32-headings}[2022/01/28 GOST 7.32-2017] | ||
| 2 | |||
| 3 | \RequirePackage{titlesec} | ||
| 4 | \RequirePackage{titling} | ||
| 5 | \RequirePackage{setspace} | ||
| 6 | |||
| 7 | \RequirePackage{gost-7-32-counters} | ||
| 8 | |||
| 9 | % | ||
| 10 | % Set custom formatting to well-known LaTeX commands: section, subsection and subsubsection | ||
| 11 | % | ||
| 12 | \titleformat{\section}[block]{\centering\large\setstretch{1}\bfseries}{\thesection}{0.5em}{} | ||
| 13 | \titlespacing*{\section}{0cm}{0cm}{0.5cm} | ||
| 14 | \newcommand{\sectionbreak}{\clearpage} | ||
| 15 | |||
| 16 | \titleformat{\subsection}[block]{\normalsize\bfseries}{\thesubsection}{0.5em}{} | ||
| 17 | \titlespacing{\subsection}{0cm}{0.5cm}{0.5cm} | ||
| 18 | |||
| 19 | \titleformat{\subsubsection}[runin]{\normalsize\bfseries}{\thesubsubsection}{0.5em}{}[\newline\indent] | ||
| 20 | \titlespacing{\subsubsection}{1.25cm}{0.5em}{0cm} | ||
| 21 | |||
| 22 | \makeatletter | ||
| 23 | \let\oldsection\section | ||
| 24 | \newcommand{\@sectionnostar}[1]{\phantomsection\oldsection*{#1}\addcontentsline{toc}{section}{#1}} | ||
| 25 | \newcommand{\@sectionstar}[1]{\oldsection{#1}} | ||
| 26 | \renewcommand{\section}{\sectionbreak\@ifstar{\@sectionnostar}{\@sectionstar}} | ||
| 27 | \makeatother | ||
| 28 | |||
| 29 | % | ||
| 30 | % Make special headings, that have their own formatting rules: | ||
| 31 | % - centered | ||
| 32 | % - all-caps | ||
| 33 | % - bold | ||
| 34 | % | ||
| 35 | % Only three of them must appear in TOC: introduction, conclusion and references | ||
| 36 | % | ||
| 37 | \newcommand{\introduction}{ | ||
| 38 | \addcontentsline{toc}{section}{ВВЕДЕНИЕ} | ||
| 39 | \begin{center} | ||
| 40 | \bfseries\large | ||
| 41 | ВВЕДЕНИЕ | ||
| 42 | \end{center} | ||
| 43 | } | ||
| 44 | |||
| 45 | \newcommand{\conclusion}{ | ||
| 46 | \addcontentsline{toc}{section}{ЗАКЛЮЧЕНИЕ} | ||
| 47 | \begin{center} | ||
| 48 | \bfseries\large | ||
| 49 | ЗАКЛЮЧЕНИЕ | ||
| 50 | \end{center} | ||
| 51 | } | ||
| 52 | |||
| 53 | \newcommand{\references}{ | ||
| 54 | \addcontentsline{toc}{section}{СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ} | ||
| 55 | \begin{center} | ||
| 56 | \bfseries\large | ||
| 57 | СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ | ||
| 58 | \end{center} | ||
| 59 | } | ||
| 60 | |||
| 61 | \newcommand{\essay}{ | ||
| 62 | \begin{center} | ||
| 63 | \bfseries\large | ||
| 64 | РЕФЕРАТ | ||
| 65 | \end{center} | ||
| 66 | } | ||
| 67 | |||
| 68 | \newcommand{\definitions}{ | ||
| 69 | \begin{center} | ||
| 70 | \bfseries\large | ||
| 71 | ОПРЕДЕЛЕНИЯ | ||
| 72 | \end{center} | ||
| 73 | } | ||
| 74 | |||
| 75 | \newcommand{\abbreviations}{ | ||
| 76 | \begin{center} | ||
| 77 | \bfseries\large | ||
| 78 | ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ | ||
| 79 | \end{center} | ||
| 80 | } | ||
| 81 | |||
| 82 | \newcommand{\defsabbrs}{ | ||
| 83 | \begin{center} | ||
| 84 | \bfseries\large | ||
| 85 | ОПРЕДЕЛЕНИЯ, ОБОЗНАЧЕНИЯ И СОКРАЩЕНИЯ | ||
| 86 | \end{center} | ||
| 87 | } | ||
| 88 | |||
| 89 | % | ||
| 90 | % Appendices headings. Appendices have autoincrementing number, | ||
| 91 | % that is represented with russian letter. | ||
| 92 | % This heading must appear in TOC | ||
| 93 | % | ||
| 94 | \newcounter{appendixcnt} | ||
| 95 | \setcounter{appendixcnt}{1} | ||
| 96 | |||
| 97 | \renewcommand{\appendix}[1]{ | ||
| 98 | \addcontentsline{toc}{section}{ПРИЛОЖЕНИЕ \AlphRus{appendixcnt}. #1} | ||
| 99 | \begin{center} | ||
| 100 | \bfseries\large | ||
| 101 | ПРИЛОЖЕНИЕ \AlphRus{appendixcnt} | ||
| 102 | |||
| 103 | #1 | ||
| 104 | \end{center} | ||
| 105 | \stepcounter{appendixcnt} | ||
| 106 | } | ||
diff --git a/doc/gost/gost-7-32-lists.sty b/doc/gost/gost-7-32-lists.sty new file mode 100644 index 0000000..6f41980 --- /dev/null +++ b/doc/gost/gost-7-32-lists.sty | |||
| @@ -0,0 +1,17 @@ | |||
| 1 | \ProvidesPackage{gost-7-32-lists}[2022/01/28 GOST 7.32-2017] | ||
| 2 | |||
| 3 | \RequirePackage{enumitem} | ||
| 4 | \RequirePackage{gost-7-32-counters} | ||
| 5 | |||
| 6 | \AddEnumerateCounter*{\alphRus}{\c@alphRus}{1} | ||
| 7 | |||
| 8 | \setlist{nosep} | ||
| 9 | \setlist[itemize, 1]{label=\textendash} | ||
| 10 | \setlist[itemize, 2]{label=\bullet} | ||
| 11 | \setlist[itemize, 3]{label=\bullet} | ||
| 12 | |||
| 13 | \setlist[enumerate, 2]{label=\alphRus*)} | ||
| 14 | |||
| 15 | \setlist[1]{wide=\parindent} | ||
| 16 | \setlist[2]{wide=2\parindent, leftmargin=\parindent} | ||
| 17 | \setlist[3]{wide=2\parindent} | ||
diff --git a/doc/gost/gost-7-32-tables.sty b/doc/gost/gost-7-32-tables.sty new file mode 100644 index 0000000..750ab75 --- /dev/null +++ b/doc/gost/gost-7-32-tables.sty | |||
| @@ -0,0 +1,29 @@ | |||
| 1 | \ProvidesPackage{gost-7-32-tables}[2022/01/28 GOST 7.32-2017] | ||
| 2 | |||
| 3 | \RequirePackage{tabularx} | ||
| 4 | |||
| 5 | % | ||
| 6 | % Center-aligned column with automatic width | ||
| 7 | % | ||
| 8 | \newcolumntype{Y}{>{\centering\arraybackslash}X} | ||
| 9 | |||
| 10 | % | ||
| 11 | % Right-aligned column with automatic width | ||
| 12 | % | ||
| 13 | \newcolumntype{Z}{>{\raggedleft\arraybackslash}X} | ||
| 14 | |||
| 15 | % | ||
| 16 | % Table with designations | ||
| 17 | % | ||
| 18 | \newenvironment{designations}{ | ||
| 19 | \noindent | ||
| 20 | \tabularx{\textwidth}{@{} | ||
| 21 | >{\raggedright \arraybackslash \hsize=0.25\hsize}X | ||
| 22 | >{\centering \arraybackslash \hsize=0.05\hsize}X | ||
| 23 | >{\arraybackslash \hsize=0.70\hsize}X | ||
| 24 | } | ||
| 25 | }{ | ||
| 26 | \endtabularx | ||
| 27 | } | ||
| 28 | |||
| 29 | \newcommand{\designation}[2]{#1 &---& #2. \\} | ||
diff --git a/doc/gost/gost-7-32-toc.sty b/doc/gost/gost-7-32-toc.sty new file mode 100644 index 0000000..328079d --- /dev/null +++ b/doc/gost/gost-7-32-toc.sty | |||
| @@ -0,0 +1,34 @@ | |||
| 1 | \ProvidesPackage{gost-7-32-toc}[2022/01/28 GOST 7.32-2017] | ||
| 2 | |||
| 3 | \RequirePackage{tocloft} | ||
| 4 | \RequirePackage[ | ||
| 5 | bookmarks=true, | ||
| 6 | colorlinks=true, | ||
| 7 | unicode=true, | ||
| 8 | urlcolor=black, | ||
| 9 | linkcolor=black, | ||
| 10 | anchorcolor=black, | ||
| 11 | citecolor=black, | ||
| 12 | menucolor=black, | ||
| 13 | filecolor=black, | ||
| 14 | hidelinks | ||
| 15 | ]{hyperref} | ||
| 16 | |||
| 17 | % | ||
| 18 | % Set custom font styles | ||
| 19 | % | ||
| 20 | \renewcommand{\cftsecfont}{\normalfont} | ||
| 21 | \renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}} | ||
| 22 | \renewcommand{\cftsecpagefont}{\normalsize} | ||
| 23 | \renewcommand{\cftaftertoctitle}{\hfill\hfill} | ||
| 24 | \renewcommand{\cfttoctitlefont}{\hfill\normalfont\large\bfseries} | ||
| 25 | \titleformat{\tableofcontents}[block]{\centering\large\bfseries}{\thesection}{0.5em}{} | ||
| 26 | \titlespacing{\tableofcontents}{0cm}{0cm}{1cm} | ||
| 27 | |||
| 28 | % | ||
| 29 | % Set indents and line spacing | ||
| 30 | % | ||
| 31 | \setlength{\cftbeforesecskip}{0cm} | ||
| 32 | \setlength{\cftbeforesubsecskip}{0cm} | ||
| 33 | \setlength{\cftbeforesubsubsecskip}{0cm} | ||
| 34 | \setlength{\cftbeforeparaskip}{0cm} | ||
diff --git a/doc/gost/gost-7-32.cls b/doc/gost/gost-7-32.cls new file mode 100644 index 0000000..5cfca06 --- /dev/null +++ b/doc/gost/gost-7-32.cls | |||
| @@ -0,0 +1,63 @@ | |||
| 1 | % https://github.com/weterans/gost | ||
| 2 | \NeedsTeXFormat{LaTeX2e} | ||
| 3 | \ProvidesClass{gost-7-32}[2022/01/28 GOST 7.32-2017] | ||
| 4 | |||
| 5 | % | ||
| 6 | % Supported font sizes: 12pt, 14pt | ||
| 7 | % | ||
| 8 | \DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} | ||
| 9 | \DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} | ||
| 10 | |||
| 11 | \ProcessOptions\relax | ||
| 12 | |||
| 13 | % | ||
| 14 | % Set A4 paper format | ||
| 15 | % | ||
| 16 | \LoadClass[a4paper]{extarticle} | ||
| 17 | |||
| 18 | % | ||
| 19 | % Use 1.5 line spacing | ||
| 20 | % | ||
| 21 | \RequirePackage{setspace} | ||
| 22 | \spacing{1.5} | ||
| 23 | |||
| 24 | % | ||
| 25 | % First paragraph indentation | ||
| 26 | % | ||
| 27 | \RequirePackage{indentfirst} | ||
| 28 | \setlength{\parindent}{12.5mm} | ||
| 29 | |||
| 30 | % | ||
| 31 | % Page margin | ||
| 32 | % | ||
| 33 | \RequirePackage[ | ||
| 34 | left=2.5cm, | ||
| 35 | right=2cm, | ||
| 36 | top=2cm, | ||
| 37 | bottom=2cm, | ||
| 38 | footskip=1cm, | ||
| 39 | ]{geometry} | ||
| 40 | |||
| 41 | % | ||
| 42 | % Use TMR-like font | ||
| 43 | % | ||
| 44 | \RequirePackage{fontspec} | ||
| 45 | \RequirePackage{xunicode} | ||
| 46 | \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text} | ||
| 47 | \setmainfont{Times New Roman} | ||
| 48 | |||
| 49 | % | ||
| 50 | % Use russian language | ||
| 51 | % | ||
| 52 | \RequirePackage[main=russian, english]{babel} | ||
| 53 | \babelhyphenation[russian]{} | ||
| 54 | |||
| 55 | % | ||
| 56 | % gost-7-32 packages | ||
| 57 | % | ||
| 58 | \RequirePackage{gost-7-32-headings} | ||
| 59 | \RequirePackage{gost-7-32-toc} | ||
| 60 | \RequirePackage{gost-7-32-lists} | ||
| 61 | % \RequirePackage{gost-7-32-bibliography} | ||
| 62 | \RequirePackage{gost-7-32-captions} | ||
| 63 | \RequirePackage{gost-7-32-tables} | ||
diff --git a/doc/ox-init.el b/doc/ox-init.el new file mode 100644 index 0000000..a7cfed5 --- /dev/null +++ b/doc/ox-init.el | |||
| @@ -0,0 +1,30 @@ | |||
| 1 | ;;; ox-init.el --- Initialization script for async org exprort session | ||
| 2 | ;;; Commentary: | ||
| 3 | ;;; Code: | ||
| 4 | (org-babel-do-load-languages | ||
| 5 | 'org-babel-load-languages | ||
| 6 | '((latex . t) | ||
| 7 | (haskell . t))) | ||
| 8 | |||
| 9 | (require 'ox-extra) | ||
| 10 | (ox-extras-activate '(ignore-headlines)) | ||
| 11 | |||
| 12 | (setq org-latex-src-block-backend 'minted) | ||
| 13 | |||
| 14 | (require 'oc-bibtex) | ||
| 15 | (setq org-latex-bib-compiler "biber") | ||
| 16 | |||
| 17 | (setq org-latex-remove-logfiles nil) | ||
| 18 | |||
| 19 | (setq org-latex-caption-above '(table src-block special-block)) | ||
| 20 | |||
| 21 | (setq org-latex-pdf-process '("%latex -shell-escape -interaction nonstopmode -output-directory %o %f" | ||
| 22 | "%bib %b" | ||
| 23 | "%latex -shell-escape -interaction nonstopmode -output-directory %o %f")) | ||
| 24 | (setq org-latex-classes '(("spbstu-report" "\\documentclass[12pt]{spbstu-report}" | ||
| 25 | ("\\section{%s}" . "\\section*{%s}") | ||
| 26 | ("\\subsection{%s}" . "\\subsection*{%s}") | ||
| 27 | ("\\subsubsection{%s}" . "\\subsubsection*{%s}") | ||
| 28 | ("\\paragraph{%s}" . "\\paragraph*{%s}") | ||
| 29 | ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))) | ||
| 30 | ;;; ox-init.el ends here | ||
diff --git a/doc/report.org b/doc/report.org new file mode 100644 index 0000000..fac39e7 --- /dev/null +++ b/doc/report.org | |||
| @@ -0,0 +1,352 @@ | |||
| 1 | #+title: Обработка файлов в Haskell | ||
| 2 | #+author: Михалец М. | ||
| 3 | #+latex_header: \reportof{О ВЫПОЛНЕНИИ ЛАБОРАТОРНОЙ РАБОТЫ №3} | ||
| 4 | #+latex_header: \subject{по дисциплине «Функциональное программирование»} | ||
| 5 | #+latex_header: \university{Федеральное государственное автономное образовательное учреждение высшего образования \enquote{Санкт-Петербургский политехнический университет Петра Великого}} | ||
| 6 | #+latex_header: \institute{Институт компьютерных наук и кибербезопасности} | ||
| 7 | #+latex_header: \school{Высшая школа технологии искусственного интеллекта} | ||
| 8 | #+latex_header: \direction{02.03.01 Математика и компьютерные науки} | ||
| 9 | #+latex_header: \reviewertitle{}\reviewer{Моторин Д.Е.} | ||
| 10 | #+latex_header: \city{Санкт-Петербург} | ||
| 11 | #+date: 2024 | ||
| 12 | |||
| 13 | #+setupfile: setup.org | ||
| 14 | #+latex: \sloppy | ||
| 15 | |||
| 16 | * ВВЕДЕНИЕ | ||
| 17 | :PROPERTIES: | ||
| 18 | :UNNUMBERED: t | ||
| 19 | :END: | ||
| 20 | В данном отчете, описан результат выполнения данного практического | ||
| 21 | задания, в котором необходимо создать проект в stack, закодировать | ||
| 22 | текст биографии предоставленного ученого, в изображение, а затем | ||
| 23 | реализовать декодирование текста из изображения. | ||
| 24 | |||
| 25 | В ходе выполнения практической работы, реализован на языке Haskell --- | ||
| 26 | проект в stack в котором разработана программа кодирует текст в | ||
| 27 | изображение и декодирует текст из изображения. Программа принимает на | ||
| 28 | вход изображение, текстовый файл, кодовое слово, количество желаемых | ||
| 29 | битов кодировки. Декодирование принимает на вход закодированное | ||
| 30 | изображение. | ||
| 31 | |||
| 32 | * Постановка задачи | ||
| 33 | Для выполнения лабораторной работы необходимо было сделать следующее. | ||
| 34 | Создать проект в stack. Все чистые функции записать в библиотеку | ||
| 35 | =Lib.hs= и ограничить доступ к вспомогательным функциям. Использовать | ||
| 36 | do-нотацию для работы с внешними файлами. Найти портрет Паули Вольфганга. | ||
| 37 | Перевести изображение в формат .bmp (24-разрядный). Сохранить в файл | ||
| 38 | формата =.txt= фрагмент биографии (не менее 1000 символов без пробелов, | ||
| 39 | текст не должен обрываться на середине слова или предложения). | ||
| 40 | Закодировать текст в изображение шифром Цезаря (смещение задается | ||
| 41 | пользователем). Ключ к шифру записывается в имя файла. Написать | ||
| 42 | функцию расшифровывающую текст из изображения используя ключ из имени | ||
| 43 | файла и сохраняющую результат в отдельный текстовый файл. Создать | ||
| 44 | функции шифрующие текст в последний бит каждого байта, последние два | ||
| 45 | бита каждого байта, …, все биты в байте. В отчете привести примеры | ||
| 46 | искажений изображения. | ||
| 47 | |||
| 48 | * Математическое описание | ||
| 49 | ** Шифр Цезаря | ||
| 50 | /Шифр Цезаря/ --- разновидность шифра подстановки, в котором каждый | ||
| 51 | символ в открытом тексте заменяется символом, находящимся на некотором | ||
| 52 | постоянном числе позиций левее или правее него в алфавите (так, в | ||
| 53 | шифре со сдвигом вправо на 3, А была бы заменена на Г, Б станет Д, и | ||
| 54 | так далее). Шифр был назван в честь римского полководца Гая Юлия | ||
| 55 | Цезаря, использовавшего его для секретной переписки со своими | ||
| 56 | военачальниками. | ||
| 57 | |||
| 58 | Если сопоставить каждому символу алфавита его порядковый номер (нумеруя с 0), то шифрование и дешифрование можно выразить формулами модульной арифметики [cite:@LucianoPrichett1987]: | ||
| 59 | #+begin_export latex | ||
| 60 | \begin{align*} | ||
| 61 | y &= x + k \mod n \\ | ||
| 62 | x &= y - k \mod n | ||
| 63 | \end{align*} | ||
| 64 | #+end_export | ||
| 65 | где $x$ --- символ открытого текста, $y$ --- символ шифрованного | ||
| 66 | текста, $n$ --- мощность алфавита, $k$ --- ключ. | ||
| 67 | |||
| 68 | * Особенности реализации | ||
| 69 | ** Исходное изображение и текст | ||
| 70 | Для выполнения лабораторной работы необходимо было найти изображение | ||
| 71 | Паули Вольфганга (см. Рис. [[pauli]]). Изображение было переведено из | ||
| 72 | формата =jpeg= в формат =bmp= с помощью программы =convert= пакета | ||
| 73 | =imagemagick=. | ||
| 74 | |||
| 75 | #+name: pauli | ||
| 76 | #+caption: Портрет Паули Вольфганга. | ||
| 77 | #+attr_latex: :width .5\linewidth | ||
| 78 | [[file:res/img.png]] | ||
| 79 | |||
| 80 | Отрывок биографии Паули Вольфганга длиною в 2096 символов без учёта | ||
| 81 | пробелов представлен ниже. | ||
| 82 | |||
| 83 | #+include: "../res/biblio.txt" src text | ||
| 84 | |||
| 85 | ** Кодирование и декодирование текста с помощью шифра Цезаря | ||
| 86 | Код функций для кодирования и декодирования текста с помощью шифра | ||
| 87 | Цезаря представлен на Рис. [[caesar-code]]. Функция ~encryptCaesar~ | ||
| 88 | принимает смещение и сам текст, а возвращает зашифрованный текст. В | ||
| 89 | её коде используется вспомогательная функция ~addWithWrapInRange~. | ||
| 90 | Функция принимает основу, сдвиг, нижний и верхний диапазоны, а | ||
| 91 | возвращает основу увеличенную на сдвиг, сохраняя значение в указанном | ||
| 92 | диапазоне его закручиванием. Для декодирования текста используется | ||
| 93 | функция ~decryptCaesar~, которая, по-сути, является лишь обёрткой над | ||
| 94 | функцией ~encryptCaesar~, так как процесс кодирования осуществляется | ||
| 95 | почти так же как и декодирования. Функция ~decryptCaesar~ принимает на | ||
| 96 | вход смещение и закодированный текст, а возвращает декодированный | ||
| 97 | текст. Алфавит сохраняется в отдельный файл и должен передаваться | ||
| 98 | вместе с зашифрованным текстом, чтобы этот текст можно было | ||
| 99 | дешифровать. | ||
| 100 | |||
| 101 | #+name: caesar-code | ||
| 102 | #+caption: Функции для кодирования и декодирования текста с помощью шифра Цезаря. | ||
| 103 | #+attr_latex: :placement H | ||
| 104 | #+include: "../src/Lib.hs" src haskell :lines "18-33" | ||
| 105 | |||
| 106 | Пример закодированного с помощью шифра Цезаря текста биографии Паули | ||
| 107 | Вольфганга для смещения 5 представлен ниже. | ||
| 108 | |||
| 109 | #+include: "res/biblio-5.txt" src text | ||
| 110 | |||
| 111 | ** Представление текста в виде последовательности бит | ||
| 112 | Код функций для преобразования текста в последовательность бит и | ||
| 113 | обратно представлен на Рис. [[text2bits]]. Функция ~textToBits~ принимает | ||
| 114 | текст в виде строки и возвращает его представление в виде вектора бит. | ||
| 115 | Она использует вспомогательную функцию ~charToBits~, которая преобразует | ||
| 116 | символ в список бит, представляющих его код ASCII в двоичном виде. | ||
| 117 | Для преобразования последовательности бит обратно в текст используется | ||
| 118 | функция ~bitsToText~. Она рекурсивно делит вектор бит на блоки по 8 | ||
| 119 | бит, преобразует каждый блок в символ ASCII и объединяет их в строку. | ||
| 120 | В процессе этого преобразования используется функция ~bitsToInt~, | ||
| 121 | которая преобразует вектор бит в целое число, интерпретируя их как | ||
| 122 | двоичное представление этого числа. | ||
| 123 | |||
| 124 | #+name: text2bits | ||
| 125 | #+caption: Функции для конвертации текста в последовательность бит и обратно. | ||
| 126 | #+attr_latex: :placement H | ||
| 127 | #+include: "../src/Lib.hs" src haskell :lines "34-59" | ||
| 128 | |||
| 129 | ** Работа с файлами | ||
| 130 | Для работы с текстовыми файлами использовались базовые функции | ||
| 131 | Haskell: | ||
| 132 | - ~readFile~ --- читает содержимое файла и возвращает его как строку; | ||
| 133 | - ~writeFile~ --- записывает строку в файл, заменяя его содержимое. | ||
| 134 | |||
| 135 | Для работы с изображениями использовалась библиотека =JuicyPixels= | ||
| 136 | [cite:@JuicyPixels]. С её помощью можно как прочитать изображение в | ||
| 137 | любом популярном формате, так и сохранить его. В частности в работе | ||
| 138 | использовались функции: | ||
| 139 | - ~readImage~ --- для чтения изображения из указанного файла; | ||
| 140 | - ~saveBmpImage~ --- для сохранения изображения в формате bmp. | ||
| 141 | |||
| 142 | ** Сохранение зашифрованных данных в изображении | ||
| 143 | Код функций для создания изображения с закодированными данными | ||
| 144 | представлен на Рис. [[generate-image]]. Функция ~encodePixel~ отвечает за | ||
| 145 | кодирование последовательности бит в определённый пиксель изображения. | ||
| 146 | Она принимает количество бит данных, которое будет сохранено в каждый | ||
| 147 | байт изображения, исходное изображение, вектор бит зашифрованных | ||
| 148 | данных, координаты пикселя $(x, y)$ и возвращает новый пиксель с | ||
| 149 | закодированными данными. Для этого функция вычисляет индекс пикселя в | ||
| 150 | изображении, извлекает соответствующую часть вектора бит данных, | ||
| 151 | преобразует её в целые числа, накладывает битовую маску, которая | ||
| 152 | соответствует количество изменяемых бит в байте, и записывает | ||
| 153 | закодированные данные. Для создания маски используется | ||
| 154 | вспомогательная функция ~createMask~. | ||
| 155 | |||
| 156 | Функция ~encodePixel~ затем используется вместе с функцией ~generateImage~ | ||
| 157 | из библиотеки =JuicyPixels= для генерации нового изображения. | ||
| 158 | |||
| 159 | При сохранении изображения в файл, в его названии сохраняется смещение | ||
| 160 | шифра Цезаря и количество бит в байте, отведённых для хранения | ||
| 161 | зашифрованных данных. Например, название изображения =img-2-5.bmp= | ||
| 162 | означает, что при кодировании использовался код Цезаря со смещением 5, | ||
| 163 | а для хранения закодированных данных в каждом байте изображения | ||
| 164 | использовалось 2 бита. | ||
| 165 | |||
| 166 | #+name: generate-image | ||
| 167 | #+caption: Функции для создания изображения с закодированными данными. | ||
| 168 | #+attr_latex: :placement H | ||
| 169 | #+include: "../src/Lib.hs" src haskell :lines "66-85" | ||
| 170 | |||
| 171 | ** Чтение зашифрованных данных из изображения | ||
| 172 | Код функций для чтения зашифрованных данных из изображения представлен | ||
| 173 | на Рис. [[read-image]]. Функция ~extractBits~ извлекает заданное количество | ||
| 174 | бит из одного байта пикселя. Она принимает число бит на байт и байт | ||
| 175 | пикселя, возвращая список бит. Функция ~extractBitsFromPixel~ | ||
| 176 | предназначена для извлечения бит из всех трёх цветовых каналов $(R, G, | ||
| 177 | B)$ пикселя. Она объединяет списки бит из каждого канала в один общий | ||
| 178 | список. Для извлечения бит из всего изображения используется функция | ||
| 179 | ~extractBitsFromImage~. Она последовательно обрабатывает все пиксели | ||
| 180 | изображения, извлекая биты с помощью ~extractBitsFromPixel~, и | ||
| 181 | объединяет их в общий список. | ||
| 182 | |||
| 183 | Функция ~extractShift~ извлекает смещения для шифра Цезаря из названия файла изображения. | ||
| 184 | |||
| 185 | #+name: read-image | ||
| 186 | #+caption: Функции для чтения зашифрованных данных из изображения. | ||
| 187 | #+attr_latex: :placement H | ||
| 188 | #+include: "../src/Lib.hs" src haskell :lines "86-" | ||
| 189 | |||
| 190 | * Результаты работы программы | ||
| 191 | При успешном завершении программа создаёт три файла: файл изображения | ||
| 192 | с закодированных текстом, текстовый файл с закодированным текстом и | ||
| 193 | текстовый файл с декодированным текстом. | ||
| 194 | |||
| 195 | На Рис. [[result-console]] представлены результаты работы программы в | ||
| 196 | консоли. | ||
| 197 | |||
| 198 | #+name: result-console | ||
| 199 | #+caption: Результаты работы программы в консоли. | ||
| 200 | #+begin_src text | ||
| 201 | $ stack run 5 1 | ||
| 202 | Reading text from file `./res/biblio.txt'... | ||
| 203 | Text sample (10 symbols): "Wolfgang P" | ||
| 204 | Encrypting text... | ||
| 205 | Encrypted text sample (10 symbols): "Btqklfsl U" | ||
| 206 | Converting text to bits... | ||
| 207 | Encrypted data sample (10 bits): [0,1,0,0,0,0,1,0,0,1] | ||
| 208 | Encoding encrypted data into image... | ||
| 209 | Reading image from file `./res/img.bmp'... | ||
| 210 | Writing image to file `./tmp/img-1-5.bmp'... | ||
| 211 | Image saved to `./tmp/img-1-5.bmp' | ||
| 212 | Decoding data from image... | ||
| 213 | Cipher key extracted from file name: 5 | ||
| 214 | Reading image from file `./tmp/img-1-5.bmp'... | ||
| 215 | Data sample (10 bits): [0,1,0,0,0,0,1,0,0,1] | ||
| 216 | Converting text to bits... | ||
| 217 | Decoded text sample (10 symbols): "Btqklfsl U" | ||
| 218 | Decrypting text... | ||
| 219 | Decrypted text sample (10 symbols): "Wolfgang P" | ||
| 220 | Writing decrypted text to file `./tmp/biblio.txt'... | ||
| 221 | Text saved to `./tmp/biblio.txt' | ||
| 222 | #+end_src | ||
| 223 | |||
| 224 | На Рис. [[enc0]]-[[enc8]] представлены результирующие изображения с разным | ||
| 225 | количеством бит, отведённых под зашифрованные данные. | ||
| 226 | |||
| 227 | Дополнительно, чтобы было проще заметить закодированные данные были | ||
| 228 | внесены изменения в функцию ~encodePixel~, которые дают закодированным | ||
| 229 | данным чёрный фон: | ||
| 230 | #+begin_src haskell | ||
| 231 | PixelRGB8 r g b = | ||
| 232 | if startPos < encryptedBits | ||
| 233 | then PixelRGB8 0 0 0 | ||
| 234 | else pixelAt img x y | ||
| 235 | #+end_src | ||
| 236 | |||
| 237 | На Рис. [[ench0]]-[[ench8]] представлены результирующие изображения с разным | ||
| 238 | количеством бит, отведённых под зашифрованные данные с черным фоном | ||
| 239 | закодированных данных. | ||
| 240 | |||
| 241 | #+name: encs | ||
| 242 | #+caption: Изображения с зашифрованными данными в разные количества битов. | ||
| 243 | #+attr_latex: :options [H] | ||
| 244 | #+begin_figure | ||
| 245 | \centering | ||
| 246 | #+name: enc0 | ||
| 247 | #+caption: Исходное изображение. | ||
| 248 | #+attr_latex: :float subfigure :placement [b]{.3\textwidth} :width \textwidth | ||
| 249 | [[file:res/img.png]] | ||
| 250 | #+name: enc1 | ||
| 251 | #+caption: Использован 1 бит. | ||
| 252 | #+attr_latex: :float subfigure :placement [b]{.3\textwidth} :width \textwidth | ||
| 253 | [[file:res/img-1-5.png]] | ||
| 254 | #+name: enc2 | ||
| 255 | #+caption: Использованы 2 бита. | ||
| 256 | #+attr_latex: :float subfigure :placement [b]{.3\textwidth} :width \textwidth | ||
| 257 | [[file:res/img-2-5.png]] | ||
| 258 | |||
| 259 | #+name: enc3 | ||
| 260 | #+caption: Использованы 3 бита. | ||
| 261 | #+attr_latex: :float subfigure :placement [b]{.3\textwidth} :width \textwidth | ||
| 262 | [[file:res/img-3-5.png]] | ||
| 263 | #+name: enc4 | ||
| 264 | #+caption: Использованы 4 бита. | ||
| 265 | #+attr_latex: :float subfigure :placement [b]{.3\textwidth} :width \textwidth | ||
| 266 | [[file:res/img-4-5.png]] | ||
| 267 | #+name: enc5 | ||
| 268 | #+caption: Использовано 5 битов. | ||
| 269 | #+attr_latex: :float subfigure :placement [b]{.3\textwidth} :width \textwidth | ||
| 270 | [[file:res/img-5-5.png]] | ||
| 271 | |||
| 272 | #+name: enc6 | ||
| 273 | #+caption: Использовано 6 битов. | ||
| 274 | #+attr_latex: :float subfigure :placement [b]{.3\textwidth} :width \textwidth | ||
| 275 | [[file:res/img-6-5.png]] | ||
| 276 | #+name: enc7 | ||
| 277 | #+caption: Использовано 7 битов. | ||
| 278 | #+attr_latex: :float subfigure :placement [b]{.3\textwidth} :width \textwidth | ||
| 279 | [[file:res/img-7-5.png]] | ||
| 280 | #+name: enc8 | ||
| 281 | #+caption: Использовано 8 битов. | ||
| 282 | #+attr_latex: :float subfigure :placement [b]{.3\textwidth} :width \textwidth | ||
| 283 | [[file:res/img-8-5.png]] | ||
| 284 | #+end_figure | ||
| 285 | |||
| 286 | #+name: enchs | ||
| 287 | #+caption: Изображения с зашифрованными данными в разные количества битов (с выбеделием зашифрованных данных). | ||
| 288 | #+attr_latex: :options [H] | ||
| 289 | #+begin_figure | ||
| 290 | \centering | ||
| 291 | #+name: ench0 | ||
| 292 | #+caption: Исходное изображение. | ||
| 293 | #+attr_latex: :float subfigure :placement [b]{.3\textwidth} :width \textwidth | ||
| 294 | [[file:res/img.png]] | ||
| 295 | #+name: ench1 | ||
| 296 | #+caption: Использован 1 бит. | ||
| 297 | #+attr_latex: :float subfigure :placement [b]{.3\textwidth} :width \textwidth | ||
| 298 | [[file:res/imgh-1-5.png]] | ||
| 299 | #+name: ench2 | ||
| 300 | #+caption: Использованы 2 бита. | ||
| 301 | #+attr_latex: :float subfigure :placement [b]{.3\textwidth} :width \textwidth | ||
| 302 | [[file:res/imgh-2-5.png]] | ||
| 303 | |||
| 304 | #+name: ench3 | ||
| 305 | #+caption: Использованы 3 бита. | ||
| 306 | #+attr_latex: :float subfigure :placement [b]{.3\textwidth} :width \textwidth | ||
| 307 | [[file:res/imgh-3-5.png]] | ||
| 308 | #+name: ench4 | ||
| 309 | #+caption: Использованы 4 бита. | ||
| 310 | #+attr_latex: :float subfigure :placement [b]{.3\textwidth} :width \textwidth | ||
| 311 | [[file:res/imgh-4-5.png]] | ||
| 312 | #+name: ench5 | ||
| 313 | #+caption: Использовано 5 битов. | ||
| 314 | #+attr_latex: :float subfigure :placement [b]{.3\textwidth} :width \textwidth | ||
| 315 | [[file:res/imgh-5-5.png]] | ||
| 316 | |||
| 317 | #+name: ench6 | ||
| 318 | #+caption: Использовано 6 битов. | ||
| 319 | #+attr_latex: :float subfigure :placement [b]{.3\textwidth} :width \textwidth | ||
| 320 | [[file:res/imgh-6-5.png]] | ||
| 321 | #+name: ench7 | ||
| 322 | #+caption: Использовано 7 битов. | ||
| 323 | #+attr_latex: :float subfigure :placement [b]{.3\textwidth} :width \textwidth | ||
| 324 | [[file:res/imgh-7-5.png]] | ||
| 325 | #+name: ench8 | ||
| 326 | #+caption: Использовано 8 битов. | ||
| 327 | #+attr_latex: :float subfigure :placement [b]{.3\textwidth} :width \textwidth | ||
| 328 | [[file:res/imgh-8-5.png]] | ||
| 329 | #+end_figure | ||
| 330 | |||
| 331 | * ЗАКЛЮЧЕНИЕ | ||
| 332 | :PROPERTIES: | ||
| 333 | :UNNUMBERED: t | ||
| 334 | :END: | ||
| 335 | В результате выполнения лабораторной работы была создана программа на | ||
| 336 | языке Haskell, которая способна кодировать текстовые данных из | ||
| 337 | указанного файла с помощью шифра Цезаря и сохранять эти данные внутрь | ||
| 338 | изображения. Причём программа позволяет выбрать как смещение для | ||
| 339 | шифра Цезаря, так и количество бит, которое будет использовано в | ||
| 340 | каждом байте изображения для хранения данных. | ||
| 341 | |||
| 342 | * СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ | ||
| 343 | :PROPERTIES: | ||
| 344 | :UNNUMBERED: t | ||
| 345 | :END: | ||
| 346 | #+print_bibliography: :heading none | ||
| 347 | |||
| 348 | # Local Variables: | ||
| 349 | # org-confirm-babel-evaluate: nil | ||
| 350 | # org-export-async-init-file: "ox-init.el" | ||
| 351 | # org-export-in-background: t | ||
| 352 | # End: | ||
diff --git a/doc/setup.org b/doc/setup.org new file mode 100644 index 0000000..2daa8e8 --- /dev/null +++ b/doc/setup.org | |||
| @@ -0,0 +1,24 @@ | |||
| 1 | #+options: ':nil *:t -:t ::t <:t H:3 \n:nil ^:{} arch:headline | ||
| 2 | #+options: author:t broken-links:nil c:nil creator:nil | ||
| 3 | #+options: d:(not "LOGBOOK") date:t e:t email:nil f:t inline:f num:t | ||
| 4 | #+options: p:nil pri:nil prop:nil stat:f tags:f tasks:f tex:t | ||
| 5 | #+options: timestamp:nil title:t toc:t todo:t |:t | ||
| 6 | #+creator: Emacs 29.4 (Org mode 9.7.14) | ||
| 7 | |||
| 8 | #+select_tags: export | ||
| 9 | #+exclude_tags: noexport | ||
| 10 | |||
| 11 | #+bibliography: biblio.bib | ||
| 12 | #+cite_export: biblatex | ||
| 13 | |||
| 14 | #+latex_compiler: xelatex | ||
| 15 | #+latex_class: spbstu-report | ||
| 16 | # #+latex_class_options: [draft] | ||
| 17 | #+latex_header: \usepackage{enumitem} | ||
| 18 | #+latex_header: \usepackage[newfloat]{minted} | ||
| 19 | #+latex_header: \usemintedstyle{bw} | ||
| 20 | #+latex_header: \setminted{baselinestretch=1,linenos,breaklines,escapeinside=\#\#,ignorelexererrors} | ||
| 21 | #+latex_header: \renewcommand\theFancyVerbLine{\large\arabic{FancyVerbLine}} | ||
| 22 | #+latex_header: \defaultfontfeatures{Ligatures=TeX,Scale=MatchLowercase,Mapping=tex-text} | ||
| 23 | #+latex_header: \setmainfont{Times New Roman} | ||
| 24 | #+latex_header: \setmonofont{Iosevka Term Slab}[Contextuals=AlternateOff] | ||
diff --git a/doc/spbstu-report.cls b/doc/spbstu-report.cls new file mode 100644 index 0000000..7ae6b05 --- /dev/null +++ b/doc/spbstu-report.cls | |||
| @@ -0,0 +1,74 @@ | |||
| 1 | \NeedsTeXFormat{LaTeX2e} | ||
| 2 | \ProvidesClass{spbstu-report}[2023/05/12 Класс для отчетов] | ||
| 3 | |||
| 4 | % | ||
| 5 | % Support font sizes: 12pt, 14pt | ||
| 6 | % | ||
| 7 | \DeclareOption{12pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} | ||
| 8 | \DeclareOption{14pt}{\PassOptionsToClass{\CurrentOption}{extarticle}} | ||
| 9 | |||
| 10 | \ProcessOptions\relax | ||
| 11 | |||
| 12 | \LoadClass[a4paper]{gost-7-32} | ||
| 13 | |||
| 14 | \RequirePackage{csquotes} | ||
| 15 | \RequirePackage{amsmath} | ||
| 16 | \RequirePackage{adjustbox} | ||
| 17 | \RequirePackage{setspace} | ||
| 18 | |||
| 19 | \newcommand{\@reportof}{}\newcommand{\reportof}[1]{\renewcommand{\@reportof}{#1}} | ||
| 20 | \newcommand{\@university}{}\newcommand{\university}[1]{\renewcommand{\@university}{#1}} | ||
| 21 | \newcommand{\@institute}{}\newcommand{\institute}[1]{\renewcommand{\@institute}{#1}} | ||
| 22 | \newcommand{\@school}{}\newcommand{\school}[1]{\renewcommand{\@school}{#1}} | ||
| 23 | \newcommand{\@direction}{}\newcommand{\direction}[1]{\renewcommand{\@direction}{#1}} | ||
| 24 | \newcommand{\@subject}{}\newcommand{\subject}[1]{\renewcommand{\@subject}{#1}} | ||
| 25 | \newcommand{\@reviewer}{}\newcommand{\reviewer}[1]{\renewcommand{\@reviewer}{#1}} | ||
| 26 | \newcommand{\@reviewertitle}{}\newcommand{\reviewertitle}[1]{\renewcommand{\@reviewertitle}{#1}} | ||
| 27 | \newcommand{\signdate}{$\underset{\centering\text{\normalsize подпись, дата}}{\underline{\hspace{5cm}}}$} | ||
| 28 | \newcommand{\@city}{}\newcommand{\city}[1]{\renewcommand{\@city}{#1}} | ||
| 29 | \renewcommand{\maketitle}{ | ||
| 30 | \begin{titlepage} | ||
| 31 | \begin{center} | ||
| 32 | \vspace{2cm} | ||
| 33 | \small{МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ РОССИЙСКОЙ ФЕДЕРАЦИИ} | ||
| 34 | |||
| 35 | \normalsize{\@university} | ||
| 36 | |||
| 37 | \vspace{0.5cm} | ||
| 38 | \normalsize{\@institute} | ||
| 39 | |||
| 40 | \normalsize{\@school} | ||
| 41 | |||
| 42 | \normalsize{Направление \@direction} | ||
| 43 | |||
| 44 | \vspace{2cm} | ||
| 45 | \LARGE{ОТЧЁТ} | ||
| 46 | |||
| 47 | \normalsize{\@reportof} | ||
| 48 | |||
| 49 | \large{\@subject} | ||
| 50 | |||
| 51 | \large{\textit{\@title}} | ||
| 52 | \end{center} | ||
| 53 | |||
| 54 | \vspace{3cm} | ||
| 55 | \small{ | ||
| 56 | \begin{tabular}{lrrl} | ||
| 57 | \!\!\!Студент, & \hspace{2cm} & & \\ | ||
| 58 | \!\!\!группы 5130201/20102 & \hspace{2cm} & \underline{\hspace{3cm}} & \@author \\\\ | ||
| 59 | \!\!\!Преподаватель, & \hspace{2cm} & \\ | ||
| 60 | \!\!\!\@reviewertitle & \hspace{2cm} & \underline{\hspace{3cm}} & \@reviewer \\\\ | ||
| 61 | &&\hspace{5cm} | ||
| 62 | \end{tabular} | ||
| 63 | \begin{flushright} | ||
| 64 | \enquote{\underline{\hspace{1cm}}}\underline{\hspace{2.5cm}} \@date г. | ||
| 65 | \end{flushright} | ||
| 66 | } | ||
| 67 | |||
| 68 | \vspace*{\fill} | ||
| 69 | \begin{center} | ||
| 70 | \small{\@city, \@date} | ||
| 71 | \end{center} | ||
| 72 | \end{titlepage} | ||
| 73 | \setcounter{page}{2} | ||
| 74 | } | ||
diff --git a/doc/task.org b/doc/task.org new file mode 100644 index 0000000..d8dbd8b --- /dev/null +++ b/doc/task.org | |||
| @@ -0,0 +1,32 @@ | |||
| 1 | *Обработка файлов в Haskell* (вариант *№26*) | ||
| 2 | |||
| 3 | Создать проект в stack. Все чистые функции записать в библиотеку | ||
| 4 | =Lib.hs= и ограничить доступ к вспомогательным функциям. Использовать | ||
| 5 | =do=-нотацию для работы с внешними файлами. Найти портрет указанного | ||
| 6 | человека: | ||
| 7 | |||
| 8 | *Паули, Вольфганг* | ||
| 9 | |||
| 10 | Перевести изображения в формат =.bmp= (24-разрядный), при необходимости | ||
| 11 | изменить ширину и высоту изображения без искажений. Сохранить в файл | ||
| 12 | формата =.txt= фрагмент биографии (не менее 1000 символов без пробелов, | ||
| 13 | текст не должен обрываться на середине слова или предложения). | ||
| 14 | Закодировать текст в изображение методом: | ||
| 15 | |||
| 16 | *Шифром Цезаря. Смещение задается пользователем* | ||
| 17 | |||
| 18 | Ключ к шифру записывается в имя файла. Написать функцию | ||
| 19 | расшифровывающую текст из изображения используя ключ из имени файла и | ||
| 20 | сохраняющую результат в отдельный текстовый файл. | ||
| 21 | |||
| 22 | Создать функции шифрующие текст в последний бит каждого байта, | ||
| 23 | последние два бита каждого байта, ..., все биты в байте. В отчете | ||
| 24 | привести примеры искажений изображения. | ||
| 25 | |||
| 26 | _Задача со звездочкой*_: Разобрать сложный формат данных с | ||
| 27 | использованием библиотек доступных в Hackage. Зашифровать и | ||
| 28 | расшифровать данные. | ||
| 29 | |||
| 30 | _Задача с двумя звездочками**_: Разобрать сложный формат данных | ||
| 31 | самостоятельно используя только стандартные библиотеки. Зашифровать и | ||
| 32 | расшифровать данные. | ||
diff --git a/src/Lib.hs b/src/Lib.hs new file mode 100644 index 0000000..250cc5c --- /dev/null +++ b/src/Lib.hs | |||
| @@ -0,0 +1,115 @@ | |||
| 1 | module Lib | ||
| 2 | ( encryptCaesar | ||
| 3 | , decryptCaesar | ||
| 4 | , textToBits | ||
| 5 | , bitsToText | ||
| 6 | , encodePixel | ||
| 7 | , extractShift | ||
| 8 | , extractBitsFromImage | ||
| 9 | ) where | ||
| 10 | |||
| 11 | import Codec.Picture | ||
| 12 | import Data.Bits ((.&.), (.|.), complement, shiftL, testBit) | ||
| 13 | import Data.Char (chr, isDigit, isLower, isUpper, ord) | ||
| 14 | import qualified Data.Vector.Unboxed as VU | ||
| 15 | import Data.Word (Word8) | ||
| 16 | import Text.Read (readMaybe) | ||
| 17 | |||
| 18 | addWithWrapInRange :: Int -> Int -> Int -> Int -> Int | ||
| 19 | addWithWrapInRange base increment lower upper = | ||
| 20 | lower + (base - lower + increment) `mod` (upper - lower + 1) | ||
| 21 | |||
| 22 | encryptCaesar :: Int -> String -> String | ||
| 23 | encryptCaesar shift text = map caesarChar text | ||
| 24 | where | ||
| 25 | caesarChar c | ||
| 26 | | isDigit c = chr $ addWithWrapInRange (ord c) shift (ord '0') (ord '9') | ||
| 27 | | isUpper c = chr $ addWithWrapInRange (ord c) shift (ord 'A') (ord 'Z') | ||
| 28 | | isLower c = chr $ addWithWrapInRange (ord c) shift (ord 'a') (ord 'z') | ||
| 29 | | otherwise = c | ||
| 30 | |||
| 31 | decryptCaesar :: Int -> String -> String | ||
| 32 | decryptCaesar shift = encryptCaesar (- shift) | ||
| 33 | |||
| 34 | textToBits :: String -> VU.Vector Int | ||
| 35 | textToBits text = VU.fromList $ concatMap charToBits text | ||
| 36 | |||
| 37 | charToBits :: Char -> [Int] | ||
| 38 | charToBits c = | ||
| 39 | [ if testBit (ord c) i | ||
| 40 | then 1 | ||
| 41 | else 0 | ||
| 42 | | i <- [7,6 .. 0] | ||
| 43 | ] | ||
| 44 | |||
| 45 | bitsToText :: VU.Vector Int -> String | ||
| 46 | bitsToText bits | ||
| 47 | | VU.null bits = [] | ||
| 48 | | otherwise = | ||
| 49 | (chr $ bitsToInt (VU.take 8 bits)) : bitsToText (VU.drop 8 bits) | ||
| 50 | |||
| 51 | bitsToInt :: VU.Vector Int -> Int | ||
| 52 | bitsToInt bits = | ||
| 53 | sum | ||
| 54 | [ bit * (2 ^ index) | ||
| 55 | | (bit, index) <- zip (VU.toList bits) [len,(len - 1) .. 0] | ||
| 56 | ] | ||
| 57 | where | ||
| 58 | len = VU.length bits - 1 | ||
| 59 | |||
| 60 | intToWord8 :: Int -> Word8 | ||
| 61 | intToWord8 x = fromIntegral x | ||
| 62 | |||
| 63 | word8ToInt :: Word8 -> Int | ||
| 64 | word8ToInt x = fromIntegral x | ||
| 65 | |||
| 66 | createMask :: Int -> Int | ||
| 67 | createMask shift = shiftL (complement 0) shift .&. complement 0 | ||
| 68 | |||
| 69 | encodePixel :: | ||
| 70 | Int -> Image PixelRGB8 -> VU.Vector Int -> Int -> Int -> PixelRGB8 | ||
| 71 | encodePixel bitsPerByte img bits x y = PixelRGB8 newR newG newB | ||
| 72 | where | ||
| 73 | width = imageWidth img | ||
| 74 | index = x + y * width | ||
| 75 | startPos = index * 3 * bitsPerByte | ||
| 76 | pixelBits = VU.slice startPos (3 * bitsPerByte) bits | ||
| 77 | bitsIntR = bitsToInt $ VU.slice 0 bitsPerByte pixelBits | ||
| 78 | bitsIntG = bitsToInt $ VU.slice bitsPerByte bitsPerByte pixelBits | ||
| 79 | bitsIntB = bitsToInt $ VU.slice (2 * bitsPerByte) bitsPerByte pixelBits | ||
| 80 | mask = createMask bitsPerByte | ||
| 81 | PixelRGB8 r g b = pixelAt img x y | ||
| 82 | newR = intToWord8 $ ((word8ToInt r) .&. mask) .|. bitsIntR | ||
| 83 | newG = intToWord8 $ ((word8ToInt g) .&. mask) .|. bitsIntG | ||
| 84 | newB = intToWord8 $ ((word8ToInt b) .&. mask) .|. bitsIntB | ||
| 85 | |||
| 86 | extractBits :: Int -> Pixel8 -> [Int] | ||
| 87 | extractBits bitsPerByte pixelByte = | ||
| 88 | [ if testBit pixelByte i | ||
| 89 | then 1 | ||
| 90 | else 0 | ||
| 91 | | i <- [bitsPerByte - 1,bitsPerByte - 2 .. 0] | ||
| 92 | ] | ||
| 93 | |||
| 94 | extractBitsFromPixel :: Int -> PixelRGB8 -> [Int] | ||
| 95 | extractBitsFromPixel bitsPerByte (PixelRGB8 r g b) = | ||
| 96 | let bitsR = extractBits bitsPerByte r | ||
| 97 | bitsG = extractBits bitsPerByte g | ||
| 98 | bitsB = extractBits bitsPerByte b | ||
| 99 | in bitsR ++ bitsG ++ bitsB | ||
| 100 | |||
| 101 | extractBitsFromImage :: Int -> Image PixelRGB8 -> [Int] | ||
| 102 | extractBitsFromImage bitsPerByte img = | ||
| 103 | let width = imageWidth img | ||
| 104 | height = imageHeight img | ||
| 105 | pixels = | ||
| 106 | [pixelAt img x y | y <- [0 .. height - 1], x <- [0 .. width - 1]] | ||
| 107 | in concatMap (extractBitsFromPixel bitsPerByte) pixels | ||
| 108 | |||
| 109 | extractShift :: String -> Maybe Int | ||
| 110 | extractShift path = | ||
| 111 | let shift = | ||
| 112 | takeWhile | ||
| 113 | (`elem` ['0' .. '9']) | ||
| 114 | (reverse $ takeWhile (/= '-') (reverse path)) | ||
| 115 | in readMaybe shift | ||
