Saturday, January 8, 2022

How to unzip all the zip files present in folder and sub folders using java

In this tutorial, we are going to learn how we can unzip all the zip files present in the folder and sub-folders.

Steps to follow:

  • loop through the folder and subfolders and get the files inside it.
  • Check if the file is a zip file or not
  • If the file is a zip file then extract that file in the corresponding folder

Create a java class called UnzipFolderFile.java. First, let's implement the method which will loop through the folder and subfolders and read the zip file.

public static void searchZipFile(String directoryName) throws IOException {
        File directory = new File(directoryName);
        File[] fList = directory.listFiles();
        if (fList != null)
            for (File file : fList) {
                if (file.isDirectory()) {
                    searchZipFile(file.getAbsolutePath());
                } else if (file.isFile()) {
                    String ext = getFileExtension(file.getName());
                    if (ext.equals(".zip")) {
                        System.out.println("Zip file found");
                        String zipFilePath = file.getAbsolutePath();
                        String unZipOutputPath = getFileNameWithoutExtension(zipFilePath); // using apache commons i.o library
                        unzipFile(zipFilePath, unZipOutputPath);
                        searchZipFile(unZipOutputPath); // for nested zip file
                    }
                }
            }
    }

Here, we are using the recursion in order to search zip files inside sub-folders. If the current file is a directory then it will again search inside this directory. If it is a zip file then it will unzip that file. 

Note that we need to extract the nested zip file i.e zip file inside zip file case so, we used searchZipFile(unZipOutputPath); recursion.

In order to get the current folder, we are using the getFileNameWithoutExtension method which we gonna implement later. Now, let's implement the unzipFile method getFileExtension to get the extension of the file in order to test the current file is a zip file or not

 public static String getFileExtension(String fileName) {
        int lastIndexOf = fileName.lastIndexOf(".");
        if (lastIndexOf == -1) {
            return ""; // empty extension
        }
        return fileName.substring(lastIndexOf).toLowerCase();
    }
