Script to rotate image 'attached' to button

I'm very new to the business of creating interactive forms, having only just figured out how to get the script editor to appear.
But to the point, I've created a form with twenty plus pages, each page contains an 'image field' for the end user to click on which allows them to submit a series of pictures.
The form is in Portrait orientation, but some of the images will be in Landscape orientation, ('best fit' means that the image is smaller and only takes up the top half of the image space). What I am looking for is to create a 'rotate image' button on each page that allows the end user to click it and have the image rotate through 90 degrees (within the image field) if they what to, leaving the page orientation in Portrait. (The viewer will have to turn their head sideways, but at least the image will be larger and more detailed)
Currently the advice is that they 'rotate' the image first using any familiar software, and then select it for the form.
This is a 'nicety' as far as the form is concerned, but it would give it a finishing touch. Any advice/ideas?

Ah, pguerett, this is probably exactly the TYPE of thing the user is looking for. I just tested it out. However, I see two problems with it.
1) The button only works once. So if you click it to rotate and then decide you liked it the other way, if you click the button again it does nothing.
2) It doesn't resize the image. If I insert a "Landscape oriented" picture it resizes it to be proportional to the size of the portrait oriented field. Click the button to rotate it 90 degrees. It rotates the picture so that it is sideways, but it does not resize the image to now be porportional to the long-edge of the field. I hope I'm making sense.
I would definitely like to see a solution to this one, since I have a form I will be working on very soon that could benefit from having this.

Similar Messages

  • Script to rotate an image in InDesign CS4 from an Excel Spreadsheet

    Hi all,
    Is there a script for InDesign CS4 that reads degrees from an excel spreadsheet and then rotates a specific image by the same amount of degrees that was written in this excel spreadsheet? I would like to create a column in Excel full of rotation degrees and then go to InDesign, run the script for a specific image and the image will rotate automatically.
    If there isn't a script like that already around, can you let me know if it is possible to be done and also if it is possible, can you help me create one please?
    Thank you in advance for your help.
    Lucas

    a script to rotate images... only one at a time and marijan tompa had the answer for that: http://forums.adobe.com/message/2998073
    as for referencing an excel file or txt/csv, i don't know, but perhaps other posters could assist.
    colly

  • How to make a button remain still while on top of a rotating image?

    I've tried making an interactive menu that has a rotating image in the background and some buttons on top of that background. The background itself is in a JPanel and the button is added directly on that JPanel since the Panel occupies the entire frame. Now, the problem is that the button spins along with the rotated graphics X_X. So...any ideas?
    Here's some of the code:
    class EyE extends JPanel{
    Image im;
    public int angx=0;
    MediaTracker tracker=new MediaTracker(this);
    EyE(){
    Toolkit ec=Toolkit.getDefaultToolkit();
    im=ec.getImage("Graphics\\hcr1.png");
    setPreferredSize(new Dimension (400,400));
    setBackground(Color.BLACK);
    JButton frog=new JButton("Jerry");
    this.add(frog);
    setOpaque(false);
    setVisible(true);
    public void paintComponent(Graphics ecr){
    Graphics2D g2d=(Graphics2D)ecr;
    tracker.addImage(im,1);
    try{tracker.waitForID(1);}
    catch(InterruptedException ie){}
    //code for roatating image (really didn't want to use AffineTransform)
    double cs=Math.cos(Math.toRadians(angx)),ss=Math.sin(Math.toRadians(angx));
    g2d.rotate(Math.toRadians(angx));
    double x2=(200*cs-200*ss),y2=(200*ss+200*cs);
    double m,n,d,tetcs1,tetss1,tetcs2,tetss2,ang1,ang2;
    d=(Math.sqrt(Math.pow((y2-200),2)+Math.pow((x2-200),2)));
    tetcs1=d/(400*Math.sqrt(2));
    tetss1=Math.sqrt(1-Math.pow(tetcs1,2));
    tetcs2=(160000-Math.pow(d,2))/160000;
    tetss2=Math.sqrt(1-Math.pow(tetcs2,2));
    ang2=180-2*Math.toDegrees(Math.acos(tetcs1));
    ang1=ang2+Math.toDegrees(Math.acos(tetcs1))-45;
    n=d*(Math.sin(Math.toRadians(ang1)));
    double g=Math.sin(Math.toRadians(ang1));
    m=Math.sqrt(Math.pow(d,2)-Math.pow(n,2));
    if(angx<=90)g2d.translate(m,-n);
    else if(angx<=180)g2d.translate(-m,-n);
    else if(angx<=270)g2d.translate(-n,-m);
    else if(angx<=360)g2d.translate(-n,m);
    //rotating code ends
    g2d.drawImage(im, 0,0,400,400, this);
    }

    class EyE extends JPanel {
        Image im;
        public int angx=0;
        MediaTracker tracker=new MediaTracker(this);
        EyE(){
            Toolkit ec=Toolkit.getDefaultToolkit();
            im=ec.getImage("Graphics\\hcr1.png");
            setPreferredSize(new Dimension (400,400));
            setBackground(Color.BLACK);
            setOpaque(false);
            setVisible(true);
        public void paintComponent(Graphics ecr){
            Graphics2D g2d=(Graphics2D)ecr.create();
            tracker.addImage(im,1);
            try{tracker.waitForID(1);}
            catch(InterruptedException ie){}
    //      code for roatating image (really didn't want to use AffineTransform)
            double cs=Math.cos(Math.toRadians(angx)),ss=Math.sin(Math.toRadians(angx));
            g2d.rotate(Math.toRadians(angx));
            double y2=(200*cs-200*ss),x2=(200*ss+200*cs);
            double m,n,d,tetcs1,tetss1,tetcs2,tetss2,ang1,ang2;
            d=(Math.sqrt(Math.pow((y2-200),2)+Math.pow((x2-200),2)));
            tetcs1=d/(400*Math.sqrt(2));
            tetss1=Math.sqrt(1-Math.pow(tetcs1,2));
            tetcs2=(160000-Math.pow(d,2))/160000;
            tetss2=Math.sqrt(1-Math.pow(tetcs2,2));
            ang2=180-2*Math.toDegrees(Math.acos(tetcs1));
            ang1=ang2+Math.toDegrees(Math.acos(tetcs1))-45;
            n=d*(Math.sin(Math.toRadians(ang1)));
            double g=Math.sin(Math.toRadians(ang1));
            m=Math.sqrt(Math.pow(d,2)-Math.pow(n,2));
            if(angx<=90)g2d.translate(m,-n);
            else if(angx<=180)g2d.translate(-m,-n);
            else if(angx<=270)g2d.translate(-n,-m);
            else if(angx<=360)g2d.translate(-n,m);
    //      rotating code ends
            g2d.drawImage(im, 0,0,400,400, this);
            g2d.dispose();
            super.paintComponent(ecr);
    }

  • Manipulating (Rotating) an Image with a button in Java

    I'm trying to display an image in a BorderLayout, and also I want a button on the layout that, when pressed, will rotate the image. I'm not sure how to create an image and be able to add it to a JFrame because when I do so, using something like:
    Image img = new Image("myPic.gif");
    myFrame.add(img, BorderLayout.CENTER);
    I just end up getting a compiler error. I could use a seperate class and draw the image in the paintComponent method, but I'm not sure how I add both the image and a button with which I can manipulate the image in the same class (I am assuming I need to use an ActionListener on the button to control the image, and if this is the case I am assuming they need to be in the same class). Can someone point me in the right direction here?
    Thanks,
    Alex
    [email protected]

    put the image in a JPanel subclass as you mention above and have a public method in this class that rotates the image. Then just have the button call this object's rotate method. OOP to the rescue.

  • Lightbox script conflicting with image rotator script

    Hope someone can help with this....
    Basically I have added a Lightbox gallery, which is all working as it should here -
    http://www.goodsafariguide.com/new/gallery.php
    However, the large photos can render underneath the two sets of rotating images - the ones near the top of various resorts, and the one on the left hand side showing sponsor's logos. It only seems to do it sometimes with the set at the top, but always with the Award Sponsors one.
    If it doesn't show with the page as it loads, you can see what I mean by scrolling down until the Awards Sponsors graphic is about halfway down the screen.
    So my question is really just to ask if there's a way of ensuring that the Lightbox photos do appear over everything else on the page?
    Thanks.

    HI Ian, It looks right to me now in both FireFox and IE7. I haven't checked in IE8, which does have some Javascript interpretation problems. Hopefully you are not running into those here.
    Not specifically for this problem, but, for general css managablity and neatness, I usually try to group my z-index levels by either tens or hundreds, according to application. That is, If I have layers,
    I will use z-index: 10 for the first layer then anything inside that layer that might need a z-index will get 11, 12, etc.
    and z-index 0 for the second layer with anything inside it using 21, 22, etc.
    After that, I'll use 100 for javascript layers, and anything controlled by them that need indexing will get z-inde: 110, 120, etc.
    Then use 200 for the next JS layer, and so on.
    A lightbox that covers the whole page will get z-index: 1000, with nesteed elements getting 1100, 1200, etc.
    This allows me to keep it straight in my mind how everything overlaps, as well as make finer adjustments where needed, without interfering with any layers above or below the one I'm concerned with.
    Of course, it's rare that it gets very complicated, but I like to keep this as a good habit for myself since clients (even if I'm the client) have a way of surprising you with extra functionality requests after you've gotten something built.

  • Rotated image overlaps other controls

    Hi, I am working on an AIR app involving images. One of the functionalities is viewing as well as rotating images. I made a simple test app to illustrate this portion:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
        <mx:Script>
            <![CDATA[
                private function rotate():void
                    var bitmap:Bitmap = Bitmap(img.content);
                    var matrix:Matrix = bitmap.transform.matrix;
                    var centerX:Number = bitmap.width/2;
                    var centerY:Number = bitmap.height/2;
                    matrix.translate(-centerX, -centerY);
                    matrix.rotate(90*Math.PI/180);
                    matrix.translate(centerY, centerX);
                    bitmap.transform.matrix = matrix;
            ]]>
        </mx:Script>
        <mx:Text width="100%" text="Some text"/>
        <mx:Image id="img" width="100%" height="100%" source="test.jpg" horizontalAlign="center" verticalAlign="middle"/>
        <mx:Button label="rotate 90" click="rotate()"/>
    </mx:WindowedApplication>
    The application window has text on the top and a button on the bottom, with the image in the middle. Each click of the button rotates the image by 90 degrees.
    On launch, the app works great. It fetches the image file and fits it to the Image container. As I resize the application, the image also resizes and maintains the position relative to the other controls. Top text and bottom button are where they should be. All good. Let's assume the image is landscape/wide. After I perform the rotate 90 degrees by clicking the button, although the image is rotated and now in portrait orientation, the bottom portion of the image is now out of the image boundary and overlapping the button.
    Is there a way to tell the image to fit the content to the container again? Basically, re-layout the whole thing as if the image is in this new orientation.
    I suppose I can try to figure out a change in scale and resize the image, but I am not sure if this will hold when the user resizes the application. Also, the rotated image is now rather far to the left, as the "top left" corner is where a landscape image would be. For a portait orientation that's centered horizontally, it should be further to the right. I suppose I can also come up with some formula to center the rotated image. It just seems that the application already has all this logic built in, as it did exactly what I wanted when the image was loaded initially. If I can just ask the application to do it again. Note that similar issue occurs if the image starts out in portrait orientation and is rotated to landscape (too far to the right).
    Thanks in advance for the help.
    Will

    Thanks Sheila and Arnis,
    Today I opened the project to try different zoom settings and the problem has vanished; I get the correct arrow at zooms of 100, 120 and 140%.
    Likely a bug somewhere deep in Frame's innards. Anyway we've ordered TCS3 so soon I'll be using FM10. Thanks anyway.
    --- Derek

  • I have a Flash Sample to rotate images and text but I not find a way to display special characters

    Hello everyone.
    I bought a very nice Flash application that rotate images, and text of any color and size. It use an XML input file.
    I've posted here, a complete copy, so any of you can download, view and use it freely.
    I would appreciate if any of you know how to do, so that the text displayed, including the characters I use in my language (Spanish), such as á, é, í, ó, ú, ñ, and other special characters.
    In fact, I could not find a way to do it, because I'm not expert Flash, and less in ActionScript.
    If any of you would help me on that, I thank you implement the appropriate adjustments and compressed into a. zip file, and let me know where to download it, or if you prefer you can send it to my email: [email protected]
    After all compressed in .zip format is a very small file: 430K.
    Click here to download the complete sample.
    Thanks.
    =====================================
    Translated using http://translate.google.es
    =====================================

    Hello Rinus,
    If I understood your last post correctly, then problem 2 is resolved, right?
    Regarding problem 3:
    I'm not asking you to share exact VIs.
    I just want to see a very simple VI that explains the concept of what you're trying to do, what should happen (this can be in words that refer to the front panel elements) and what you've tried.
    The terminology you're using isn't clear to me without an extra explanation.
    This could even be only a Front Panel with a few buttons on where you just describe what should happen with specific controls/indicators.
    Based on the first post it is not clear to me what you mean with:
    - A "button element":
      Are you talking about a control, an indicator, a cluster that contains multiple control?
    - The structure:
      Is this an event structure, case structure, for loop, ...?
    Is it seems like you want to programmatically control Front Panel objects, which on itself is no problem at all independent of how many objects you want to control.
    Please share with me simple example of what goes wrong and explain which things should happen on that specific Front Panel.
    This will allow me to help you and also allow me to guide you along the right path.
    Kind Regards,
    Thierry C - Applications Engineering Specialist Northern European Region - National Instruments
    CLD, CTA
    If someone helped you, let them know. Mark as solved and/or give a kudo.

  • How to link an image to a button in Flash Builder 4

    I am new to Flash Builder 4 and have trouble to link an image to a button in Flash Builder 4.
    For example, I want an image of a round green button to replace the default retangle button in Flash Builder 4.
    Can anyone help me up?
    Thanks

    You could also use the mx:Image control and just add a click event handler:
    function(){return A.apply(null,[this].concat($A(arguments)))}
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
            xmlns:s="library://ns.adobe.com/flex/spark"
            xmlns:mx="library://ns.adobe.com/flex/mx"
            width="500" height="400">
        <fx:Script>
            <![CDATA[
                import mx.controls.Alert;
                protected function image1_clickHandler(evt:MouseEvent):void {
                    Alert.show("You clicked the image");
            ]]>
        </fx:Script>
        <mx:Image source="http://helpexamples.com/flash/images/image1.jpg"
                click="image1_clickHandler(event);" />
    </s:Application>

  • Anchored images outside of button frame

    Hi Experts
    I am trying to find a way of getting an image to become visible on rollover on a button I've created, without having the image positioned within the button frame. The images are large & I have several small buttons on the page, each linked to text frames with anchored text objects (the images.) Anchoring the images outside the text frame is no problem, but visibility is limited to the button frame.How do I link large images to small buttons that only activate on rollover? Any ideas? PLEASE help!

    Convert that image you want to appear to separate button, and attach show/hide buttons action to your real button. Use rollover as trigger for showing your image, and rollout for hiding it again....

  • Rotating Image with Fade Effect

    Ok looking to rotate an image with a fade effect; below is a rotating image code.
    (Wanting this effect to be transitional and smooth. Transparency? Opacity?)
    <script language="JavaScript">
    <!--
    function adArray() {
    for (i=0; i*2<adArray.arguments.length; i++) {
    this[i] = new Object();
    this[i].src = adArray.arguments[i*2];
    this[i].href = adArray.arguments[i*2+1];
    this.length = i;
    function getAdNum() {
    dat = new Date();
    dat = (dat.getTime()+"").charAt(8);
    if (dat.length == 1)
    ad_num = dat%ads.length;
    else
    ad_num = 0;
    return ad_num;
    var ads = new adArray(
    "img1.jpg","http://www.domain.com",
    "img2.jpg","http://www.domain.com",
    "img3.jpg","http://www.domain.com");
    var ad_num = getAdNum();
    document.write('<div align="center"><A HREF="'+ads[ad_num].href+'" target="_blank"><IMG SRC="'+ads[ad_num].src+'" '
    +'BORDER=0 name=js_ad></A></div>');
    link_num = document.links.length-1;
    function rotateSponsor() {
    if (document.images) {
    ad_num = (ad_num+1)%ads.length;
    document.js_ad.src = ads[ad_num].src;
    document.links[link_num].href = ads[ad_num].href;
    setTimeout("rotateSponsor()",4000);
    setTimeout("rotateSponsor()",4000);
    // -->
    </script>
    Any ideas?

    Here is the script I finally got working! It would have not came to me without your help guys!
    <script>
    var pictureWebPartName="Pictures"; // name of the picture library web part
    var showThumbnails = true; //otherwise show full sized images
    var randomImg = true; //set to true to show in random order
    var useCustomLinks = false; //true to use second column as URL for picture clicks
    var RotatingPicturesLoopTime = 5000; //2000 = 2 seconds
    var imgToImgTransition = 1.0; //2 = 2 seconds
    // don't change these
    var selectedImg = 0;
    var imgCache = [];
    var imgTag;
    function RotatingPictures()
    imgTag = document.getElementById("RotatingImage");
    //Find the picture web part and hide it
    var Imgs = [];
    var x = document.getElementsByTagName("TD"); // find all of the table cells
    var LinkList;
    var i=0;
    for (i=0;i<x.length;i++)
    if (x[i].title == pictureWebPartName)
    // tables in tables in tables... ah SharePoint!
    LinkList = x[i].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
    // hide the links list web part
    LinkList.style.display="none";
    break;
    if (!LinkList)
    document.all("RotatingImageMsg").innerHTML="Web Part '" + pictureWebPartName + "' not found!";
    //Copy all of the links from the web part to our array
    var links = LinkList.getElementsByTagName("TR") // find all of the rows
    var url;
    var len;
    for (i=0;i<links.length;i++)
    //if (links(i).id.match("row")!=null)
    if (links[i].childNodes[0].className=="ms-vb2")
    len=Imgs.length
    Imgs[len]=[]
    Imgs[len][0] = links[i].childNodes[0].childNodes[0].href;
    if (useCustomLinks)
    if (links[i].childNodes[1].childNodes.length>0)
    { Imgs[len][1] = links[i].childNodes[1].childNodes[0].href; }
    else
    { Imgs[len][1] = "" }
    if (Imgs.length==0)
    document.all("RotatingImageMsg").innerHTML="No images found in web part '" + pictureWebPartName + "'!";
    for (i = 0; i < Imgs.length; i++)
    imgCache[i] = new Image();
    imgCache[i].src = Imgs[i][0];
    if (useCustomLinks)
    imgCache[i].customlink=Imgs[i][1];
    RotatingPicturesLoop();
    // now show the pictures...
    function RotatingPicturesLoop()
    if (randomImg)
    selectedImg=Math.floor(Math.random()*imgCache.length);
    if (document.all){
    imgTag.style.filter="blendTrans(duration=" + imgToImgTransition + ")";
    imgTag.filters.blendTrans.Apply();
    url=imgCache[selectedImg].src
    if (useCustomLinks)
    { RotatingImageLnk.href=imgCache[selectedImg].customlink; }
    else
    { RotatingImageLnk.href = url; }
    if (showThumbnails)
    // convert URLs to point to the thumbnails...
    // from airshow%20pictures/helicopter.jpg
    // to airshow%20pictures/_t/helicopter_jpg.jpg
    url = revString(url);
    c = url.indexOf(".");
    url = url.substring(0,c) + "_" + url.substring(c+1,url.length);
    c = url.indexOf("/");
    url = url.substring(0,c) + "/t_" + url.substring(c,url.length);
    url = revString(url) + ".jpg";
    imgTag.src = url;
    if (document.all){
    imgTag.filters.blendTrans.Play();
    selectedImg += 1;
    if (selectedImg > (imgCache.length-1)) selectedImg=0;
    setTimeout(RotatingPicturesLoop, RotatingPicturesLoopTime);
    // utility function revString found here:
    // http://www.java2s.com/Code/JavaScript/Language-Basics/PlayingwithStrings.htm
    function revString(str) {
    var retStr = "";
    for (i=str.length - 1 ; i > - 1 ; i--){
    retStr += str.substr(i,1);
    return retStr;
    // add our function to the SharePoint OnLoad event
    _spBodyOnLoadFunctionNames.push("RotatingPictures");
    </script>
    <!-- add your own formatting here... -->
    <center>
    <table border="0" cellpadding="0" cellspacing="0">
    <tr>
    <td id="VU" height="125" width="160" align="center" valign="middle">
    <a name="RotatingImageLnk" id="RotatingImageLnk" alt="click for larger picture">
    <img src="/_layouts/images/dot.gif" name="RotatingImage" id="RotatingImage" border=0>
    </a>
    <span name="RotatingImageMsg" id="RotatingImageMsg"></span>
    </td>
    </tr>
    </table>
    </center>
    Thanks again guys!

  • Is there a way to add images , text and button in the individual marquee of a carousel

    Is there a way to add images , text and button in the individual marquee of a carousel ?

    Write a custom carousel.  Usually carousel components are just ULs that use something like jQuery to rotate through the LIs.  The foundation carousel component is really just designed for some specific use cases.  Generally I would just recommend rolling your own.

  • Rotating images in separate htm document (DW CS4)

    Hi all,
    A few questions:
    1. I created a rotating images htm document by using the swap image function and then changing the code a bit (found this on internet). This works just fine on my PC (LiveView) and the htm document is switching between 3 images. I have placed the document in the images folder. However, when uploaded it doesnt work:
    http://www.competenciagroup.com/images/RotatingImages.htm
    2. If i get this htm document to work on the net I would like to input the htm document with the rotating images into the heading of my main document:
    http://www.competenciagroup.com/ColombiaTravel/index.html
    (just above the menu)
    I could not though figure out how to input the htm document into the existing html document.
    Anybody have any clue on the 2 questions above?
    Thanks in advance,
    Ingvar Malde

    I know plenty of people run into the issue of not being able to see their images while in design view, but mine is the exact opposite.
    My images show up as a tiny blue question mark box in Live View... As well as when I preview it in a browser localy on my machine.
    I think I know why it might be happening but dont know how to fix it...
    When I insert an image DW codes it as such:
    <img src="/images/madintro.jpg" width="470" height="267" />
    The problem seems to lie in DW adding the "/" in front of "images"
    when I manually go in and take out the "/" the image shows magically shows up as it should.
    Why has dreamweaver suddenly defaulted to making bad code? what did I do to cause this issue? And obviously how can I change it back to work again and make the image show in my DW workspace?
    Yes, the slash is exactly the problem. That is known as a Site-root relative link.These types of link are good to use in Templates because they are always the same. They don't need to be "fixed' when you generate a page from your Template into a different folder.
    The downside of using Site-root reltive links, is that you can't access the files locally. You must get the page from a web server. One exception to that is using Preview in Browser (PIB) "Temp" files.
    Read this Tech Note about setting up a Testing Server so you can see these files in Live View and PIB:
    http://blogs.adobe.com/dreamweaver/2008/12/live_view_and_siteroot_relativ.html
    If you want to switch back to using Document relative links, then setthe Relative to: field to be "Document" in the "Browse for file" dialog (folder button next to Link field in PI). This setting is sticky, so all future link will use the same setting.
    Hope this helps,
    Randy

  • Rotating images

    Hello,
    I have created a website which displays an image and have added a button which when is clicked will rotate the image. The problem I am having is that the page seems to be loading before the image is updated and the non rotated image is still displayed on the page. I don't think this is a caching problem because I tried appending a unique name to the image source for each page refresh and the old image still appears.
    The reason why I think that the page is refreshed before the image updated is because if I have a popup window to display before the page is refreshed and let it sit there for a short period of time the page refreshes correctly displaying the rotated image.
    Is there any way to halt the browser from refreshing before my java class is completely done writing out the image? My java class that does the rotation is called from a javaservlet if that helps...
    Thanks,
    -- George

    Ok, thats a little more info.
    Funny, your the first person I ever heard of that is using velocity rather than a real web langauge.
    Anyway, I think what your doing is confusing where and when what code should executed. Its a tremendously common misunderstanding.
    If you use a java servlet to get your image names, your going to have to have the page (or part of the page in a frame, iframe or somthing equally lame ) reload.
    If you want your page to have a different image load when somone hits a new link, then you can worry about vm code and getting servlet names, and you *wont use javascript.
    If you want to have an image appear when you highlight a link or have time pass or somthing, then you will use javascript completely to do this, and you will only use VM to write the names and populate the javascript array.
    ~kullgen

  • Script that rotates a PNG in Photoshop?

    I have the following Photoshop ExtendScript (.jsx) script which rotates the image canvas, but doesn't rotate the contents:
    #target photoshop
    var doc = app.open(...);       // open the .png file
    if (doc.width > doc.height) {  // check if this document is landscape
      doc.rotateCanvas(90);        // rotate the canvas to portrait
      // but how to rotate the contents?
    I would like to rotate the entire image, contents included. I've  tried also rotating all the document's layers, and art layers, but  nothing works.

    hiltoncampbell wrote:
    #target photoshop
    var doc = app.open(...);       // open the .png file
    if (doc.width > doc.height) {  // check if this document is landscape
      doc.rotateCanvas(90);        // rotate the canvas to portrait
      // but how to rotate the contents?
    While the code look good it may not work??? You see it does not insure what ruler units is.   So if your ruler units were set to something like persent the if statement would read 
    if ( 100% is greater then 100% )  rotate
    I have a script like that RotatePortrait.jsx  to rotate portrait to landscape looks like this
    <javascriptresource>
    <about>$$$/JavaScripts/RotatePortrait/About=JJMack's Rotate Portrait.^r^rCopyright 2009 Mouseprints.^r^rScript utility for action.^rNOTE:Rotate Portrait to Landscape!</about>
    <category>JJMack's Action Utility</category>
    </javascriptresource>
    Rotate();
    function Rotate() {
    // validate that a document is open
    if (documents.length < 1) {
    alert("No Open Document!");
    return;
    var orig_ruler_units = app.preferences.rulerUnits;
    app.preferences.rulerUnits = Units.PIXELS;
    // Rotate portrait to landscape orientation
    if (activeDocument.height > activeDocument.width) activeDocument.rotateCanvas(90);
    // Reset units to original settings
    app.preferences.rulerUnits = orig_ruler_units;

  • Rotate dragged shape on button click

    Hi guys,
    I need help here. I want to do a drawing application where user can resize and rotate a shape. I have created a shape which I can drag around but how to make it rotate upon clicking on button?? Let say when I select the shape and click on 'rotate' button my shape will be rotate by 90 degree. After that the rotated shape can still be drag. Any help would be appreciated.

    Hi Darryl.Burke,
    Thanks for your reply, yes I use AffineTransform methods to rotate the shape. Is there any different with other rotation method?? Ok when I use setToRotation, the shape indeed rotate to the correct position but when I click the shape return back to its original and other weird things happen. Below is the code. Can you please point out the part that I done it wrong please. Thanks.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.util.Vector;
    import javax.swing.border.CompoundBorder;
    import java.io.*;
    public class RotateShape
         private static void createAndShowGUI() {
            //Create and set up the window.
           JFrame.setDefaultLookAndFeelDecorated(true);      
           Viewer frame = new Viewer();
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           frame.setVisible(true);
        public static void main(String[] args)
             javax.swing.SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                   createAndShowGUI();
    class Viewer extends JFrame implements ActionListener
         JMenuBar menuBar;
         drawRect buildDesign;
        public Viewer()
           Toolkit kit = Toolkit.getDefaultToolkit();
            Dimension screenSize = kit.getScreenSize();
            int screenHeight = screenSize.height;
            int screenWidth = screenSize.width;
            // center frame in screen
              setSize(700, 600);
              setLocation(screenWidth / 4, screenHeight / 4);
              setResizable(false);
            buildDesign = new drawRect();
            buildDesign.setBorder(BorderFactory.createEmptyBorder(0, 2, 3, 3));
            JTabbedPane tabbed = new JTabbedPane();
            tabbed.addTab("Design", buildDesign);
            //tabbed.addTab("Viewer", buildViewer());
            tabbed.setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6),
                                                tabbed.getBorder()));
            //------------------------End of Tabbed Pane----------------------------------------------------//
          JPanel pane = new JPanel();
          Button rectButton = new Button("Rect");
          rectButton.addActionListener(this);
          pane.add(rectButton);
          Button deleteButton = new Button("Delete");
          deleteButton.addActionListener(this);
          pane.add(deleteButton);
          Button rotateButton = new Button("Rotate");
          rotateButton.addActionListener(this);
          pane.add(rotateButton);
          JScrollPane scroller = new JScrollPane(pane);
          scroller.setOpaque(false);
          scroller.getViewport().setOpaque(false);
          scroller.setBorder(new CompoundBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6),
                                                  scroller.getBorder()));
               //------------------------End of Build Item list----------------------------------------------//
          JPanel content = new JPanel(new BorderLayout());
          content.setOpaque(false);
          content.add(tabbed, BorderLayout.CENTER);
          content.add(scroller, BorderLayout.WEST);
          add (content, BorderLayout.CENTER);
          //------------------------End of add content----------------------------------------------//
              public void actionPerformed(ActionEvent evt) {
               // Respond to a command from one of the window's menu.
          String command = evt.getActionCommand();
          if (command.equals("Rect"))
             buildDesign.addShape(new RectShape());
          else if (command.equals("Delete"))
             buildDesign.delete();
          else if (command.equals("Rotate"))
             buildDesign.rotate();
    class drawRect extends JPanel implements ActionListener, MouseListener, MouseMotionListener
             Image offScreenCanvas = null;   // off-screen image used for double buffering
                 Graphics offScreenGraphics;     // graphics context for drawing to offScreenCanvas
                 Vector shapes = new Vector();   // holds a list of the shapes that are displayed on the canvas
                 Color currentColor = Color.black; // current color; when a shape is created, this is its color
                 float alpha;
            drawRect() {
            // Constructor: set background color to white set up listeners to respond to mouse actions
          setBackground(Color.white);
          addMouseListener(this);
          addMouseMotionListener(this);
       synchronized public void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g;
            // In the paint method, everything is drawn to an off-screen canvas, and then
            // that canvas is copied onto the screen.
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
          g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
          makeOffScreenCanvas();
          g2.drawImage(offScreenCanvas,0,0,this); 
          AlphaComposite composite = AlphaComposite.getInstance(AlphaComposite.SRC_OUT,alpha);
              g2.setComposite(composite);
          g2.setColor(Color.GRAY);
          drawGrid(g, 20); 
       public void update(Graphics g) {
            // Update method is called when canvas is to be redrawn.
            // Just call the paint method.
          super.paintComponent(g);
       void makeOffScreenCanvas() {
             // Erase the off-screen canvas and redraw all the shapes in the list.
             // (First, if canvas has not yet been created, then create it.)
          if (offScreenCanvas == null) {
             offScreenCanvas = createImage(getSize().width,getSize().height);
             offScreenGraphics = offScreenCanvas.getGraphics();
          offScreenGraphics.setColor(getBackground());
          offScreenGraphics.fillRect(0,0,getSize().width,getSize().height);
          int top = shapes.size();
          for (int i = 0; i < top; i++) {
             Shape s = (Shape)shapes.elementAt(i);
             s.draw(offScreenGraphics);
            private void drawGrid(Graphics g, int gridSpace) {
          Insets insets = getInsets();
          int firstX = insets.left;
          int firstY = insets.top;
          int lastX = getWidth() - insets.right;
          int lastY = getHeight() - insets.bottom;
          //Draw vertical lines.
          int x = firstX;
          while (x < lastX) {
            g.drawLine(x, firstY, x, lastY);
            x += gridSpace;
          //Draw horizontal lines.
          int y = firstY;
          while (y < lastY) {
            g.drawLine(firstX, y, lastX, y);
            y += gridSpace;
        public void actionPerformed(ActionEvent evt)
         synchronized void addShape(Shape shape) {
              // Add the shape to the canvas, and set its size/position and color.
              // The shape is added at the top-left corner, with size 50-by-30.
              // Then redraw the canvas to show the newly added shape.
          shape.setColor(Color.red);
          shape.setColor(currentColor);
           shape.reshape(3,3,70,10);
          shapes.addElement(shape);
          repaint();
         void clear() {
             // remove all shapes
           shapes.setSize(0);
           repaint();
        void delete() {
             // remove selected shapes
                  shapes.removeElement(selectedShape);
                   repaint();
       void rotate() {     
                     //shapes.addElement(selectedShape);
                  selectedShape.setToRotate(true);
                  //shapes.removeElement(selectedShape);
                   repaint();
       Shape selectedShape = null;
       Shape shapeBeingDragged = null;  // This is null unless a shape is being dragged.
                                        // A non-null value is used as a signal that dragging
                                        // is in progress, as well as indicating which shape
                                        // is being dragged.
       int prevDragX;  // During dragging, these record the x and y coordinates of the
       int prevDragY;  //    previous position of the mouse.
        Shape clickedShape(int x, int y) {
             // Find the frontmost shape at coordinates (x,y); return null if there is none.
          for ( int i = shapes.size() - 1; i >= 0; i-- ) {  // check shapes from front to back
             Shape s = (Shape)shapes.elementAt(i);
             if (s.containsPoint(x,y))
                  s.tickSelected(true);
                  selectedShape = s;
                return s;
                else
                s.tickSelected(false);
                repaint();
          return null;
       synchronized public void mousePressed(MouseEvent evt) {
             // User has pressed the mouse.  Find the shape that the user has clicked on, if
             // any.  If there is a shape at the position when the mouse was clicked, then
             // start dragging it.  If the user was holding down the shift key, then bring
             // the dragged shape to the front, in front of all the other shapes.
          int x = evt.getX();  // x-coordinate of point where mouse was clicked
          int y = evt.getY();  // y-coordinate of point                                  
             shapeBeingDragged = clickedShape(x,y);
             if (shapeBeingDragged != null) {
                prevDragX = x;
                prevDragY = y;
                if (evt.isShiftDown()) {                 // Bring the shape to the front by moving it to
                   shapes.removeElement(shapeBeingDragged);  //       the end of the list of shapes.
                   shapes.addElement(shapeBeingDragged);
                   repaint();  // repaint canvas to show shape in front of other shapes
       synchronized public void mouseDragged(MouseEvent evt) {
              // User has moved the mouse.  Move the dragged shape by the same amount.
          int x = evt.getX();
          int y = evt.getY();
          if (shapeBeingDragged != null) {
             shapeBeingDragged.moveBy(x - prevDragX, y - prevDragY);
             prevDragX = x;
             prevDragY = y;
             repaint();      // redraw canvas to show shape in new position
       synchronized public void mouseReleased(MouseEvent evt) {
              // User has released the mouse.  Move the dragged shape, then set
              // shapeBeingDragged to null to indicate that dragging is over.
              // If the shape lies completely outside the canvas, remove it
              // from the list of shapes (since there is no way to ever move
              // it back onscreen).
          int x = evt.getX();
          int y = evt.getY();
          if (shapeBeingDragged != null) {
             shapeBeingDragged.moveBy(x - prevDragX, y - prevDragY);
             if ( shapeBeingDragged.left >= getSize().width || shapeBeingDragged.top >= getSize().height ||
                     shapeBeingDragged.left + shapeBeingDragged.width < 0 ||
                     shapeBeingDragged.top + shapeBeingDragged.height < 0 ) {  // shape is off-screen
                shapes.removeElement(shapeBeingDragged);  // remove shape from list of shapes
             shapeBeingDragged = null;
             repaint();
       public void mouseEntered(MouseEvent evt) { }   // Other methods required for MouseListener and
       public void mouseExited(MouseEvent evt) { }    //              MouseMotionListener interfaces.
       public void mouseMoved(MouseEvent evt) { }
       public void mouseClicked(MouseEvent evt) { }
       abstract class Shape implements Serializable{
          // A class representing shapes that can be displayed on a ShapeCanvas.
          // The subclasses of this class represent particular types of shapes.
          // When a shape is first constucted, it has height and width zero
          // and a default color of white.
       int left, top;      // Position of top left corner of rectangle that bounds this shape.
       int width, height;  // Size of the bounding rectangle.
       Color color = Color.white;  // Color of this shape.
       boolean isSelected;
       boolean isRotate;
       AffineTransform t;
       AffineTransform origTransform;
       void reshape(int left, int top, int width, int height) {
             // Set the position and size of this shape.
          this.left = left;
          this.top = top;
          this.width = width;
          this.height = height;
       void moveTo(int x, int y) {
              // Move upper left corner to the point (x,y)
          this.left = x;
          this.top = y;
       void moveBy(int dx, int dy) {
              // Move the shape by dx pixels horizontally and dy pixels veritcally
              // (by changing the position of the top-left corner of the shape).
          left += dx;
          top += dy;
       void setColor(Color color) {
              // Set the color of this shape
          this.color = color;
       void tickSelected (boolean draw) {
                 // If true, a red outline is drawn around this shape.
             isSelected = draw;
       void setToRotate (boolean draw) {
                 // If true, the shape will rotate 90 deg
             isRotate = draw;
       boolean containsPoint(int x, int y) {
             // Check whether the shape contains the point (x,y).
             // By default, this just checks whether (x,y) is inside the
             // rectangle that bounds the shape.  This method should be
             // overridden by a subclass if the default behaviour is not
             // appropriate for the subclass.
          if (x >= left && x < left+width && y >= top && y < top+height)
             return true;
          else
                      return false;
       abstract void draw(Graphics g); 
             // Draw the shape in the graphics context g.
             // This must be overriden in any concrete subclass.
         }  // end of class Shape
    class RectShape extends Shape {
          // This class represents rectangle shapes.
       void draw(Graphics g) {
            Graphics2D g2 = (Graphics2D) g;
            Rectangle2D wall = new Rectangle2D.Double(left,top,width,height);
            Rectangle2D border = new Rectangle2D.Double(left-2,top-2,width+3,height+3);
            origTransform = g2.getTransform();
            if ((isRotate) && (isSelected))
                   t = new AffineTransform();
                      t.setToRotation ((Math.toRadians (90)),(left+width/2) , (top+height/2) );
                      g2.transform(t);
                      g2.setColor(color);
                   g2.fill(wall);
                   g2.setColor(Color.red);
                    g2.draw(border);
                    g2.setTransform( origTransform );
                    return;
            else
                 g2.setColor(color);
              g2.fill(wall);
            if ((isSelected)&& !(isRotate))
                         g2.setColor(Color.red);
                         g2.draw(border);
                              else
                                   g2.setColor(Color.black);
                                   g2.draw(wall);
    }

Maybe you are looking for