This is the program of resizing image on mouse wheel scroll. Here I am using image-scaling-library for resizing image, This library gives good quality scaled images. Display Image using JScrollPane to handle overflow of image situations.

Adding Panel to JScrollPane

JFrame frmImageZoomIn = new JFrame();
JScrollPane scrollPane = new JScrollPane();
frmImageZoomIn.getContentPane().add(scrollPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
scrollPane.setViewportView(panel);

Adding Image to Panel

Icon imageIcon = new ImageIcon(inputImage);
label = new JLabel( imageIcon );
panel.add(label, BorderLayout.CENTER);

Zoom factor based  on Mouse Wheel Scroll

 Observe notches variable in below code. If user scrolls mouse wheel up then notches value will be -1 or else it will be 1. based on notches  value zoom factor value be changed. Based on zoom factor value image will be scaled
public void mouseWheelMoved(MouseWheelEvent e) {
    int notches = e.getWheelRotation();
    double temp = zoom - (notches * 0.2);
    // minimum zoom factor is 1.0
    temp = Math.max(temp, 1.0);
    if (temp != zoom) {
        zoom = temp;
        resizeImage();
    }
}

Complete Java Code

Update inputImage  variable with the your image file path and then run this code
import java.awt.EventQueue;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import com.mortennobel.imagescaling.ResampleOp;
import java.awt.event.MouseWheelListener;
import java.awt.event.MouseWheelEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageZoom {

    private JFrame frmImageZoomIn;
    private static final String inputImage = "C:\\my-pfl-pic.jpg"; // give image path here
    private JLabel label = null; 
    private double zoom = 1.0;  // zoom factor
    private BufferedImage image = null;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ImageZoom window = new ImageZoom();
                    window.frmImageZoomIn.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     * @throws IOException 
     */
    public ImageZoom() throws IOException {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     * @throws IOException 
     */
    private void initialize() throws IOException {
        frmImageZoomIn = new JFrame();
        frmImageZoomIn.setTitle("Image Zoom In and Zoom Out");
        frmImageZoomIn.setBounds(100, 100, 450, 300);
        frmImageZoomIn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        JScrollPane scrollPane = new JScrollPane();
        frmImageZoomIn.getContentPane().add(scrollPane, BorderLayout.CENTER);
        
        image = ImageIO.read(new File(inputImage));
        
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        
        // display image as icon 
        Icon imageIcon = new ImageIcon(inputImage);
        label = new JLabel( imageIcon );
        panel.add(label, BorderLayout.CENTER);
        
        panel.addMouseWheelListener(new MouseWheelListener() {
            public void mouseWheelMoved(MouseWheelEvent e) {
                int notches = e.getWheelRotation();
                double temp = zoom - (notches * 0.2);
                // minimum zoom factor is 1.0
                temp = Math.max(temp, 1.0);
                if (temp != zoom) {
                    zoom = temp;
                    resizeImage();
                }
            }
        });
        scrollPane.setViewportView(panel);
    }
    
    public void resizeImage() {
           System.out.println(zoom);
           ResampleOp  resampleOp = new ResampleOp((int)(image.getWidth()*zoom), (int)(image.getHeight()*zoom));
               BufferedImage resizedIcon = resampleOp.filter(image, null);
           Icon imageIcon = new ImageIcon(resizedIcon);
           label.setIcon(imageIcon);
        }


}
Read More
In previous article, I have written Angular JS directive for Mouse Wheel Scroll. In this article we will see how to implement Image Zoom In and Zoom Out using those Angular JS directives.

Program Flow

  1. Style of the element can be manipulated by ng-style pre-defined directive. Initialize style for the object imgStyle = {  width:"100px" } and zoomWidth = 100
  2.  On Mouse scroll up increment zoomWitdth by 20 and assign to imgStyle.width
  3.  On Mouse scroll down decrement zoomWitdth by 20 and assign to imgStyle.width 

Markup

<img src="/my-pic.jpg" ng-init="zoomWidth = 100;imgStyle = {width:'100px'}" ng-style="imgStyle" 
ng-mouse-wheel-up="zoomWidth = zoomWidth + 20; imgStyle.width = zoomWidth +'px'; "  
ng-mouse-wheel-down="zoomWidth = zoomWidth - 20;imgStyle.width = zoomWidth  +'px'; "/>

Script

var myApp = angular.module('myApp', []);


function MyCtrl($scope) {
  // controller code here
}

myApp.directive('ngMouseWheelUp', function() {
        return function(scope, element, attrs) {
            element.bind("DOMMouseScroll mousewheel onmousewheel", function(event) {
                   
                        // cross-browser wheel delta
                        var event = window.event || event; // old IE support
                        var delta = Math.max(-1, Math.min(1, (event.wheelDelta || -event.detail)));
                
                        if(delta > 0) {
                            scope.$apply(function(){
                                scope.$eval(attrs.ngMouseWheelUp);
                            });
                        
                          // for IE
                          event.returnValue = false;
                          // for Chrome and Firefox
                          if(event.preventDefault) event.preventDefault();                        
                       }
            });
        };
});


myApp.directive('ngMouseWheelDown', function() {
        return function(scope, element, attrs) {
            element.bind("DOMMouseScroll mousewheel onmousewheel", function(event) {
                   
                        // cross-browser wheel delta
                        var event = window.event || event; // old IE support
                        var delta = Math.max(-1, Math.min(1, (event.wheelDelta || -event.detail)));
                
                        if(delta < 0) {
                            scope.$apply(function(){
                                scope.$eval(attrs.ngMouseWheelDown);
                            });

                          // for IE
                          event.returnValue = false;
                          // for Chrome and Firefox
                          if(event.preventDefault) event.preventDefault();                        
                       }
            });
        };
});
Read More
I found a way to implement mouse wheel scroll event with hamster.js which is complicated and costly process. So I came up with simple solution with less code. Here I have created two directives, one is for mouse scroll up event and another is for mouse scroll down event.
You can use these directives for image zoom-in and zoom-out as like shown in this article. Element binds to event DOMMouseScroll ( for firefox ), mousewheel ( for chrome),  onmousewheel (for IE)

Directive for Mouse Wheel Scroll Up

HTML Usage

<div ng-mouse-wheel-up="..expression here..">........</div>

Script

myApp.directive('ngMouseWheelUp', function() {
        return function(scope, element, attrs) {
            element.bind("DOMMouseScroll mousewheel onmousewheel", function(event) {
                   
                        // cross-browser wheel delta
                        var event = window.event || event; // old IE support
                        var delta = Math.max(-1, Math.min(1, (event.wheelDelta || -event.detail)));
                
                        if(delta > 0) {
                            scope.$apply(function(){
                                scope.$eval(attrs.ngMouseWheelUp);
                            });
                        
                            // for IE
                            event.returnValue = false;
                            // for Chrome and Firefox
                            if(event.preventDefault) {
                                event.preventDefault();                        
                            }

                        }
            });
        };
});

Directive for Mouse Wheel Scroll Down

HTML Usage

<div ng-mouse-wheel-down="..expression here..">........</div>

Script

myApp.directive('ngMouseWheelDown', function() {
        return function(scope, element, attrs) {
            element.bind("DOMMouseScroll mousewheel onmousewheel", function(event) {
                   
                        // cross-browser wheel delta
                        var event = window.event || event; // old IE support
                        var delta = Math.max(-1, Math.min(1, (event.wheelDelta || -event.detail)));
                
                        if(delta < 0) {
                            scope.$apply(function(){
                                scope.$eval(attrs.ngMouseWheelDown);
                            });
                        
                            // for IE
                            event.returnValue = false;
                            // for Chrome and Firefox
                            if(event.preventDefault)  {
                                event.preventDefault();
                            }

                        }
            });
        };
});
Read More
We can select rectangular area of an image using  Image editing tools. Here in this article, I am going to implement this feature with Java.

Program Flow

  1. Create one panel to display only image using graphics
  2. Implement mousepressed, mousereleased and mousedrag events and create create rectangular shapes based on these mouse events
  3. Get sub image of main image with coordinates from above selection
  4. Update selected area panel with above sub image 

ImagePanel.java

This class extends JPanel. It implements mouse events and it is responsible for user selection of image. Whenever user select rectangular area, it will trigger main panel to update selected region.
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class ImagePanel extends JPanel {
    private static final long serialVersionUID = 1L;
    private BufferedImage image;
    private Shape shape = null;
    Point startDrag, endDrag;

    public ImagePanel( String inputImage, MainFrame mf1) throws IOException {
        final MainFrame mf = mf1;
        image = ImageIO.read(new File(inputImage));
        this.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                startDrag = new Point(e.getX(), e.getY());
                endDrag = startDrag;
                repaint();
            }

            public void mouseReleased(MouseEvent e) {
                if(endDrag!=null && startDrag!=null) {
                    try {
                        shape = makeRectangle(startDrag.x, startDrag.y, e.getX(),
                                e.getY());
                        mf.updateSelectedRegion(image.getSubimage(startDrag.x, startDrag.y, e.getX()-startDrag.x, e.getY()-startDrag.y));   
                        startDrag = null;
                        endDrag = null;
                        repaint();
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }   
                }
            }
        });

        this.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                endDrag = new Point(e.getX(), e.getY());
                repaint();
            }   
        });
    }

    
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.drawImage(image, 0, 0, null);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        
        g2.setStroke(new BasicStroke(2));
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
                0.50f));

        if (shape != null) {
            g2.setPaint(Color.BLACK);
            g2.draw(shape);
            g2.setPaint(Color.YELLOW);
            g2.fill(shape);
        }
        
        if (startDrag != null && endDrag != null) {
            g2.setPaint(Color.LIGHT_GRAY);
            Shape r = makeRectangle(startDrag.x, startDrag.y, endDrag.x,
                    endDrag.y);
            g2.draw(r);
        }
        
    }

    private Rectangle2D.Float makeRectangle(int x1, int y1, int x2, int y2) {
        return new Rectangle2D.Float(Math.min(x1, x2), Math.min(y1, y2),
                Math.abs(x1 - x2), Math.abs(y1 - y2));
    }
    
}

