Wednesday, 20 April 2016

Converting Dicom files to standard image format(.jpeg,.png etc) in MVC using C#

So I was doing a project of medical domain and I faced a big challenge to handle the Dicom files. The users of my application wanted to upload a zip file which contains some DICOM files and then they wanted to see it in image format. So I am sharing my efforts in the form of a sample project.


Introduction

First of all by writing this article I am celebrating my success on my assignment to handle Dicom files in MVC. There are many software available which can show Dicom images but it was a web application and browser doesn't understand DICOM format, so I have to process the uploaded zip and convert each DICOM file to Jpeg format and shown these on the browser.  Though there are many projects on internet depicting conversion of Dicom files to Standard image formats (Code Project also have an aritcle) but none of the projects fulfilled my requirements because some are using deprecated dlls or some are bounded with the Dicom extension(.dcm). So I have created a project which can convert any Dicom file (with or without extension) to standard image format.

Background

Developers having knowledge of Dicom or having challenges regarding Dicom library would find it interesting. https://en.wikipedia.org/wiki/DICOM

Steps to Run the project :

Open this project using Visual Studio 2012 or 2013 and run it. It will show you the Index page of DicomSlider Controller. You will see a file upload control, click the browse button and browse to project folder itself, it has a folder named "Sample Files", open this folder you will find a zip file, select it and click on submit button. After clicking submit button it will process each file of zip folder and convert it to jpeg file and show you on the same Index page. Now lets look what is exactly being done at code level to achieve this :

Using the code

It is a simple MVC project without Authentication having a single controller and two actions and a single view. You will need two dlls to copy in your project to make this code work. I am posting the full project here so you can find those dll in project's bin folder named : "dicom.dll and dicom.native.dll". 
So basically this project has a view which is capable of uploading a zip file and this same view also show the result of zip processing. It displays the images which are converted from Dicom format to JPEG. So lets look at the code step by step:

1. View (Index.cshtml):

The view is very simple having only a browse button to upload the zip of Dicom files and after submit it will show the converted files:

@model List<DicomSliderDemo.Models.SliderModel>

@{
    ViewBag.Title = "Index";

}

