How to have 2DGraphics zoom into a specific part of an image?

I am trying to mess around with2DGraphics and affinetramsform to zoom into a section of an image but i have no luck doing it. Can someone help me out? Lets say I want to zoom into the coordinates (200,300) and (400,600) . I know DrawImage has a method that does this but does 2DGraphics have it too or affinetransform? I havent see anything like it yet. thanks

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.*;
public class ZoomIt extends JPanel {
    BufferedImage image;
    Dimension size;
    Rectangle clip;
    AffineTransform at = new AffineTransform();
    public ZoomIt(BufferedImage image) {
        this.image = image;
        size = new Dimension(image.getWidth(), image.getHeight());
        clip = new Rectangle(100,100,200,200);
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        g2.drawRenderedImage(image, at);
        g2.setColor(Color.red);
        g2.draw(clip);
        //g2.setPaint(Color.blue);
        //g2.draw(at.createTransformedShape(clip));
    public Dimension getPreferredSize() {
        return size;
    private void zoomToClip() {
        // Viewport size.
        Dimension viewSize = ((JViewport)getParent()).getExtentSize();
        // Component dimensions.
        int w = getWidth();
        int h = getHeight();
        // Scale the clip to fit the viewport.
        double xScale = (double)viewSize.width/clip.width;
        double yScale = (double)viewSize.height/clip.height;
        double scale = Math.min(xScale, yScale);
        at.setToScale(scale, scale);
        size.width = (int)(scale*size.width);
        size.height = (int)(scale*size.height);
        revalidate();
    private void reset() {
        at.setToIdentity();
        size.setSize(image.getWidth(), image.getHeight());
        revalidate();
    private JPanel getControlPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.weightx = 1.0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        panel.add(getZoomControls(), gbc);
        panel.add(getClipControls(), gbc);
        return panel;
    private JPanel getZoomControls() {
        final JButton zoom = new JButton("zoom");
        final JButton reset = new JButton("reset");
        ActionListener al = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JButton button = (JButton)e.getSource();
                if(button == zoom)
                    zoomToClip();
                if(button == reset)
                    reset();
                repaint();
        zoom.addActionListener(al);
        reset.addActionListener(al);
        JPanel panel = new JPanel();
        panel.add(zoom);
        panel.add(reset);
        return panel;
    private JPanel getClipControls() {
        int w = size.width;
        int h = size.height;
        SpinnerNumberModel xModel = new SpinnerNumberModel(100, 0, w/2, 1);
        final JSpinner xSpinner = new JSpinner(xModel);
        SpinnerNumberModel yModel = new SpinnerNumberModel(100, 0, h/2, 1);
        final JSpinner ySpinner = new JSpinner(yModel);
        SpinnerNumberModel wModel = new SpinnerNumberModel(200, 0, w, 1);
        final JSpinner wSpinner = new JSpinner(wModel);
        SpinnerNumberModel hModel = new SpinnerNumberModel(200, 0, h, 1);
        final JSpinner hSpinner = new JSpinner(hModel);
        ChangeListener cl = new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                JSpinner spinner = (JSpinner)e.getSource();
                int value = ((Integer)spinner.getValue()).intValue();
                if(spinner == xSpinner)
                    clip.x = value;
                if(spinner == ySpinner)
                    clip.y = value;
                if(spinner == wSpinner)
                    clip.width = value;
                if(spinner == hSpinner)
                    clip.height = value;
                repaint();
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(2,2,2,2);
        gbc.weightx = 1.0;
        addComponents(new JLabel("x"),      xSpinner, panel, gbc, cl);
        addComponents(new JLabel("y"),      ySpinner, panel, gbc, cl);
        addComponents(new JLabel("width"),  wSpinner, panel, gbc, cl);
        addComponents(new JLabel("height"), hSpinner, panel, gbc, cl);
        return panel;
    private void addComponents(Component c1, JSpinner s, Container c,
                               GridBagConstraints gbc, ChangeListener cl) {
        gbc.anchor = GridBagConstraints.EAST;
        c.add(c1, gbc);
        gbc.anchor = GridBagConstraints.WEST;
        c.add(s, gbc);
        s.addChangeListener(cl);
    public static void main(String[] args) throws IOException {
        String path = "images/owls.jpg";
        BufferedImage image = ImageIO.read(new File(path));
        ZoomIt test = new ZoomIt(image);
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new JScrollPane(test));
        f.getContentPane().add(test.getControlPanel(), "Last");
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
}

Similar Messages

  • How to zoom into a specific part of an image?

    I am trying to mess around with2DGraphics and affinetramsform to zoom into a section of an image but i have no luck doing it. Can someone help me out? Lets say I want to zoom into the coordinates (200,300) and (400,600) . I know DrawImage has a method that does this but does 2DGraphics have it too or affinetransform? I havent see anything like it yet. thanks

    you could check this
    http://www.javareference.com/jrexamples/viewexample.jsp?id=84
    it may help you

  • What's the easiest way to embed a video into a specific part of an image map?

    What's the easiest way to embed a video into a specific part of an image map?
    Anybody help? Is there a way to do this in Dreamweaver?

    One way would be to create your image map first. Then, use the CSS property position to position the div containing the video player relative to the image map or absolute to the page (depending on how your website layout is).
    Then, use an event listener (javascript) to enable the div holding the video player to show only when the specific area on the image map is clicked.

  • How to cast an Object into a specific type (Integer/String) at runtime

    Problem:
    How to cast an Object into a specific type (Integer/String) at runtime, where type is not known at compile time.
    Example:
    public class TestCode {
         public static Object func1()
    Integer i = new Integer(10); //or String str = new String("abc");
    Object temp= i; //or Object temp= str;
    return temp;
         public static void func2(Integer param1)
              //Performing some stuff
         public static void main(String args[])
         Object obj = func1();
    //cast obj into Integer at run time
         func2(Integer);
    Description:
    In example, func1() will be called first which will return an object. Returned object refer to an Integer object or an String object. Now at run time, I want to cast this object to the class its referring to (Integer or String).
    For e.g., if returned object is referring to Integer then cast that object into Integer and call func2() by passing Integer object.

    GDS123 wrote:
    Problem:
    How to cast an Object into a specific type (Integer/String) at runtime, where type is not known at compile time.
    There is only one way to have an object of an unknown type at compile time. That is to create the object's class at runtime using a classloader. Typically a URLClassloader.
    Look into
    Class.ForName(String)

  • Hi my iph4s wont turn on or off and seems to be zoomed into a particular part of the screen, loads normally when rebooted the phone. what is wrong with it? and how would i go abouts fixing it?thanks

    hi my
    iph4s wont turn on or off and seems to be zoomed into a particular part of the screen, loads normally when rebooted the phone. what is wrong with it? and how would i go abouts fixing it?
    also recovery mode shows up as a red icon instead of a blue one, not jail broken or had any third party alterations
    thanks

    Reset the PRAM
    Reinstall the operating system from the dvd (you will not loose your data)

  • I am wondering how to zoom into a video in iMovie '09. For example I want to  zoom into a certain part of the video. Is there any way to do this???

    I am wondering how to zoom into a video in iMovie '09. For example I want to
    zoom into a certain part of the video. Is there any way to do this???

    Yes.
    If you want to see the zoom, use the Rotate, Crop, Ken Burns Tool and select the Ken Burns effect. You can set the starting and ending rectangle for your zoom.
    If you want to go directly to the zoom, use the Rotate, Crop, KenBurns Tool and select Crop. Set the rectangle to be where you want the zoom.

  • How to write the errors into a specific file

    Hi all,
    How to handled the errors in the scenarios,By using fault messages we can informed about errors to sender.But in my case i have to gather all errors & write into a specific file.For this can i create another Communication Channel for File reciever.How can i gather error messages in the scenario.
    Early response is appreciate

    Hi,
    Bhavesh had already answered how to handle it. For saving it in a file yes you can use File Receiver adapter.
    Regards,
    Prakash

  • How to get mail address into a specific address group folder

    I need to be able to copy an email address from Mail and when saving it into Address Book, have it automatically go into a specific folder.
    Seems pretty obvious but I'm not seeing how to do this.
    Or is my only option to save to Address Book then manually drag the address into the intended folder?
    Thanks.

    Mail will only add an address to the main Address Book list. You could write an Applescript to perform the operation or possibly an Automator script.

  • Zoom into a specific point on a clip

    How do I zoom to a specific point on a clip or picture?
    Whenever I try to use this feature it just goes to the centre of the clip.
    Thank-you.

    Make sure Image + Wireframe is selected in the Canvas:
    Select the clip you want to zoom in on and reposition on the timeline by clicking on it. Once it is selected on the timeline, the turquoise box and cross hairs should appear in the canvas.
    If you click and drag on one of the boxes on the corner, you can resize your image:
    And if you click and drag on the image itself, you can change the clips position:
    You may need to change the canvas display scale to see the handles after you zoom in:
    MtD

  • How to impdp data only into a specific schema

    Hello,
    How to impdp Tables and Materialized Views only into a specific schema. Also, how to exclude certain tables in particular schemas from being imported. Thank you.

    Pl Check the link
    http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14215/dp_import.htm#i1007865
    Thanks

  • How can I import photos into a specific album?

    Wow, I have been using Applescript for 15 years but I can't get this to work. I just want to make a script that brings a JPG image into iPhoto '09 into a specific album, but it seems set against letting me, and I can't find specific examples of what I'm trying to do so far.
    tell application "iPhoto"
    new album name "hello"
    add "Mac HD:Users:pp:mypic.jpg" to album "hello"
    end tell
    This doesn't give an error and it makes the album, but nothing else. Nothing is imported into iPhoto.
    Eventually I want to add a title and keyword data to that picture also using Applescript (hopefully not UI scripting), but since I can't get the barest basics of importing to work properly, I thought I'd see if anyone here could help.

    Peter
    I’ve never seens an AS that can do this. Hazel can and it might be worth examining it to see what you can learn.
    Automator can do this too, but there’s no way in that to add keywords or titles in that - though it is possible with Aperture and Automator.
    Given that we can go months on here without mention of AppleScript I wouldn’t be surprised if you get a better response on the AppleScript forum.
    Regards
    TD

  • I have taken pictures of items that are linked to a database that I am building.  How can I bypass importing into iPhoto and simply downloading the images as "files" not "photos" so I can access them with my database?  thanx.

    I have taken pictures with both my Sony camera and my iPhone of items that are linked to a database that I am building, as well as my website.  How can I bypass importing the images into iPhoto and simply downloading the images as "files" not "photos" so I can access them with my database?  thanx.

    If your Sony has a removable memory card you can use a card reader to copy the image files from to a folder on your Desktop and then move them anywhere you'd like.
    Since the iPhone doesn't have a removable memory card you can try using Image Capture to see if you can manually upload the files to a folder on the Desktop. 
    If you have to import the photos, which are image files, into iPhoto you can then export them out of iPhoto to the Desktop and go from there to your database.  Just because they are in iPhoto doesn't prevent you from using them elsewhere.
    OT

  • How to have a box layout on a JDialog, with an image set as background

    Hi,
    I need to have a JDialog in which there is a background image set (I already did this part, but only with the default layout). I further need to add text to the lower part of the JDialog. (For this, I guess I need to have a box layout.). I am not able to do so, because if I do so, I wont be able to set image background to the entire JDialog. Please help me out with how to solve this issue?
    Thanks,
    Joby

    Hi jduprez,
    Thanks for the reply. I checked Rob Camick's blog. It gives a nice way to add an image to a panel (*master panel*) and to use it.
    I still have my problem open. The above solution gives panel that I can add to my JDialog. But on the bottom half of the image (as you said, BorderLayout.South), I need to add another structured set of components using a Border Layout again.!, ie, one more panel with a BorderLayout. So when I add
    this panel, to the master panel containing the image, then the image gets cut off, at that point. I tried using component.setOpaque(false) on my sub-panel, still it does not work. Any idea, how to achieve this...?
    Following is the code I have adapted.
    public class BackgroundPanel extends JPanel
         public static final int SCALED = 0;
         public static final int TILED = 1;
         public static final int ACTUAL = 2;
         private Paint painter;
         private Image image;
         private int style = SCALED;
         private float alignmentX = 0.5f;
         private float alignmentY = 0.5f;
         private boolean isTransparentAdd = true;
         public static void main(String[] args) {
              Image img = getImage("D:/imgs/Snowdrop.jpg");
              BackgroundPanel panel = new BackgroundPanel(img);
              JDialog dlg = new JDialog();
              dlg.setLayout(new BorderLayout());
              dlg.add(panel);
              panel.setTransparentAdd(true);
              Panel nPanel = new Panel();
              nPanel.setLayout(new BorderLayout());
              JLabel label = new JLabel();
              //label.set
              label.setText("<html>HI<br>This is another line<br><br><br><br><br><br><br><br><br><br></html>");
              nPanel.add(label, BorderLayout.NORTH);
              panel.add(nPanel/*label*/,BorderLayout.SOUTH);
              dlg.setSize(600, 500);
              dlg.setVisible(true);
         private static Image getImage(String fileName){
              File file = new File(fileName);
             Image image = null;
             try{
                  image = ImageIO.read(file);     
             catch(IOException ioe){
                  /*JOptionPane.showMessageDialog(dlg, "Error in loading image file",
                            "Error", JOptionPane.ERROR_MESSAGE, null);*/
             return image;
          *  Set image as the background with the SCALED style
         public BackgroundPanel(Image image)
              this(image, SCALED);
          *  Set image as the background with the specified style
         public BackgroundPanel(Image image, int style)
              this(image,style,-1,-1);
          *  Set image as the backround with the specified style and alignment
         public BackgroundPanel(Image image, int style, float alignmentX, float alignmentY)
              setImage( image );
              setStyle( style );
              if (alignmentX  > 0){
                   setImageAlignmentX( alignmentX );     
              if (alignmentY  > 0){
                   setImageAlignmentY( alignmentY );     
              setLayout( new BorderLayout() );
          *  Use the Paint interface to paint a background
         public BackgroundPanel(Paint painter)
              setPaint( painter );
              setLayout( new BorderLayout() );
          *     Set the image used as the background
         public void setImage(Image image)
              this.image = image;
              repaint();
          *     Set the style used to paint the background image
         public void setStyle(int style)
              this.style = style;
              repaint();
          *     Set the Paint object used to paint the background
         public void setPaint(Paint painter)
              this.painter = painter;
              repaint();
          *  Specify the horizontal alignment of the image when using ACTUAL style
         public void setImageAlignmentX(float alignmentX)
              this.alignmentX = alignmentX > 1.0f ? 1.0f : alignmentX < 0.0f ? 0.0f : alignmentX;
              repaint();
          *  Specify the horizontal alignment of the image when using ACTUAL style
         public void setImageAlignmentY(float alignmentY)
              this.alignmentY = alignmentY > 1.0f ? 1.0f : alignmentY < 0.0f ? 0.0f : alignmentY;
              repaint();
          *  Override method so we can make the component transparent
         public void add(JComponent component)
              add(component, null);
          *  Override method so we can make the component transparent
         public void add(JComponent component, Object constraints)
              if (isTransparentAdd)
                   makeComponentTransparent(component);
              super.add(component, constraints);
          *  Controls whether components added to this panel should automatically
          *  be made transparent. That is, setOpaque(false) will be invoked.
          *  The default is set to true.
         public void setTransparentAdd(boolean isTransparentAdd)
              this.isTransparentAdd = isTransparentAdd;
          *     Try to make the component transparent.
          *  For components that use renderers, like JTable, you will also need to
          *  change the renderer to be transparent. An easy way to do this it to
          *  set the background of the table to a Color using an alpha value of 0.
         private void makeComponentTransparent(JComponent component)
              component.setOpaque( false );
              if (component instanceof JScrollPane)
                   JScrollPane scrollPane = (JScrollPane)component;
                   JViewport viewport = scrollPane.getViewport();
                   viewport.setOpaque( false );
                   Component c = viewport.getView();
                   if (c instanceof JComponent)
                        ((JComponent)c).setOpaque( false );
          *  Add custom painting
         protected void paintComponent(Graphics g)
              super.paintComponent(g);
              //  Invoke the painter for the background
              if (painter != null)
                   Dimension d = getSize();
                   Graphics2D g2 = (Graphics2D) g;
                   g2.setPaint(painter);
                   g2.fill( new Rectangle(0, 0, d.width, d.height) );
              //  Draw the image
              if (image == null ) return;
              switch (style)
                   case SCALED :
                        drawScaled(g);
                        break;
                   case TILED  :
                        drawTiled(g);
                        break;
                   case ACTUAL :
                        drawActual(g);
                        break;
                   default:
                     drawScaled(g);
          *  Custom painting code for drawing a SCALED image as the background
         private void drawScaled(Graphics g)
              Dimension d = getSize();
              g.drawImage(image, 0, 0, d.width, d.height, null);
          *  Custom painting code for drawing TILED images as the background
         private void drawTiled(Graphics g)
                 Dimension d = getSize();
                 int width = image.getWidth( null );
                 int height = image.getHeight( null );
                 for (int x = 0; x < d.width; x += width)
                      for (int y = 0; y < d.height; y += height)
                           g.drawImage( image, x, y, null, null );
          *  Custom painting code for drawing the ACTUAL image as the background.
          *  The image is positioned in the panel based on the horizontal and
          *  vertical alignments specified.
         private void drawActual(Graphics g)
              Dimension d = getSize();
              Insets insets = getInsets();
              int width = d.width - insets.left - insets.right;
              int height = d.height - insets.top - insets.left;
              float x = (width - image.getWidth(null)) * alignmentX;
              float y = (height - image.getHeight(null)) * alignmentY;
              g.drawImage(image, (int)x + insets.left, (int)y + insets.top, this);
    }Thanks,
    Joby

  • How do I get original shape of photos. Mine have all changed to square , losing part of the image. Infuriating!

    My photo library has changed the shape of all my images to square meaning I have lost part of the image. How do I revert all the images to their original shape? Very annoying!

    All the images are now square with rounded corners, very "arty" but substantil parts of the image is lost as all my photos are A shape ie they are normal photo negative shape. Ther seems to be no tool on the latest iPhoto to make the change back to originals. I have nearly 1000 photos  so changing them back one by on is not practical

  • How to have H-REAP broadcast only specific locally switched SSID's?

    I'm new to this H-REAP configuration, but in the main office we have about 6 WLAN's.  I have a remote office which I want to have 2 new WLAN's and have them switched locally.  How can I only have the H-REAP AP's at this site only broadcast those 2 SSID's vs all 8?  I haven't really read anything about using AP Group VLAN's with H-REAP or know if that's even possible, but is this a possibility and if no,t what would you recommend?
    Thanks for the help!

    I may create another topic - but here it goes...
    I've decided to try to use an existing WLAN in the H-REAP config...
    -I've joined the AP to the remote controller, assigned it an IP, put it in H-REAP mode.
    -I chose a WLAN, enabled local switching
    -I went into the AP, configured the native VLAN, however, I CAN NOT change the vlan of the WLAN listed.  It always goes back to default.
    I verified the vlan exists on the switch, is routable, etc, the switch port is a member of that vlan, it is set as a trunk w/ 802.1q, etc.
    Any ideas on what would cause this?
    I am SOO close   Thanks!

Maybe you are looking for

  • Windows 8 + HP Officejet 6500 E709n, Scan problem

    L.s After buying a new pc with Windows 8, the HP printer is not able to scan. After fixing the first error that occur (not recognizing the scannere at all), a new error occur. This time it says: "The scan can not be performed because the HP imaging d

  • ITunes wont open, tried pretty much everything

    So earlier this month I went to update to iTunes 8.0.2, expecting the same standard process. When I went to open iTunes after the update, though, nothing happens. When I poen the task manager, I find that no application is running. But when I check m

  • General error 34

    Im trying to open a sequence & im getting an error message general error (34) Error out of memory wont open sequence wont open timeline window of the project any ideas

  • Use of bind keyword

    Hi all, I read that 'bind' keyword would create relationship between two variables. I tried out an example but i could not make out the difference with and without this variable. //Bind a sequence var s1 = [1,2,3,4,5]; def s2 = bind for(item in s1){

  • Acrobat Distiller, Excel, Adding a reference in VBA

    I have a snippet of VBA to generate a PDF through Excel. I expected to see "Acrobat Distiller" in the references under the menu option Tools/References in the Visual Basic editor. It's not there. Can anyone help?