MainFrame.java

This is the main window which has Image Panel and Selected area panel. Here update imagePath variable with your image file path.
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;

public class MainFrame {

    private JFrame frmSelectAreaIn;
    private JPanel selectedAreaPanel;
    private String imagePath="C:\\inputImage.jpg";
    
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame window = new MainFrame();
                    window.frmSelectAreaIn.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     * @throws IOException 
     */
    public MainFrame() throws IOException {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     * @throws IOException 
     */
    private void initialize() throws IOException {
        frmSelectAreaIn = new JFrame();
        frmSelectAreaIn.setTitle("Select Area In Image");
        frmSelectAreaIn.setBounds(100, 100, 708, 370);
        frmSelectAreaIn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmSelectAreaIn.getContentPane().setLayout(null);
        
        // Image Panel display selected area of the image
        selectedAreaPanel = new JPanel();
        selectedAreaPanel.setBounds(469, 36, 221, 289);
        frmSelectAreaIn.getContentPane().add(selectedAreaPanel);
        
        // Image Panel display image with graphics
        JPanel mainPanel = new ImagePanel(imagePath, this);
        mainPanel.setBounds(10, 11, 449, 314);
        frmSelectAreaIn.getContentPane().add(mainPanel);
        
        JLabel lblSelectedArea = new JLabel("Selected Area");
        lblSelectedArea.setBounds(469, 11, 221, 14);
        frmSelectAreaIn.getContentPane().add(lblSelectedArea);
    }

    // function to update selected region of the image
    public void updateSelectedRegion(BufferedImage bufferedImage) {
        Graphics g = selectedAreaPanel.getGraphics();
        g.clearRect(0, 0, 221, 289);
        g.drawImage(bufferedImage, 0, 0, null);
    }
}
Read More
I have observed the content links with images in facebook wrong size. Facebook has given some specifications for images with content links. To get best look and feel, we need to optimize our images. Whatever images you are sharing, convert that image size into optimized image size.

Facebook Optimized Image Size 

1200  X  300
  600  X  315
  600  X  600
If you create an Image of size 730 X 500 ,then what you have to do optimize the image for facebook. You might need photoshop or any other image manipulation tool for adjusting size.  Here I am giving you the quick way of doing this by java program.

Java Library :

For quality image scaling, I have used java-image-scaling library.

Java Code

Replace destinationDir with your destination folder path to save images. Give your image path to sourceImage
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import com.mortennobel.imagescaling.ResampleOp;

public class FacebookLinkSharedImages {
  static String destinationDir = "C:\\fbIcons";
  static String sourceImage = "C:\\facebook1.png";
  static ArrayList<Dimension> dimensions = new ArrayList<Dimension>();
  
