Showing posts with label swing. Show all posts
Showing posts with label swing. Show all posts

Saturday 25 January 2014

DicomMultiframePlayer in JAVA

package packageTestDcm4che3;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;

import javax.imageio.ImageReader;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.dcm4che.imageio.plugins.dcm.DicomImageReadParam;
import org.dcm4che.imageio.plugins.dcm.DicomImageReader;

/**
 * Plays a multiframe DICOM instance.
 *
 * @author dimitri PIANETA
 *
 * <p>The code for this came from <a href="http://samucs.blogspot.com" target="_blank">http://samucs.blogspot.com</a>
 *    and was dated 6-January-2010.</p>
 *
 * <p> code modification 14 January 2014 for dcm4che3 <p>
 */   
public class DicomMultiframePlayer extends JFrame implements ActionListener, Runnable {
   
    private static final long serialVersionUID = 1L;
    private JLabel fileLabel;
    /**
     * Will contain name of file to be read.
     */
    private JTextField fileField;
    /**
     * Triggers process for selecting file to be read.
     * @see #actionPerformed(ActionEvent)
     */
    private JButton btnChoose;
    /**
     * Starts playing of images.
     * @see #actionPerformed(ActionEvent)
     */
    private JButton btnPlay;
    /**
     * Pauses playing of images.
     * @see #actionPerformed(ActionEvent)
     */
    private JButton btnPause;
    /**
     * Halts playing of images.
     * @see #actionPerformed(ActionEvent)
     */
    private JButton btnStop;
    private JButton btnExit;   
    private Vector<BufferedImage> images;
    private ImagePanel imagePanel;   
    private boolean stop;
    private int currentFrame;
   
       
        private int frame = 1;

       
       
       
          private final ImageReader imageReader =
            ImageIO.getImageReadersByFormatName("DICOM").next();
       
       
    public DicomMultiframePlayer() {
        super("DICOM Multiframe Player using dcm4che - by samucs-dev");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.getContentPane().setLayout(new BorderLayout());
       
        images = new Vector<BufferedImage>();
        imagePanel = new ImagePanel();
       
        fileLabel = new JLabel("File:");
        fileField = new JTextField(30);
        btnChoose = this.createJButton(25, 25, "...");
       
        btnPlay = this.createJButton(80,25,"Play");
        btnPause = this.createJButton(80,25,"Pause");
        btnStop = this.createJButton(80,25,"Stop");       
        btnExit = this.createJButton(80,25,"Exit");
        btnPause.setEnabled(false);
        btnStop.setEnabled(false);
       
        JPanel panelNorth = new JPanel();
        panelNorth.add(fileLabel);
        panelNorth.add(fileField);
        panelNorth.add(btnChoose);
       
        JPanel panelSouth = new JPanel();
        panelSouth.add(btnPlay);
        panelSouth.add(btnPause);
        panelSouth.add(btnStop);
        panelSouth.add(btnExit);
       
        this.getContentPane().add(panelNorth, BorderLayout.NORTH);
        this.getContentPane().add(imagePanel, BorderLayout.CENTER);
        this.getContentPane().add(panelSouth, BorderLayout.SOUTH);
       
        this.setSize(new Dimension(500,500));
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }
    /**
     * Plays the frames in order.
     *
     * <p>I removed the Override annotation.</p>
     */
    // @Override
    public void run() {
        while(true) {
            if (!btnPlay.isEnabled()) {               
                if (stop) break;               
                currentFrame++;
                if (currentFrame == images.size())
                    currentFrame = 0;
                imagePanel.setImage(images.get(currentFrame));               
                try {
                    Thread.sleep(70);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * Detects clicking of button and carries out appropriate action.
     *
     * <p>I removed the Override annotation.</p>
     */
    // @Override
    public void actionPerformed(ActionEvent e) {       
        if (e.getSource().equals(btnChoose)) {
            JFileChooser chooser = new JFileChooser();
            int action = chooser.showOpenDialog(this);
            switch(action) {
                case JFileChooser.APPROVE_OPTION:
                    this.openFile(chooser.getSelectedFile());
                    break;
                case JFileChooser.CANCEL_OPTION:
                    return;
            }
        }       
        if (e.getSource().equals(btnPlay)) {
            btnPlay.setEnabled(false);
            btnPause.setEnabled(true);
            btnStop.setEnabled(true);
            stop = false;
            new Thread(this).start();           
        }
        if (e.getSource().equals(btnPause)) {
            btnPlay.setEnabled(true);
            btnPause.setEnabled(false);
            btnStop.setEnabled(true);
            stop = false;
        }
        if (e.getSource().equals(btnStop)) {
            btnPlay.setEnabled(true);
            btnPause.setEnabled(false);
            btnStop.setEnabled(false);
            stop = true;
            currentFrame = 0;
            imagePanel.setImage(images.get(0));           
        }
        if (e.getSource().equals(btnExit)) {
            System.exit(0);
        }
    }
    /**
     * Creates JButton objects on window.
     * @param width width of button in pixels.
     * @param height height of button in pixels
     * @param text text to appear in button
     * @return JButton object
     */
    private JButton createJButton(int width, int height, String text) {
        JButton b = new JButton(text);
        b.setMinimumSize(new Dimension(width, height));
        b.setMaximumSize(new Dimension(width, height));
        b.setPreferredSize(new Dimension(width, height));
        b.addActionListener(this);
        return b;
    }
    /**
     * Reads the contents of the dicom file
     * @param file file to be opened
     * @see org.dcm4che2.imageioimpl.plugins.dcm.DicomImageReaderSpi
     * @see org.dcm4che2.imageioimpl.plugins.dcm.DicomImageReader
     */
    private void openFile(File file) {
        images.clear();
        try {
           
                   
                       
            int numFrames =setNumber(file);
            //System.out.println("DICOM image has "+ numFrames +" frames...");           
            System.out.println("Extracting frames...");
            for (int i=0; i < numFrames; i++) {
                     
                       
                          
                BufferedImage img =  chargeImageDicomBufferise(file,i);
                images.add(img);
                System.out.println(" > Frame "+ (i+1));
            }           
            System.out.println("Finished.");
        } catch(Exception e) {
            e.printStackTrace();
            imagePanel.setImage(null);
            return;
        }
        stop = false;
        currentFrame = 0;
        imagePanel.setImage(images.get(0));
    }

     
       
        /**
         * Building BufferingImage
         * @param file : input file
         * @param value : number frame
         * @return
         * @throws IOException
         */
       
        public BufferedImage chargeImageDicomBufferise(File file, int value) throws IOException  {

                Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");//sp?cifie l'image

                              
                         

              ImageReader readers = iter.next();//on se d?place dans l'image dicom

         DicomImageReadParam   param1 =  (DicomImageReadParam) readers.getDefaultReadParam();//return DicomImageReadParam
               //    Adjust the values of Rows and Columns in it and add a Pixel Data attribute with the byte array from the DataBuffer of the scaled Raster

                ImageInputStream iis = ImageIO.createImageInputStream(file);

             readers.setInput(iis, false);//sets the input source to use the given ImageInputSteam or other  Object

               BufferedImage image = readers.read(value,param1);//BufferedImage image = reader.read(frameNumber, param); frameNumber = int qui est l'imageIndex
                System.out.println(image);//affichage au terminal des caract?res de l'image

                readers.dispose();//Releases all of the native sreen resources used by this Window, its subcomponents, and all of its owned children
              return  image;

            }
   
         /**
 *  Find number frame
 * @param file : input file
 * @return numbre frame in Dicom
 * @throws IOException
 */
   public int setNumber(File file) throws IOException  {

            /* Parcourt le fichier dicom*/
             Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");//sp?cifie l'image
           ImageReader readers = (ImageReader)iter.next();//on se d?place dans l'image dicom

            DicomImageReadParam   param1=  (DicomImageReadParam) readers.getDefaultReadParam();//return DicomImageReadParam
           //    Adjust the values of Rows and Columns in it and add a Pixel Data attribute with the byte array from the DataBuffer of the scaled Raster

            ImageInputStream iis = ImageIO.createImageInputStream(file);//cr?ation du fichier image


           readers.setInput(iis, false);//sets the input source to use the given ImageInputSteam or other  Object

            //iis.close();
            int  number = readers.getNumImages(true);//numberOfFrame on a "readers" qui doit ?tre DicomImage
            System.out.println(number);//return NumberOfFrame (Tag : (0028, 0008))
           return  number;
        }
   
   
   
    private class ImagePanel extends JPanel {
        private static final long serialVersionUID = 1L;
        private BufferedImage image;
        private int frame;
        public ImagePanel() {
            super();
            this.setPreferredSize(new Dimension(1024,1024));
            this.setBackground(Color.black);           
        }
        public void setImage(BufferedImage image) {
            this.image = image;
            this.updateUI();
        }
        @Override
        public void paint(Graphics g) {
            if (this.image != null) {
                g.drawImage(this.image, 0, 0, image.getWidth(), image.getHeight(), null);
            }
        }
   
        };

    public static void main(String[] args) {
        new DicomMultiframePlayer();
    }

}

Tuesday 3 December 2013

BufferedImage pixel value issue RGB Value for each PIXEL

package com..jpt.dream.miscl;

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.imageio.ImageIO;

import java.net.URL;

class ImageTest {

public static int getRGB(int x, int y, BufferedImage image) {
return image.getRGB(x, y);
}

public static Color getColor(int x, int y, BufferedImage image) {
int rgb = image.getRGB(x, y);
Color c = new Color(rgb);
return c;
}

public static void main(String[] args) throws Exception {
BufferedImage bi = ImageIO
.read(new URL("http://i.imgur.com/WMfeU.png"));
int w = bi.getWidth();
int h = bi.getHeight();

final BufferedImage bi2 = new BufferedImage(w, h,
BufferedImage.TYPE_INT_RGB);

for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
int rgb = getRGB(x, y, bi);
if (x % 20 == 0 && y % 20 == 0) {
System.out.println(getColor(x, y, bi));
}
bi2.setRGB(x, y, rgb);
}
}

SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(
bi2)));
}
});

}
}

Get and set pixels on a Buffered Image


In this tutorial we are going to show you how to set and get the RGB value of each pixel of a Buffered Image. This is particularly useful when you want to perform several operation on images based on the RGB values of each individual image. Or if you want your UI to interact in some way according to the values of the pixel that the user points to.
In short in order to flip an image one should take the following steps:
  • Load an image from a source usingToolkit.getDefaultToolkit().getImage method
  • Use an ImageObserver to monitor the loading of the image. When the image is fully load the user will be notified
  • Create a buffed image from the source image with a format more close to the custom display environment using GraphicsEnvironmentGraphicsDevice and GraphicsConfiguration to perform several image configurations
  • Use Image.getRGB(x,y) to get the RGB value of a specific pixel and Image.setRGB(x, y, rgbValue) to set the RGB value of the pixel.
  • And simply paint the buffered image in a new Frame
Let’s take a look at the code snippet that follows


package com.myDrea,.snippets.desktop;

import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;

public class BufferedImagePixels {

  static boolean imageLoaded = false;

  public static void main(String[] args) {

// The ImageObserver implementation to observe loading of the image

ImageObserver myImageObserver = new ImageObserver() {

  public boolean imageUpdate(Image image, int flags, int x, int y, int width, int height) {

    if ((flags & ALLBITS) != 0) {

imageLoaded = true;

System.out.println("Image loading finished!");

return false;

    }

    return true;

  }

};

// The image URL - change to where your image file is located!

String imageURL = "image.png";

/**

 * This call returns immediately and pixels are loaded in the background

 * We use an ImageObserver to be notified when the loading of the image

 * is complete

 */

Image sourceImage = Toolkit.getDefaultToolkit().getImage(imageURL);

sourceImage.getWidth(myImageObserver);

// We wait until the image is fully loaded

while (!imageLoaded) {

    try {

  Thread.sleep(100);

    } catch (InterruptedException e) {

    }

}

// Create a buffered image from the source image with a format that's compatible with the screen

GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();

GraphicsDevice graphicsDevice = graphicsEnvironment.getDefaultScreenDevice();

GraphicsConfiguration graphicsConfiguration = graphicsDevice.getDefaultConfiguration();

// If the source image has no alpha info use Transparency.OPAQUE instead

BufferedImage image = graphicsConfiguration.createCompatibleImage(sourceImage.getWidth(null), sourceImage.getHeight(null), Transparency.BITMASK);

// Copy image to buffered image

Graphics2D graphics = image.createGraphics();

// Paint the image onto the buffered image

graphics.drawImage(sourceImage, 0, 0, null);

graphics.dispose();

int x = 10;

int y = 10;

// Get a pixel

int rgb = image.getRGB(x, y);

System.out.println("Pixel at [" + x + "," + y + "] RGB : " + rgb);

// Get all the pixels

int w = image.getWidth(null);

int h = image.getHeight(null);

int[] rgbs = new int[w*h];

image.getRGB(0, 0, w, h, rgbs, 0, w);

// Set a pixel

rgb = 0xFF00FF00; // green

image.setRGB(x, y, rgb);

  }

}