@using (Html.BeginForm("UploadZip", "DicomSlider", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <table>
        <tr>
            <input id="filePosted" name="filePosted" type="file" />
            <input id="Submit1" type="submit" value="submit" />
        </tr>
 </table>
}
<div style="width:inherit;height:250PX">
    @if (Model != null && Model.Count() > 0)
    {
        foreach (var pathModel in Model)
        {
            <div style="DISPLAY: BLOCK; FLOAT: left; WIDTH: 300PX; height: 200PX; margin:10PX;border:2PX solid GRAY">
                
                <img src="~/DicomSlider/DICOMIMG/@pathModel.Path" id="@pathModel.Id" alt="" width="300" height="200" />
                <label>@pathModel.Id</label>

            </div>
        }
    }
</div>

So you can see this view is having a model of list type, this list will be responsible for showing the converted images. It has a from which is being post at "UploadZip" action of "DicomSlider" controller. So when you clcick submit button the form posted to thisd action with the selected files in file upload control. We are haivng a Div under the form element, this div will be responsible to show the converted files. You cann see and img tage there having the src pointing to "DICOMIMG" folder which resides in our root project files You will see how this folder is used to store images at the controller level so lets look at the Controller Code, bascially we will look at the "UploadZip" action.

2. Controller:

public class DicomSliderController : Controller
    {
        //
        // GET: /DicomSlider/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult UploadZip(HttpPostedFileBase filePosted)
        {
            List<SliderModel> objModel = new List<SliderModel>();
            try
            {
                objModel=uploadAndSaveZipFile(filePosted);
            }
            catch (Exception ex)
            { }
            return View("Index", objModel);
        }

        public List<SliderModel> uploadAndSaveZipFile(HttpPostedFileBase objFile)
        {

            List<SliderModel> objModel = new List<SliderModel>();
            try
            {
                string FilesPath = Server.MapPath("Dtest");
                string ImagesPath = Server.MapPath("DICOMIMG");

                DirectoryInfo objDirectory = new DirectoryInfo(FilesPath);

                DirectoryInfo objDirectoryImg = new DirectoryInfo(ImagesPath);

                if (!objDirectoryImg.Exists)
                {
                    Directory.CreateDirectory(ImagesPath);
                }
                

                if (objDirectory.Exists)
                {
                    foreach (System.IO.DirectoryInfo subDirectory in objDirectory.GetDirectories())
                    {
                        SetDirAttributesNormal(subDirectory);
                        subDirectory.Delete(true);
                    }
                    SetDirAttributesNormal(objDirectory);
                    objDirectory.Delete(true);
                    Directory.CreateDirectory(Server.MapPath("Dtest"));
                }


                ZipFile objZip = ZipFile.Read(objFile.InputStream);

                objZip.ExtractAll(FilesPath);

                string[] objFInfo = Directory.GetFiles(FilesPath + "\\" + Path.GetFileNameWithoutExtension(objFile.FileName));

                int i = 0;
                foreach (var ofile in objFInfo)
                {
                    try
                    {
                        var img = new DicomImage(ofile);
                        Bitmap bitmap = new Bitmap(img.RenderImage());
                        bitmap.Save(ImagesPath + "\\D" + i + ".jpg", ImageFormat.Jpeg);

                        i++;
                    }
                    catch (Exception ex)
                    {

                    }
                }

                objDirectory = new DirectoryInfo(FilesPath);
                if (objDirectory.Exists)
                {
                    foreach (System.IO.DirectoryInfo subDirectory in objDirectory.GetDirectories())
                    {
                        SetDirAttributesNormal(subDirectory);
                        subDirectory.Delete(true);
                    }
                    SetDirAttributesNormal(objDirectory);
                    objDirectory.Delete(true);
                }

                objDirectoryImg = new DirectoryInfo(ImagesPath);

                objModel = objDirectoryImg.GetFiles().Select(x => new SliderModel
                {
                    
                    Id=x.Name,
                    Path = x.Name,
                }).ToList();

               
            }
            catch (Exception ex)
            { }

            return objModel;
        }

        [NonAction]
        public  void SetDirAttributesNormal(DirectoryInfo dir)
        {
            foreach (var subDirPath in dir.GetDirectories())
            {
                SetDirAttributesNormal(new DirectoryInfo(subDirPath.ToString()));
                subDirPath.Attributes = FileAttributes.Normal;
            }

            foreach (var filePath in dir.GetFiles())
            {
                var file = new FileInfo(filePath.Directory + "/" + filePath.Name);
                file.Attributes = FileAttributes.Normal;
            }
        }
    }

You can see the Controller is having four methods, I will describe it step by step :

1. Index Action : It is responsible for the page which gives us facility to upload files and see the results in the form of image files.
2. UploadZip Action : This is the post action which will be called when you click the submit button on Index page. This is the action which is responsible for our core functionality, it porcess the zip file and convert the DICOM files to JPEG files. So let's look at the important line of codes of this action.
This action is expecting the "HttpPostedFileBase" object which is standard object of System.Web namespace that contains the uploaded file by the user.
It is declaring a list of "SliderModel". If you look at this class then you can find two properties in it : 1. Id 2.Path. Where Id depicts the image name and Path depicts the physical file name. In our case both are same.
Next it calls a function named "uploadAndSaveZipFile" and pass the object of "HttpPostedFileBase" and this function return a list of "SliderModel" at the last it return the "Index" view with "SliderModel" and we already decorated our Index view with this kind of model so it can handle it.

3. uploadAndSaveZipFile Method : This method extract the zip and process the files one by one to convert these in jpeg file format. This function deletes any zip file with same name (if exists)  before extracting the uploaded zip and in the last it gives a list of converted image's paths and names. So lets look at the important code lines of this method:
So in First two lines it is setting the paths of Extracted zip file and folder to store converted images files respectively. in "Dtest" directory it will extract the zip file and "DICOMIMG" folder will hold the converted images.
So First we checked if Image Direcotry is exist or not and if it doesnt exist then we created it. It is a simple code just delaing with "DirectoryInfo" class.
Next it checks if "Dtest" directory exists and if it exists then it deletes the folder and it's files becuase it may have old files. It first loops through sub directories and deletes all then it deletes the root folder. One thing to note before deltion it calls a function "SetDirAttributesNormal". This function bascially sets file attribute to Normal in ase if it is a "ReadOnly" file because if the file is readonly then it can't be deleted, you have to change it's attriute first. After Deleting the existing directory it create a new directory.
Next it creates and object of "ZipFile" by passing input stream of uploaded file. This calls is taken from Ionic.Zip.dll. After creating object it extract all the files of zip to "Dtest" folder.
Next if fetch the list of all files in "Dtest" folder and it extracts the file names without extension. It loops through the list and now the conversion part comes :

var img = new DicomImage(ofile);
Bitmap bitmap = new Bitmap(img.RenderImage());
bitmap.Save(ImagesPath + "\\D" + i + ".jpg", ImageFormat.Jpeg);

In the first line it is creating an object of "DicomImage" class, the constructor takes file name and return an object of "DicomImage" class. In Second line we are creating an object of Bitmap class, the constructor takes "Image" as an argument so we use the "DicomImage" object and calls the method called "RenderImage" which retrun an object of "Image". then in the last line it saves the image in the format of jpeg in  "DICOMIMG" folder.
Now its delete the "Dtest" directory and returns the list of converted image's name.
This is how it converts Dicom files to JPEG files.
The submitted code can be rough somewhere so sorry for that but it will surely solve your challenges. 
Thanks for reading the article, I have attached the sample project so you can download and check and if you have any questions regarding this article, I am here to solved those anytime.

Wednesday, 26 August 2015

File Uploading and posting the form data with Ajax and Jquery in Asp.Net MVC




Introduction :

This article introduce an example of Asp.Net MVC project to post the form data including File uploading (Collectively) through Ajax and Jquery.

Background :

You can find many examples of file uploading through Ajax-Jquery in MVC but if you want to post a form data which includes a file also to be uploaded then those articles doesn't suit your requirement, and people who use "Ajax.BeginForm()" to post the form through Ajax also can't be able to get the files to be uploaded on POST Action. So this example describe a simple approach to accomplish this requirement.

 

 Tools and Library Used:

1. Visual Studio 2013

2. MVC5

3. jquery-1.10.2

 

The Model :

To get started with this first we have to define a model which we want to post through our form :

    public class TestModel
    {
       public string Name { get; set;}
       public string Surname { get; set; }

    }

We have defined a model (class) which consists two string type properties which we are going to submit through form. 

The View :

@model TestUpload.Models.TestModel

@using (Html.BeginForm("UFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "Myform" }))
{
        @Html.TextBoxFor(c=>c.Name)
        @Html.TextBoxFor(c=>c.Surname)
        <input type="file" id="myfile" name="myfile" multiple />
        <button id="myBtn" type="button">Submit</button>
}

<script>
    $(document).ready(function () {
        $("#myBtn").click(function () {
            var formData = new FormData($("form#Myform")[0]);
            // send them to server
            $.ajax({
                type: "POST",
                url: '@Url.Action("UFile", "Home")',
                data: formData,
                dataType: 'json',
                contentType: false,
                processData: false,
                success: function (response) {
                    alert(response);
                },
                error: function (error) {
                    alert(error.message);
                }
            });
        });
    });

</script>

We have defined a view  called  "UFile .cshtml" which is bounded by our "TestModel", contains two text boxes and one file upload control which can accept multiple files. All the element are in the scope of a form "Html.BeginForm" not "Ajax.BeginForm". Now there is a button, on the button click we want to save the entered data of text box in database and also want to upload and save the files to our local directory, and most importantly all this work should be asynchronous(No-Post back). So in Script we have used $.ajax to post this data asynchronously. Now look at the highlighted line, this is the bunch of words which is doing all the magic for us. From this line we can get all the form data serialized in a model and all the files in HttpRequest object. Except this line nothing is new, we are just giving a url to call. If you are not familiar with @Url.Action then it is just taking two parameters and it will automatically generate the url for you. First argument in for "Action Name" and Second argument is for "Controller Name". Now have a look at the Action defined in the Home Controller.

 

The Controller:

public class HomeController : Controller
{
      
        public ActionResult UFile()
        {
            return View();
        }

        [HttpPost]
        public ActionResult UFile(TestModel model)
        {
              // Get All the files in request variable.
            for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];

                var fileName = Path.GetFileName(file.FileName);

                var path = Path.Combine(Server.MapPath("~/Upload/"), fileName);
                file.SaveAs(path);
            }
            return Json("You Did it "+string.Format("{0} {1}",model.Name,model.Surname));
        }

    }

We have  a controller called "Home" there are two Actions of same name with different arguments. One is for initial view rendering(the view which we have already described). And the second annotated with [HttpPost] is the action which is being called by the Ajax Script we have defined on our view. The action is self-explanatory, you can notice the highlighted portion in "Request.Files", you will get all the files which you have browsed before clicking the submit button and "Model.Name" and "Model.Surname"  will give you the value of textboxes you have entered before clicking the submit button.


Summary:

There are many articles which describes the process of uploading files through Ajax and Jquery and many articles describes the process of submitting a model to controller through Ajax but you have to do your hands dirty when it comes to achieve both in one shot so this articles describes you the trick of achieving both in one go. Hope this solves your many problems.

 Please share your views and questions, I'll be happy to help you.


Happy Coding!!!