Zooming into the center of an image

Hi, I have this code that allows the user to zoom into an image that they have selected. However, when the image is zoomed into using the slider, it goes towards the top left corner of the image rather than the center. How can I modify my code to zoom into the center of the image instead?
import java.awt.*;
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 MapScale extends JPanel
     BufferedImage image;
     double scale = 1.0;
     public MapScale(BufferedImage image)
          this.image = image;
     protected void paintComponent(Graphics g)
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D)g;
          g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
          double x = (getWidth() - scale*image.getWidth())/2;
          double y = (getHeight() - scale*image.getHeight())/2;
          AffineTransform at = AffineTransform.getTranslateInstance(x,y);
          at.scale(scale, scale);
          g2.drawRenderedImage(image, at);
     public Dimension getPreferredSize()
          int w = (int)(scale*image.getWidth());
          int h = (int)(scale*image.getHeight());
          return new Dimension(w, h);
     private JSlider getSlider()
          int min = 1, max = 36;
          final JSlider slider = new JSlider(min, max, 16);
          slider.setMajorTickSpacing(5);
          slider.setMinorTickSpacing(1);
          slider.setPaintTicks(true);
          slider.setSnapToTicks(true);
          slider.setPaintLabels(true);
          slider.addChangeListener(new ChangeListener()
               public void stateChanged(ChangeEvent e)
                    int value = slider.getValue();
                    scale = (value+4)/20.0;
                    revalidate();
                    repaint();
          return slider;
     public static void main(String[] args) throws IOException
          JFileChooser selectImage = new JFileChooser();
          if (selectImage.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
               String path = selectImage.getSelectedFile().getAbsolutePath();
               BufferedImage image = ImageIO.read(new File(path));
               MapScale test = new MapScale(image);
               JFrame f = new JFrame();
               f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               f.getContentPane().add(new JScrollPane(test));
               f.getContentPane().add(test.getSlider(), "Last");
               f.setSize(400,400);
               f.setLocation(200,200);
               f.setVisible(true);
}

KGCeltsGev wrote:
Hi, I have this code that allows the user to zoom into an image that they have selected. However, when the image is zoomed into using the slider, it goes towards the top left corner of the image rather than the center. How can I modify my code to zoom into the center of the image instead?Since you use a JScrollPane and change the client size when you zoom in/out you need to scroll to the center every time you zoom in/out.
This is done by using scrollRectToVisible.
slider.addChangeListener(new ChangeListener() {
    public void stateChanged(ChangeEvent e) {
        int value = slider.getValue();
        scale = (value+4)/20.0;
        revalidate();     
        Dimension d = getPreferredSize();
        Dimension extentSize = ((JViewport) getParent()).getExtentSize();
        scrollRectToVisible(new Rectangle((d.width-extentSize.width)/2, (d.height-extentSize.height)/2, extentSize.width, extentSize.height));
});

Similar Messages

  • How do I Place an image into the center of an activated artboard in CC?

    I have just upgraded to CC from CS6. In CS6, I could activate an artboard (double click it in the Artboard panel) and then Place an image, which would by default go into the center of the artboard.
    With CC, it "loads" the image into the cursor which I then need to Place by clicking somewhere.
    How can I get it to either behave as it did in CS6, or customize to load it into the center when I click, such as with a modifier key?
    Thanks!

    Hi,
    With the Window > Allign panel,
    You can select the option to allign to selection or to Artboard.
    When you select "to Artboard" you schould be able to use the Allign option to get it centerred.
    See preview bellow.
    Hope this helps.

  • Just purchased CC Lightroom & Photoshop following a 30 day free trial. All worked well during the trial but now I have subscribed to the plan and downloaded the latest LR version I am unable to zoom into the images and just get a constant 'loading' box an

    Just purchased CC2015 Lightroom & Photoshop following a 30 day free trial. All worked well during the trial but now I have subscribed to the plan and downloaded the latest LR version I am unable to zoom into the images and just get a constant 'loading' box and spinning circle. Also, the whole system is very slow - very frustrating! Any ideas? I am running it on Windows 8.
    Mick

    You keep asking variants on this same question. You've had replies in all your other threads. If you can't find them, go here and click where it says Activity:
    Thomas Cannon Jr.

  • MY IPOD APPEARS TO BE ZOOMED INTO THE SCREEN AT ALL TIMES, MAKING IT DIFFICULT TO DO SIMPLE TASKS SUCH AS GO BACK, OR SELECT A PLAYLIST, ETC. I'VE TRIED PULLING IT OUT WITH MY FINGERS BUT THAT DOESN'T WORK. PLEASE CAN YOU HELP!!! THANKS.

    I've got a touch iPod and for about a week now it's almost been permenently zoomed into the screen? I actually cannot get it to zoom back out. I've tried pulling the screen out with my fingers but that doesn't work. It's zoomed in on my home pages, on my music, settings everything! It makes simple things like deleting a number from my password login extreamly differcult. Please can someone help?!?! Thanks.

    Double tap the screen with three fingers to un-zoom.
    Then go to Settings > General > Accessibility > Zoom and turn this OFF.

  • How do I turn off the alt scroll zoom?  When I'm in Adobe photoshop and illustrator using the pen tool, alt is utilized for another short cut.  I would like to use the alt command for the pen tool instead of zooming into the screen.

    How do I turn off the alt scroll zoom? 
    When I'm in Adobe photoshop and illustrator using the pen tool, alt is utilized for another short cut.  I would like to use the alt command for the pen tool instead of zooming into the screen.

    I tend to select things from left to right and every time I am moving in a downward right diagonal motion during lasso selection I am missing a clear view and I am tending to have a more sloppy selection.  All this does is slow me down since I need to go back and hit those areas again.  The big arrowhead just get's in the way.  The original lasso tool with the thin line and small active point at it's lower left was far better for me.
    I don't like turning the cursors to precise because I like to see the active tool icon where my cursor is and as the icon changes as I hold modifier keys down.  If I am forced to get comfortable with using pricise cursors I guess I will, but man, I've never had to do this in my 15 years of photoshop use...
    I would absolutely LOVE to find a way to get the old lasso icon -- without the arrowhead above it.
    Is there any chance this option could be inlcuded in cursor preferences?  I'd give much thanks, Adobe.

  • Image rotation - mapping the image into the center of the new image

            for (int x = 1; x < imageOne.getWidth()-1 ; x++) {
                for (int y = 1; y < imageOne.getHeight()-1 ; y++) {
                    /* Get the values from imageOne */
                    int red = imageOne.getRed(x, y);
                    int green = imageOne.getGreen(x, y);
                    int blue = imageOne.getBlue(x, y);
                             * x' = a0x + a1y + a2
                             * y' = b0x + b1y + b2
                    double x2 = Math.round(a0 * x + a1 * y);
                    double y2 = Math.round(b0 * x + b1 * y);
                    if (x2 > imageOne.getWidth()-1 || x2 < 0 || y2 < 0 || y2 > imageOne.getHeight()-1){
                        //Do Nothing
                    }else{
                        imageTwo.setRGB((int)x2, (int)y2, red, green, blue);
            }Using the above algorithm, the image will rotate, but the rotation will start from the corner of the image (coordinate 1,1). For example, if I do a >90 degree angle rotation, the image will diappear.
    I want my image to rotate and appear in the middle of the new image output.
    Any idea?

    Hi,
    As part of my courseowrk, where we can't use the Java's API, im trying ot do the rotation manually...
    Say my image is always 512x 512, and I've tried "translate" -> "rotate" -> "translate" below:
            for (int x = 1; x < imageOne.getWidth()-1 ; x++) {
                for (int y = 1; y < imageOne.getHeight()-1 ; y++) {
                    /* Get the values from imageOne */
                    int red = imageOne.getRed(x, y);
                    int green = imageOne.getGreen(x, y);
                    int blue = imageOne.getBlue(x, y);
                             * x' = a0x + a1y + a2
                             * y' = b0x + b1y + b2
                    //1st transform
                    x2 = x+256;
                    y2 = y+256;
                     double rad = Math.toRadians(m);
            double cos = Math.cos(rad);
            double sin = Math.sin(rad);
            int newX = (int)Math.round(cos * getX() - sin * getY());
            int newY = (int)Math.round(sin * getX() + cos * getY());
            setX(newX);
            setY(newY);
                    //2nd transform
                    x2 = x2-256;
                    y2=y2-256;
                    if (x2 > imageOne.getWidth()-1 || x2 < 0 || y2 < 0 || y2 > imageOne.getHeight()-1){
                        //Do Nothing
                    }else{
                        imageTwo.setRGB((int)x2, (int)y2, red, green, blue);
            }setX and setY will update the value in x2 and y2.
    The concept is to move the pointer to the mid of the image (midHeight and midWidth) which is "x2 = x+256;" and "y2 = y+256;", rotate and translate again - but the output is still nto in the middle..
    Any idea?

  • Zooming  into the timeline on FCPX

    Is it just my system or does the zoom in on the timeline (Z alt click) require one to lift ones finger off the alt key between clicks. At the moment when I hold the alt key and click say three times FCP X zooms in, then out, then in again.

    What you want to do is use the command + or command - combinations. That will zoom in and out. Shift Z will shrink the timeline back down to fit in the project window and primary timeline. For a specific spot either have the playhead or skimmer line at that spot and it will zone right in for you. No matter how far in you go, the shift Z will take you back to the 35000 foot view so to speak.
    Good luck!

  • I want to zoom into digital image pixels.

    To demonstrate DSLR chip behavior at high magnification, I want to zoom into the frame and see how individual pixels actually look.
    But when I use the Scale tool to enlarge the picture, FCPX thinks I want to avoid seeing pixels so it mushes the image, blurring all the pixels.
    How do I get it to stop doing that? Can it be done in Motion?
    Photoshop scaling has all these Bicubic options, but it also has the Nearest Neighbor option so I can see individual pixels in the blow up, there. Is there a way to get FCPX to do the same idea?

    Peter Inova1 wrote:
    When you are zooming into a movie that is made in a way to reveal an HDSLR's blown pixels, it would be nice to see them as a pixel map.
    again: the actual compression (from any cam!) doesn't deliver single pixels.
    it starts on the sensor of the cam - ever heard of the Bayer Filter?
    http://en.wikipedia.org/wiki/Bayer_filter
    if you could read out the raw data of that chip, you'd notice twice as much green 'dots' than red and blue, oops!
    next, your cam compresses '4:2:0'
    http://en.wikipedia.org/wiki/4:2:0
    that Chroma Subsampling drops 7 of every 8 'color dots' ... most pixels are 'grey'!
    finally, it's a lossy codec, working with 'assumptions'
    http://en.wikipedia.org/wiki/Inter_frame
    picture-prediction .... that's bits, not atoms
    on de-coding, final delivery, these 'formulas' are calculated to a 1920x1080 picture ... but that is not the 'pixel reality' from your cam, nor on its sensor, nor in the file.
    so, a zoom-to-pixel-level is a special effect, as mentioned above, create a close-up in Photoshop, showing r/g/b- squares … but this is not reality.

  • When I drag a video clip into the upper region, it zooms in, cutting off part of the head of the subject

    I have a movie clip imported from my DVD video camera.  After importing, I drag it to the Project library.  However, it then zooms in and cuts off the head of the main subject, besides making things blurry from zooming in.  I would say it almost doubles the zoom.  I have gone to all the options... took of the cropping effect, etc.  Nothing works.   Any ideas?  I saw something else about it on here, but no answers.

    This can happen if you have image stabilization turned on as it zooms into the clip to compensate for the camera shake. It can turn it off or control the zoom factor in the Clip Adjustments function. If you reduce the zoom factor too much you'll see black around the image.

  • 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

  • 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);
    }

  • How to zoom into small text in Title Edit Window?

    Ok,
    So when I am putting in disclaimer text in the Title edit window, I can't read it.  I could if I could zoom into it or at least increase the scaling of the video preview. 
    Someone else has had to have had this problem.  As you can see from the attached image, all the wasted extra space around the video, if I could just zoom in like you can on the preview window I could read it.
    How can I zoom into the area I am trying to edit with small text???
    Pleas help, anyone???

    First of all Reset Current workspace, does not seen to fit the window also I would make the titler a floating window.
    You cannot zoom in but you can make it full screen by hitting the 'tilde"(grave) key.
    You can also scale up the text, adjust, and scale it down again.

  • How can I format a field to have a Check Box in the center.

    I am a new adobe user and I am creating a form in Adobe LiveCycle Designer. Most of what I needed to do I was able to figure out, but I cannot find a way to place a Check Box in the center of a chosen field. Each time I use the Check Box from the library it automatically places the Box in the center-right of the field. Then when trying to format the paragraph, I get no options about where I'd like the box to reside within the field. Is there a simple way to get a Check Box into the center of a Field or will I have to pursue other options. If I do have to pursue other options are there any ways to limit a text to an X and have it either be On or Off?
    Thanks for your aid.

    This behaviors usually happens when you create the fields but  a copy paste command from one of the fields. The copy paste command assumes that your intentions is to maintain a copy of the field in two separate locations (e.i, a form field  "company name" printed in each and every page of a multi-page form document.
    Go to the properties fields of each field and make sure  to assign unique form field  names.

  • Executing "bring to center" on a free cursor in a log XY graph brings the cursor to the top rim of the graph (instead of the center)

    Dear support,
    dear LV users,
    selecting "bring to center" for a free cursor in a XY graph does not
    bring the cursor into the center of the graph, but instead the command brings it to the
    mean/average value. This is not an issue for a linear mapping
    of the axis [due to the fact that the center of the axis is equal to
    the middle/average value of the end points on the axis]. But when
    mapping of the axis is logarithmic, the cursor ends up on the top of
    the screen. That is because the average value of the end points
    (min(y_axis)+max(y_axis))/2) is not equal to the center of the axis.
    Is that a wished behavior, please?
    Example: For an y_axis = [1..100], the awaited center position would be at
    10 and not at 50.5. The center position for the logarithmic mapping
    should be calculated as (log(min(y_axis))+log(max(y_axis)))/2, IMHO.
    Kind regards,
    Solved!
    Go to Solution.

    You are right, LabVIEW chooses this form (min(y_axis)+max(y_axis))/2).
    You can go to "idea exchange".
    Link:
    http://forums.ni.com/t5/ideas/v2/ideaexchangepage/blog-id/labviewideas
    here you can see how many people like your idea.
    Perhaps it will be considered in the next version of LabVIEW.

  • Zoom into a letter (Motion 3)

    Hi there,
    I have a white screen with black text on it. I am attempting to transition to a black screen by zooming all the way into a black letter. Is it possible to set a zoom point and let motion take care of the rest? Or will I have to keyframe this manually? When I attempt to keyframe this animation, I reach a point where I just can't zoom into the letter anymore. Does anyone have any advice for me? It would be greatly appreciated.

    umm...what do you mean by white borders? you tried what mark said with the camera?
    or
    change your group to 3d, arrange the anchor point of the group to where you want it to zoom to, then move the group's position on it's z axis.
    or if the group is 2d, place the anchor point of the group to where you want it to scale to and scale the group...

Maybe you are looking for