Monday 21 October 2013

Showing only close button on the JFrame undecorated


public class TestUndecoratedFrame {

    public static void main(String[] args) {
        new TestUndecoratedFrame();
    }

    public TestUndecoratedFrame() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                TitlePane titlePane = new TitlePane();

                JFrame frame = new JFrame("Testing");
                frame.setUndecorated(true);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                ((JComponent)frame.getContentPane()).setBorder(new LineBorder(Color.BLACK));
                frame.add(titlePane, BorderLayout.NORTH);
                frame.add(new JLabel("This is your content", JLabel.CENTER));
                frame.setSize(200, 200);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TitlePane extends JPanel {

        public TitlePane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1;
            gbc.anchor = GridBagConstraints.EAST;
            add(new CloseControl(), gbc);
        }
    }

    public class CloseControl extends JButton {

        public CloseControl() {
            setBorderPainted(false);
            setContentAreaFilled(false);
            setFocusPainted(false);
            setOpaque(false);
            setBorder(new EmptyBorder(0, 0, 8, 12));
            try {
                setRolloverIcon(new ImageIcon(ImageIO.read(getClass().getResource("/Highlighted.png"))));
                setRolloverEnabled(true);
                setIcon(new ImageIcon(ImageIO.read(getClass().getResource("/Normal.png"))));
            } catch (IOException ex) {
                Logger.getLogger(TestUndecoratedFrame.class.getName()).log(Level.SEVERE, null, ex);
            }

            addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    SwingUtilities.getWindowAncestor(CloseControl.this).dispose();
                }
            });
        }
    }
}

Friday 30 August 2013

Swing: Drawing Arcs Between Adjacent Edges of Triangle






import javax.swing.JComponent;
import javax.swing.JFrame;
import java.awt.geom.*;
import java.awt.*;
import java.util.*;

class MyCanvas extends JComponent {
    int a, supb, b, c, length, r;
    double x1, y1, x2, y2, x3, y3;
    Random random = new Random();

    public MyCanvas() {
            a = random.nextInt(80 - 30) + 30;
            supb = random.nextInt(120 - 70) + 100;
            b = 180 - supb;
            c = 180 - a - b;
            length = random.nextInt(150 - 100) + 100;
            x1 = 0;
            y1 = 0;
            r = 20;
            x2 = x1 + length;
            y2 = y1;
            x3 = (x1 + Math.cos(Math.toRadians(-a)) * length);
            y3 = (y1 + Math.sin(Math.toRadians(-a)) * length);
    }

    public void paintComponent(Graphics g2) {
            float dx1, dy1, ang1, dx2, dy2, ang2, ang3;
            Graphics2D g = (Graphics2D) g2;
            AffineTransform oldt = g.getTransform();

            Shape shape = getTriangle(x1, y1, x2, y2, x3, y3);

            Rectangle2D bounds = shape.getBounds2D();

            double height = bounds.getHeight();
            double width = bounds.getWidth();
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
            g.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_BUTT,
                            BasicStroke.JOIN_BEVEL));
            g.translate((this.getWidth() - width) / 2,
                            (this.getHeight() - height) / 2);
            g.translate(-bounds.getX(), -bounds.getY());

            dy1 = (float) (y3 - y1);
            dx1 = (float) (x3 - x1);
            ang1 = (float) (Math.atan((float)(dy1 / dx1)) * 180 / Math.PI);

            ang1 = (float) Math.abs(ang1);

            dy2 = (float) (y2 - y3);
            dx2 = (float) (x2 - x3);
            ang2 = (float) (Math.atan((float)(dy2 / dx2)) * 180 / Math.PI);

            ang2 = (float) Math.abs(ang2);

    ang3 = (float) (180-ang2-ang1);

            g.setColor(Color.BLACK);
            g.draw(shape);
            g.setColor(Color.RED);
            g.draw(new Arc2D.Double(x1 - r, y1 - r, 2 * r, 2 * r, 0, ang1, Arc2D.OPEN));
            g.setColor(Color.GREEN);
            g.draw(new Arc2D.Double(x2 - r, y2 - r, 2 * r, 2 * r, (180 - ang2), ang2,
                            Arc2D.OPEN));
            g.setColor(Color.RED);
            g.draw(new Arc2D.Double(x3 - r, y3 - r, 2 * r, 2 * r, -180 + a, ang3,
                            Arc2D.OPEN));
            g.setTransform(oldt);
    }

    private Shape getTriangle(double x1, double y1, double x2, double y2,
                    double x3, double y3) {
            GeneralPath gp = new GeneralPath();
            gp.moveTo(x1, y1);
            gp.lineTo(x2, y2);
            gp.lineTo(x3, y3);
            gp.closePath();
            return gp;
    }
}

public class TrianglePanel {
        public static void main(String[] a) {
                JFrame window = new JFrame();
                window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                window.setBounds(30, 30, 300, 300);
                window.getContentPane().add(new MyCanvas());
                window.setVisible(true);
        }
}