  public static void main(String[] args) throws IOException {
      dimensions.add(new Dimension(1200,630));
      dimensions.add(new Dimension(600,315));
      dimensions.add(new Dimension(600,600));
      readFile(destinationDir);
  }
  
    public static void readFile(String path) throws IOException {
        File dir = new File(destinationDir);
        if(!dir.exists()) {
            dir.mkdirs();
        }
        BufferedImage bufferedImg = ImageIO.read(new File(sourceImage));
        for(Dimension dim : dimensions) {
            String destFilePath = destinationDir+"\\icon"+(int)dim.getWidth()+"X"+(int)dim.getHeight()+".png";
            File destFile = new File(destFilePath);
            if(!destFile.exists()) {
                  destFile.createNewFile();
            }
            System.out.println("File "+ destFile.getAbsolutePath());
            ImageIO.write(createScreenImage(bufferedImg,(int)dim.getWidth(),(int)dim.getHeight()), "png", destFile);    
        }
    } 
    
      private static BufferedImage createScreenImage(BufferedImage appIconImg, int width, int height) throws IOException {
          int type = appIconImg.getType() == 0? BufferedImage.TYPE_INT_ARGB : appIconImg.getType();
          BufferedImage newPGScreen = new BufferedImage(width, height, type);
          Graphics2D g = newPGScreen.createGraphics();
          g.setColor(new Color(255,255,255));
          g.fillRect(0, 0, width, height);
          double tw = (double)width, th = (double)height;
          int iw = appIconImg.getWidth();
          int ih = appIconImg.getHeight();
          double iwf = (double)(tw / iw);
          double ihf = (double)(th / ih);
          double imf = iwf < ihf ? iwf:ihf;
          int tfw = (int)(imf * iw);
          int tfh = (int)(imf * ih);
          ResampleOp  resampleOp = new ResampleOp(tfw, tfh);
          BufferedImage resizedIcon = resampleOp.filter(appIconImg, null);
          g.drawImage(resizedIcon, (int)((tw - tfw)/2), (int)((th - tfh)/2) , null);
          g.dispose();
          return newPGScreen;
      }
  
}
Read More
Java is not providing any option to remember last browsed directory. So we have to save the last browsed directory in global static variable of Util class and use that location at the time initiating new JFileChooser class.

Util Class Structure 

Here observe the code. We are saving parent folder of selected file or directory using setLastDir method and Returning the JFileChooser with last browsed directory path using getFileChooser method
public class Utils {
    private static String lastDir = null;