public static void unzipFile(String zipFilePath, String outputDir) throws IOException {
        byte[] buffer = new byte[1024];
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry zipEntry = zis.getNextEntry();
        while (zipEntry != null) {
            File newFile = new File(outputDir + File.separator, zipEntry.getName());
            if (zipEntry.isDirectory()) {
                if (!newFile.isDirectory() && !newFile.mkdirs()) {
                    throw new IOException("Failed to create directory " + newFile);
                }
            } else {
                File parent = newFile.getParentFile();
                if (!parent.isDirectory() && !parent.mkdirs()) {
                    throw new IOException("Failed to create directory " + parent);
                }
                FileOutputStream fos = new FileOutputStream(newFile);
                int len = 0;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
            }
            zipEntry = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();
    }

This method accepts the zip file path and output path to unzip and extract the zip file and output it in the output directory provided.

Now, create getFileNameWithoutExtension method to get the directory path. For this, we are using org.apache.commons.io library. For this, load the jar file in your IDE, or if you have existing projects like Maven or Gradle add the dependency as below.

For Gradle:

Add in build.gradle under "dependencies"

implementation 'org.apache.directory.studio:org.apache.commons.io:2.4'

For Maven:

Add in pom.xml

<dependency>
  <groupId>org.apache.directory.studio</groupId>
  <artifactId>org.apache.commons.io</artifactId>
  <version>2.4</version>
</dependency>
public static String getFileNameWithoutExtension(String name) {
        return FilenameUtils.removeExtension(name);
    }

Now, implement the main method to execute the program

public static void main(String[] args) {
        String directory = "path-to-folder";
        try {
            searchZipFile(directory);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

The overall implementation looks as below:

package io;

import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnzipFolderFile {
    public static void main(String[] args) {
        String directory = "path-to-folder";
        try {
            searchZipFile(directory);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void searchZipFile(String directoryName) throws IOException {
        File directory = new File(directoryName);
        File[] fList = directory.listFiles();
        if (fList != null)
            for (File file : fList) {
                if (file.isDirectory()) {
                    searchZipFile(file.getAbsolutePath());
                } else if (file.isFile()) {
                    String ext = getFileExtension(file.getName());
                    if (ext.equals(".zip")) {
                        System.out.println("Zip file found");
                        String zipFilePath = file.getAbsolutePath();
                        String unZipOutputPath = getFileNameWithoutExtension(zipFilePath); // using apache commons i.o library
                        unzipFile(zipFilePath, unZipOutputPath);
                        searchZipFile(unZipOutputPath); // for nested zip file
                    }
                }
            }
    }

    public static void unzipFile(String zipFilePath, String outputDir) throws IOException {
        byte[] buffer = new byte[1024];
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry zipEntry = zis.getNextEntry();
        while (zipEntry != null) {
            File newFile = new File(outputDir + File.separator, zipEntry.getName());
            if (zipEntry.isDirectory()) {
                if (!newFile.isDirectory() && !newFile.mkdirs()) {
                    throw new IOException("Failed to create directory " + newFile);
                }
            } else {
                File parent = newFile.getParentFile();
                if (!parent.isDirectory() && !parent.mkdirs()) {
                    throw new IOException("Failed to create directory " + parent);
                }
                FileOutputStream fos = new FileOutputStream(newFile);
                int len = 0;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
            }
            zipEntry = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();
    }

    public static String getFileExtension(String fileName) {
        int lastIndexOf = fileName.lastIndexOf(".");
        if (lastIndexOf == -1) {
            return ""; // empty extension
        }
        return fileName.substring(lastIndexOf).toLowerCase();
    }

    public static String getFileNameWithoutExtension(String name) {
        return FilenameUtils.removeExtension(name);
    }
}
Share:

How to read only specific file from folder and sub folder using Java

In this tutorial, we are going to learn how we can learn only specific files like .png or .jpg or any other file extension which are allocated inside folder and sub-folders.

Here, what we gonna do is to list all the folders and subfolders. After that looping through the folders to filter out and get the specific desired file from those folders.

Create a sample Java class called FolderFileReader.java

Create a method that lists all the subfolders present in the folder.

 public static void listDirSubDir(String directoryName, List<String> directoryList) throws Exception {
        File directory = new File(directoryName);
        File[] fList = directory.listFiles();
        if (fList != null)
            for (File file : fList) {
                if (file.isDirectory()) {
                    String folder = file.getAbsolutePath();
                    directoryList.add(folder);
                    listDirSubDir(folder, directoryList);
                }
            }
    }

We are using recursion in order to list all the subfolders and add the available folders to the List called directoryList

Now, let's create a method that will list all the files present in the particular folder.

public static ArrayList<String> getFolderFiles(String folder) throws Exception {
        ArrayList<String> FileList = new ArrayList<String>();
        FileExtensionFilter filter = new FileExtensionFilter(extension);
        File dir = new File(folder);
        if (!dir.isDirectory()) {
            throw new Exception("Directory does not exists: " + folder);
        }
        String[] list = dir.list(filter);
        assert list != null;
        if (list.length == 0) {
            System.out.println("File not found in this folder : " + dir.getName());
        }
        for (String file : list) {
            String temp = folder + File.separator + file;
            FileList.add(temp);
        }
        return FileList;
    }

The FileExtensionFilter is the filter class used to read specific file like .png or .jpg. 

Let's create the filter class

public static class FileExtensionFilter implements FilenameFilter {

        private String ext;

        public FileExtensionFilter(String ext) {
            this.ext = ext;
        }

        public boolean accept(File dir, String name) {
            return name.endsWith(this.ext);
        }
    }

Now, implement the main method

public static void main(String[] args) {
        String directory = "folder_path";
        ArrayList<String> directoryList = new ArrayList<>();
        try {
            directoryList.add(directory); // adding current directory
            listDirSubDir(directory, directoryList);
            System.out.println("Total directory found: " + directoryList.size());
            int totalFileFound = 0;
            for (String folder : directoryList) {
                ArrayList<String> files = getFolderFiles(folder);
                for (String file : files) {
                    System.out.println(file);
                }
                totalFileFound += files.size();
            }
            System.out.println("Total files found: " + totalFileFound);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Here, we are simply getting the list of folders available, looping through it, and getting the files present in each folder.

The overall implementation looks as below:

package io;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

public class FolderFileReader {

    private static final String extension = ".dcm";

    public static void main(String[] args) {
        String directory = "folder_path";
        ArrayList<String> directoryList = new ArrayList<>();
        try {
            directoryList.add(directory); // adding current directory
            listDirSubDir(directory, directoryList);
            System.out.println("Total directory found: " + directoryList.size());
            int totalFileFound = 0;
            for (String folder : directoryList) {
                ArrayList<String> files = getFolderFiles(folder);
                for (String file : files) {
                    System.out.println(file);
                }
                totalFileFound += files.size();
            }
            System.out.println("Total files found: " + totalFileFound);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void listDirSubDir(String directoryName, List<String> directoryList) throws Exception {
        File directory = new File(directoryName);
        File[] fList = directory.listFiles();
        if (fList != null)
            for (File file : fList) {
                if (file.isDirectory()) {
                    String folder = file.getAbsolutePath();
                    directoryList.add(folder);
                    listDirSubDir(folder, directoryList);
                }
            }
    }

    public static ArrayList<String> getFolderFiles(String folder) throws Exception {
        ArrayList<String> FileList = new ArrayList<String>();
        FileExtensionFilter filter = new FileExtensionFilter(extension);
        File dir = new File(folder);
        if (!dir.isDirectory()) {
            throw new Exception("Directory does not exists: " + folder);
        }
        String[] list = dir.list(filter);
        assert list != null;
        if (list.length == 0) {
            System.out.println("File not found in this folder : " + dir.getName());
        }
        for (String file : list) {
            String temp = folder + File.separator + file;
            FileList.add(temp);
        }
        return FileList;
    }

    public static class FileExtensionFilter implements FilenameFilter {

        private String ext;

        public FileExtensionFilter(String ext) {
            this.ext = ext;
        }

        public boolean accept(File dir, String name) {
            return name.endsWith(this.ext);
        }
    }
}
Share:

How to convert Dicom file into PNG or JPG using Java

In this tutorial, we are going to learn how to convert the Dicom file into Png or Jpg.

If we want to present the Dicom image in the browser or sometimes it might be required to convert it to the desired png or jpg image to manipulate process and analysis.

For this, we can use a very useful library called SimpleItk. Please go over the installation process from this tutorial. If we are dealing with medical images like Dicom, the library is very useful for image processing, manipulation, and analysis. So we suggest using the library.

For reading Dicom metadata please follow this tutorial.

Now, let's begin with the conversion of the Dicom file, for this let's create a sample Java class called DicomConverter.java and create a method for reading the Dicom file

import org.itk.simple.*;
public static ImageFileReader getDcmImageFileReader(String imagePath) {
        ImageFileReader imageFileReader = new ImageFileReader();
        imageFileReader.setImageIO("GDCMImageIO");
        imageFileReader.setFileName(imagePath);
        return imageFileReader;
    }

Now, let's add the method for converting the Dicom

public static void convert(ImageFileReader imageFileReader, String outputPath) {
        Image image = imageFileReader.execute();
        SimpleITK.writeImage(image, outputPath);
    }

Create the main method to run the conversion

 public static void main(String[] args) {
        String inputDicomPath = "inputdicom_path/N2D_0001.dcm";
        String outputPath = "output_path/test.png";
        try {
            ImageFileReader imageFileReader = getDcmImageFileReader(inputDicomPath);
            convert(imageFileReader, outputPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
For Jpg use the .jpg output path.

The overall implementation looks like below:

package dicom;

import org.itk.simple.*;


public class DicomConverter {
    public static void main(String[] args) {
        String inputDicomPath = "/N2D_0001.dcm";
        String outputPath = "/test.png";
        try {
            ImageFileReader imageFileReader = getDcmImageFileReader(inputDicomPath);
            convert(imageFileReader, outputPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static ImageFileReader getDcmImageFileReader(String imagePath) {
        ImageFileReader imageFileReader = new ImageFileReader();
        imageFileReader.setImageIO("GDCMImageIO");
        imageFileReader.setFileName(imagePath);
        return imageFileReader;
    }
    public static void convert(ImageFileReader imageFileReader, String outputPath) {
        Image image = imageFileReader.execute();
        SimpleITK.writeImage(image, outputPath);
    }
}
Share:

Read the Dicom Image metadata using Java

In this tutorial, we are going to learn how we can read Dicom image metadata. 

A Dicom metadata generally contains:

  •  A tag that identifies the attribute, usually in the format (XXXX,XXXX) with hexadecimal numbers.
  • A DICOM Value Representation (VR) that describes the data type and format of the attribute value

We are using SimpleITK library to extract metadata. The library is very handy when used for medical Image analysis. So, please refer SimpleITK library installation from this tutorail.

Once installed and load the library, let's write some Java code that reads metadata. Create a Java file called DicomReader.java

Read the Dicom file using SimpleITK:

import org.itk.simple.ImageFileReader;
public static ImageFileReader getDcmImageFileReader(String imagePath) {
        ImageFileReader imageFileReader = new ImageFileReader();
        imageFileReader.setImageIO("GDCMImageIO");
        imageFileReader.setFileName(imagePath);
        return imageFileReader;
    }
This will read the Dicom file. This example uses the standard SimpleITK native library.

Let's create an actual method that read the metadata from the Dicom Image file

import org.itk.simple.VectorString;
import java.util.LinkedHashMap;
import java.util.Map;
public static Map<String, String> readMetadata(ImageFileReader imageFileReader) {
        Map<String, String> metaData = new LinkedHashMap<>();
        imageFileReader.loadPrivateTagsOn();
        imageFileReader.readImageInformation();
        VectorString metaDataKeys = imageFileReader.getMetaDataKeys(); // get metadata keys
        long metaDataKeySize = metaDataKeys.size();
        System.out.println("Total meta data found: " + metaDataKeySize);
        for (int metaDataKeyIndex = 0; metaDataKeyIndex < metaDataKeySize; metaDataKeyIndex++) {
            String metaDataKey = metaDataKeys.get(metaDataKeyIndex);
            String metaDataValue = imageFileReader.getMetaData(metaDataKey);
            System.out.println("Key: " + metaDataKey + " Value: " + metaDataValue);
            metaData.put(metaDataKey, metaDataValue);
        }
        return metaData;
    }
Here, we are passing the ImageFileReader object, which is obtained from the previous method. And it will extract the metadata and loop through the metadata keys and print key values. pair in the console.

Here is the sample GitHub repo for getting sample test Dicom. Let's add the main method to run the code

 public static void main(String[] args) {
        String imagePath = "path_to_dicom/N2D_0001.dcm";
        try {
            ImageFileReader imageFileReader = getDcmImageFileReader(imagePath);
            Map<String, String> metadata = readMetadata(imageFileReader);
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

The output of the above example will be similar to like this:

Total meta data found: 53
Key: 0008|0008 Value: DERIVED\SECONDARY 
Key: 0008|0016 Value: 1.2.840.10008.5.1.4.1.1.4
Key: 0008|0018 Value: 1.2.826.0.1.3680043.2.1143.1590429688519720198888333603882344634
Key: 0008|0020 Value: 20130717
Key: 0008|0021 Value: 20130717
Key: 0008|0022 Value: 20130717
Key: 0008|0023 Value: 20130717
Key: 0008|0030 Value: 141500
Key: 0008|0031 Value: 142035.93000
Key: 0008|0032 Value: 132518
Key: 0008|0033 Value: 142035.93 
Key: 0008|0050 Value: 
Key: 0008|0060 Value: MR
Key: 0008|0070 Value: BIOLAB
Key: 0008|0080 Value: 
Key: 0008|0090 Value: 
Key: 0008|1030 Value: Hanke_Stadler^0024_transrep 
Key: 0008|103e Value: anat-T1w
Key: 0008|1090 Value: nifti2dicom 
Key: 0010|0010 Value: Jane_Doe
Key: 0010|0020 Value: 02
Key: 0010|0030 Value: 19660101
Key: 0010|0040 Value: F 
Key: 0010|1000 Value: 
Key: 0010|1010 Value: 42
Key: 0010|1030 Value: 75
Key: 0010|21c0 Value: 4
Key: 0018|0050 Value: 0.666666686534882 
Key: 0018|0088 Value: 0.666666686534882 
Key: 0018|1020 Value: 0.4.11
Key: 0018|1030 Value: anat-T1w
Key: 0020|000d Value: 1.2.826.0.1.3680043.2.1143.2592092611698916978113112155415165916
Key: 0020|000e Value: 1.2.826.0.1.3680043.2.1143.515404396022363061013111326823367652
Key: 0020|0010 Value: 433724515 
Key: 0020|0011 Value: 401 
Key: 0020|0012 Value: 1 
Key: 0020|0013 Value: 1 
Key: 0020|0020 Value: L\R 
Key: 0020|0032 Value: -91.4495864331908\-160.06035870244\-142.505487236053
Key: 0020|0037 Value: 0.999032176441525\-0.0217883751691557\0.0382096472372976\0.026519476938784\0.991413870277297\-0.128043957939
Key: 0020|0052 Value: 1.2.826.0.1.3680043.2.1143.6856184167807409206647724161920598374
Key: 0028|0002 Value: 1
Key: 0028|0004 Value: MONOCHROME2 
Key: 0028|0010 Value: 384
Key: 0028|0011 Value: 274
Key: 0028|0030 Value: 0.666666686534882\0.699987828731537 
Key: 0028|0100 Value: 16
Key: 0028|0101 Value: 16
Key: 0028|0102 Value: 15
Key: 0028|0103 Value: 1
Key: 0028|1052 Value: 0 
Key: 0028|1053 Value: 1 
Key: 0028|1054 Value: US

In the above output, the key is the standard metadata key and the corresponding values are the metadata value of Dicom. 

You can find the standard Dicom tags from DICOM Tags. For e.g metadata key 0008|0008 denotes name as Image Type. Please check the link to get all the information on these keys.

The sample Dicom file used here is:


Convert the Dicom into png or jpg using SimpleITK:

Let's write the method which will convert the Dicom to PNG or JPG

 public static void convert(ImageFileReader imageFileReader, String outputImagePath) {
        Image image = imageFileReader.execute();
        SimpleITK.writeImage(image, outputImagePath);
    }
 public static void main(String[] args) {
        String imagePath = "input_path/N2D_0001.dcm";
        String outputImagePath = "output_path/test.png";
        try {
            ImageFileReader imageFileReader = getDcmImageFileReader(imagePath);
            Map<String, String> metadata = readMetadata(imageFileReader);
            convert(imageFileReader, outputImagePath);
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

The overall implementation looks as below:

package simpleitk;

import org.itk.simple.Image;
import org.itk.simple.ImageFileReader;
import org.itk.simple.SimpleITK;
import org.itk.simple.VectorString;

import java.util.LinkedHashMap;
import java.util.Map;

public class DicomReader {
    public static void main(String[] args) {
        String imagePath = "input_path/N2D_0001.dcm";
        String outputImagePath = "output_path/test.png";
        try {
            ImageFileReader imageFileReader = getDcmImageFileReader(imagePath);
            Map<String, String> metadata = readMetadata(imageFileReader);
            convert(imageFileReader, outputImagePath);
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    public static ImageFileReader getDcmImageFileReader(String imagePath) {
        ImageFileReader imageFileReader = new ImageFileReader();
        imageFileReader.setImageIO("GDCMImageIO");
        imageFileReader.setFileName(imagePath);
        return imageFileReader;
    }

    public static Map<String, String> readMetadata(ImageFileReader imageFileReader) {
        Map<String, String> metaData = new LinkedHashMap<>();
        imageFileReader.loadPrivateTagsOn();
        imageFileReader.readImageInformation();
        VectorString metaDataKeys = imageFileReader.getMetaDataKeys();
        long metaDataKeySize = metaDataKeys.size();
        System.out.println("Total meta data found: " + metaDataKeySize);
        for (int metaDataKeyIndex = 0; metaDataKeyIndex < metaDataKeySize; metaDataKeyIndex++) {
            String metaDataKey = metaDataKeys.get(metaDataKeyIndex);
            String metaDataValue = imageFileReader.getMetaData(metaDataKey);
            System.out.println("Key: " + metaDataKey + " Value: " + metaDataValue);
            metaData.put(metaDataKey, metaDataValue);
        }
        return metaData;
    }

    public static void convert(ImageFileReader imageFileReader, String outputImagePath) {
        Image image = imageFileReader.execute();
        SimpleITK.writeImage(image, outputImagePath);
    }
}

For SimpleITK tutorial, please refer to these docs.

Share:

Friday, January 7, 2022

How to set JVM arguments in IntelliJ Idea

In this tutorial, we will learn how we can set JVM argument in Intellij Idea. For e.g, if we need to set the JVM argument like -Djava.library.path=/path/to/native/library for native library.

For this, click on Add Configuration.   If you haven't created a configuration, then add one and assign the project working directory. Here we are adding 360learntocode as an example.

Now, if we don't see the VM options then click on Modify Option tab to add VM options.

After adding VM options, you can set the JVM arguments there and click apply and ok. If you want to add more than one argument use a comma to separate them.



Share:

Install SimpleITK on Linux/Ubuntu for Java Application

In this tutorial, we are going to learn how to install SimpleITK which is very handy for medical image analysis.

SimpleITK is a simplified programming interface to the algorithms and data structures of the Insight Toolkit (ITK). It supports bindings for multiple programming languages including C++, Python, R, Java, C#, Lua, Ruby, and TCL. These bindings enable scientists to develop image analysis workflows in the programming language they are most familiar with. The toolkit supports more than 15 different image file formats, provides over 280 image analysis filters, and implements a unified interface to the ITK intensity-based registration framework. you can check out official documentation from here.

For the windows system, we can find the prebuilt library where we can simply download and install it. But for Linux os, we need to build by ourselves.

Installation:

Download SimpleItk: 

Clone the SimpleITK from the github.  We can select the desired version from release and download or clone it.


git clone https://github.com/SimpleITK/SimpleITK.git

Now change to the SimpleITK directory:

cd SimpleITK

Install Cmake:

sudo apt-get  install cmake
Install Java:
sudo apt install openjdk-8-jdk

Build SimpleITK

mkdir SimpleITK-build
cd SimpleITK-build
sudo cmake ../SuperBuild

The SuperBuild generates make files that take care of downloading and building ITK. Now start the build

make -j4

Note: Be careful not to run out of memory during the build. We need 4GB of memory per core. For example, if we compile with 4 cores (e.g. make -j4) we need a machine with at least 16GB of RAM.

It will take some time. After the installation, you can find the .so library file which we are going to use. Also, you can find the .jar file for java under the created build folder.

First, we need to load the ITK .jar file in our project and .so file by providing the JVM argument as
Djava.library.path=/path/to/SimpleITKRuntime
Where, /path/to/SimpleITKRuntime is the directory that contains the .so file. Otherwise, you will get the following error
Exception in thread "main" java.lang.UnsatisfiedLinkError: no SimpleITKJava in java.library.path
	at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1860)
	at java.lang.Runtime.loadLibrary0(Runtime.java:871)
	at java.lang.System.loadLibrary(System.java:1124)
	at org.itk.simple.SimpleITKJNI.<clinit>(SimpleITKJNI.java:226)
	at org.itk.simple.SimpleITK.readImage(SimpleITK.java:475)
	at simpleitk.SimpleItkTest.main(SimpleItkTest.java:8)

Run the sample Java example

package simpleitk;

import org.itk.simple.Image;
import org.itk.simple.SimpleITK;

public class SimpleItkTest {
    public static void main(String[] args) {
		String inputImagePath = "/path/to/image";
		String outputImagePath = "/path/to/output/image";
        Image image = SimpleITK.readImage(inputImagePath);
        SimpleITK.writeImage(image, outputImagePath);
    }
}

This is a sample example for reading and writing images using simpleITK library.

Note if we are using the Gradle project, then we can add the .so library path as below

bootRun {
    jvmArgs('-Djava.library.path=/opt/SimpleItk/')
}
Where, /opt/SimpleItk/ is the directory which contains the .so file.

Share:

How to enable dark theme in google chrome dev tools

This is a quick tutorial on how to enable dark themes in google chrome dev tools.

1. Set up the dark theme from Settings:

First, inspect element to open the chrome dev tools by Ctrl + Shift + I

Click the Settings gear icon as below.



Go to Preferences  >>  Appearance  >> Theme  >>  select Dark from dropdown


Now, close the setting windows, we can see the Reload DevTools button as below. Click on it to refresh.


We can see the dark theme applied to the dev tools

2. Using Command line:

Navigate to dev tools using inspect element (Ctr + Shift + I)

Type the following command:

Ctr + Shift + P

We can see the popup dialog. Simply type and search dark in the search bar where we can click the option called Appearance Switch to dark theme 


After that, we can see the Reload DevTools button. Click on it to refresh.

Share:

Wednesday, January 5, 2022

How to record GIF on Ubuntu Linux

This is a quick tutorial on how we can record the animated GIF on a Linux Ubuntu machine.

 For this, there is a software called Peek, a simple screen recorder with an easy to use interface

Peek is very easy to create short screencasts of specific screen areas. We can simply place the Peek window over the area where we want to record and start recording.

Although it is optimized for recording and generating animated GIFs, we can also record WebM and MP4 videos too.

Let's look at how we can install it. For this open your terminal and type the following command

For Ubuntu:

sudo add-apt-repository ppa:peek-developers/stable
sudo apt update
sudo apt install peek

Here, we are adding PPA repositories required, while doing so use enter key to allow. Now, after running the above command you can simply open the peek recorder and start recording the GIFs animation.

The sample recording screen looks as below:



For Debian:

sudo apt install peek

For ElementaryOS:

sudo apt install software-properties-common
sudo add-apt-repository ppa:peek-developers/stable
sudo apt update
sudo apt install peek

For Arch Linux:

sudo pacman -S peek
Share:

How to create copy to clipboard in Vuetify VujeJs application

This is a quick tutorial on how we can add copy to clipboard functionality in the VueJs application.

In this example, we are going to create the invitation code where users can copy that code in the clipboard so that they can share it simply by copy-paste.

Let's create a simple component called CopyToClipBoard.vue and add a template

<template>
    <div>
        <v-card height="460" class="mt-8">
            <v-card-title class="justify-center mb-2 pb-0">
                <span class="text-center red--text">Your invite code</span>
            </v-card-title>
            <v-card-text class="text-center mb-0 pb-0">
                <v-chip color="grey" text-color="white" class="font-weight-bold">
                    <span class="inv-text">A0xU76E</span>
                    <v-divider
                            class="mx-4"
                            vertical
                            light
                    ></v-divider>
                    <v-tooltip top>
                        <template v-slot:activator="{ on, attrs }">
                  <span @click="copyCode" @mouseout="reset" style="cursor: pointer;" v-bind="attrs"
                        v-on="on">Copy</span>
                        </template>
                        <span>{{copyText}}</span>
                    </v-tooltip>
                </v-chip>
            </v-card-text>
        </v-card>
    </div>
</template>
Here, we are using vuetify UI framework, you can use your own HTML CSS. We are adding two events called @click for copy text to clipboard and @mouseout event for resetting the default value. 

Let's add the data:
created() {
    this.copyText = this.text
  },
data () {
    return {
      invitationCode:"A0xU76EJK",
      text: "Copy to invite",
      copyText: ''
    }
  },
Create the methods used in template:
methods : {
    async copyCode() {
      await navigator.clipboard.writeText(this.invitationCode);
      this.copyText = "Copied"
    },
    reset() {
      this.copyText = this.text
    }
  }
}
We are using vuetify tooltip to give the copy information. 

When the user clicks on the button it will call copyCode function and will copy in clipboard. In order to do so, we are using navigator.clipboard API which allows user to grant the website or app permission to access the clipboard. 

After that, we have to copy the invitationCode value so we pass this value as a parameter.

The sample demo looks like below:



The overall implementation looks as:
<template>
    <div>
        <v-card height="460" class="mt-8">
            <v-card-title class="justify-center mb-2 pb-0">
                <span class="text-center red--text">Your invite code</span>
            </v-card-title>
            <v-card-text class="text-center mb-0 pb-0">
                <v-chip color="grey" text-color="white" class="font-weight-bold">
                    <span class="inv-text">A0xU76E</span>
                    <v-divider
                            class="mx-4"
                            vertical
                            light
                    ></v-divider>
                    <v-tooltip top>
                        <template v-slot:activator="{ on, attrs }">
                  <span @click="copyCode" @mouseout="reset" style="cursor: pointer;" v-bind="attrs"
                        v-on="on">Copy</span>
                        </template>
                        <span>{{copyText}}</span>
                    </v-tooltip>
                </v-chip>
            </v-card-text>
        </v-card>
    </div>
</template>

<script>
    export default {
        name: "CopyToClipBoard",
        data () {
            return {
                invitationCode:"A0xU76EJK",
                text: "Copy to invite",
                copyText: ''
            }
        },
        created() {
            this.copyText = this.text
        },
        methods : {
            async copyCode() {
                await navigator.clipboard.writeText(this.invitationCode);
                this.copyText = "Copied"
            },
            reset() {
                this.copyText = this.text
            }
        }
    }
</script>

<style scoped>
    .inv-text {
        min-width: 150px;
        font-size: 20px;
    }
</style>
Share:

Tuesday, January 4, 2022

How to install icon fonts in vuetify vue application

This is a quick tutorial on how we can install icon fonts for material icons and font awesome

Although vuetify uses material design icons, that might not be sufficient all the time so we need to use some other library for it.

We can simply install a font by including the specified icon library CDN. For this, go to the project directory and inside it, you can see the index.html file under the public folder.  


Here, add the material icons and font awesome icon CDN link as below.

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900">
<link href="https://cdn.jsdelivr.net/npm/font-awesome@4.x/css/font-awesome.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css">
After adding this, we can simply use icons for e.g: 

From font awesome, simply use the fa- prefixed on icon name:
<v-icon left color="blue" size="50">fa-twitter</v-icon>
For google fonts, go to the google font and click the icon, we can see the icon font name similar as below, simply use the name.
<v-icon left color="blue" size="50">logout</v-icon>
Share: