Image blurring is a king of popular task during presentation preparation. For example, if you want show something but hide sensitive information. Of course you can buy Photoshop but it is too expensive for such a simple task. Also you can download Paint.NET, but this is not an option for F# geek – it is too easy=). It is much better to write something by yourself (Binaries are available as well as source code).
open System
open System.IO
open System.Drawing
open System.Drawing.Imaging
let blur (image:Bitmap) blurSize =
let blurred = new Bitmap(image.Width, image.Height)
use graphics = Graphics.FromImage(blurred)
let rectangle = Rectangle(0, 0, image.Width, image.Height)
graphics.DrawImage(image, rectangle, rectangle, GraphicsUnit.Pixel);
for X in [0..image.Width-1] do
for Y in [0..image.Height-1] do
let (r,g,b,c) =
[Math.Max(0, X-blurSize)..Math.Min(image.Width-1, X+blurSize)]
|> Seq.fold (fun sum x ->
[Math.Max(0, Y-blurSize)..Math.Min(image.Height-1, Y+blurSize)]
|> Seq.fold (fun (r,g,b,c) y ->
let p = blurred.GetPixel(x,y)
(r + (int)p.R, g + (int)p.G, b + (int)p.B, c+1)
) sum
) (0,0,0,0)
blurred.SetPixel(X, Y, Color.FromArgb(r/c, g/c, b/c));
blurred
[<EntryPoint>]
let main argv =
try
printfn "argv = %A" argv
let (fileName, blurSize) =
match argv with
| [|fileName|] -> (fileName, 3)
| [|fileName; size|] ->
match Int32.TryParse(size) with
| (true, blurSize) when blurSize > 0 -> (fileName, blurSize)
| _ -> failwithf "Incorrect blurSize '%s'" size
| _ -> failwith "Incorrect parameters. Please enter 'fileName' and 'blurSize'"
printfn "FileName:%s\nBlurSize:%d" fileName blurSize
if (not(File.Exists(fileName)))
then failwithf "File '%s' does not exist." fileName
use inputStream = new MemoryStream(File.ReadAllBytes(fileName));
use source = new Bitmap(Image.FromStream(inputStream));
printfn "Processing..."
use result = blur source blurSize
printfn "Saving..."
let resultFileName =
sprintf "%s_%dblurred.jpg" (Path.GetFileNameWithoutExtension(fileName)) blurSize
result.Save(resultFileName, ImageFormat.Jpeg)
printfn "Done!"
with
| e ->
printfn "Exception : %s" e.Message
Console.ReadLine() |> ignore
0


Discover more from Sergey Tihon's Blog
Subscribe to get the latest posts sent to your email.
Just a warning! Blurring does not hide sensitive information. By decor elation you can unhide sensitive information.