    public static JFileChooser getFileChooser() {
        if(lastDir != null) {
            JFileChooser fc = new JFileChooser(lastDir);
            return fc;
        } else {
            JFileChooser fc = new JFileChooser();
            return fc;
        }
    }

    public static void setLastDir(File file) {
        lastDir = file.getParent();
    }
}

Usage

Get JFileChooser from Utils class and send selected file to setLastDir method.
JFileChooser fc = Utils.getFileChooser();
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
     Utils.setLastDir(fc.getSelectedFile());
     ......
} else {
     System.out.println("Open command cancelled by user.");
}
Read More
Sometimes while doing programming, I need to download some jars, but the network settings blocks it. That is really embarrassing So I came with a java program which downloads file for me using third party server.  To implement this program you need to download apache-commons-io library. This program is simple servlet.

Program flow

  1. Get file URL from user
  2. Send it to proxy servlet
  3. Servlet will open input stream for that URL and write content to servlet output stream
  4. User will get file downloaded

Get file URL from user

String fileURL = request.getParameter("url");

Open Input Stream 

URL url = new URL(fileURL);
InputStream is = url.openStream();

Write Into Output stream

ServletOutputStream out = response.getOutputStream();
out.write(IOUtils.toByteArray(is));
out.flush();
out.close()

Complete Servlet Code

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;


/**
 * Servlet implementation class ProxyFile
 */
public class ProxyFile extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProxyFile() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // get file name from parameter
        String fileURL = request.getParameter("url");
        URL url;
        InputStream is = null;
        try {
            // get name of the file
            String[] names = fileURL.split("/");
            String fileName = names[names.length - 1];
            
            // open URL stream
            url = new URL(fileURL);
            is = url.openStream();
            
            // set response header
            response.setContentType("application/download");
            response.setHeader("Content-Transfer-Encoding", "binary");
            response.setHeader("Content-Disposition","attachment; filename=\"" + fileName+"\"");
            
            // write into servlet output stream  
            ServletOutputStream out = response.getOutputStream();
            out.write(IOUtils.toByteArray(is));
            out.flush();
            out.close();
        } catch (MalformedURLException mue) {
            mue.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException ioe) {
            }
        }

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // forward to doGet
        doGet(request, response);
    }

}

web.xml Configuration

  <servlet>
    <description></description>
    <display-name>ProxyFile</display-name>
    <servlet-name>ProxyFile</servlet-name>
    <servlet-class>demo.sl.ProxyFile</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ProxyFile</servlet-name>
    <url-pattern>/ProxyFile</url-pattern>
  </servlet-mapping>
Read More
When you provide an option to select an item in list of items then you must show the difference between selected items and un-selected items. To show this difference, changing in the background color or text color of selected item is necessary. The user must recognize the items that are select-able, To implement this feature we need to change the background-color or text-color on mouse over. Lets do this with example.

CSS

Here selectedItem class will give background color to selected item
.item {
  padding:12px;
  border:1px solid #ccc;
  cursor:pointer;
}

.hoverItem:hover {
  background-color:#eeeeee;
}

.selectedItem {
  background-color:#dfdfdf;
}

Markup

record.classes holds the array of classes.  You can learn about adding and removing classes from here
<html ng-app="" ng-controller="myCtrl">
.....
<div ng-click="selectItem($index)" ng-class="record.classes" ng-repeat="record in records track by $index">
  {{record.value}}
</div>
.....
</html>

Script

The logic is simple. When user clicks on an item we will add selected class and remove hover class
function myCtrl($scope) {
    // initialize data
    $scope.records = [];
    for(var i=0;i<5;i++) {
       $scope.records.push(
         { 
           value: "record "+i,
           classes : ["item", "hoverItem"]
         }
       );     
    }

    // when user selected item
    $scope.selectItem = function(index) {
       for(var i=0;i<$scope.records.length;i++) {
          if(index === i) {
            $scope.records[i].classes.pop('hoverItem');
            $scope.records[i].classes.push('selectedItem');
          } else {
            $scope.records[i].classes.pop('selectedItem');
            $scope.records[i].classes.push('hoverItem');
          }
       } 
    };
}
Read More

Blogroll


Follow this blog by Email

Popular Posts