Returning a ratio

Hey all
I am trying to calculate the "popularity" of an item. Items can be rated using integers from 0 to 5. What I do now is that I only calculate the average of all the ratings for an item, this is of course not enough because the number of times an item has been rated should also be an important factor when deciding an item's popularity.
(An item with the average rating of 5 which has been rated 20 times should be more popular than an item which has the average rating of 5 and has been rated 10 times for example).
What is the best way for returning the avg Rating/n Ratings as a Double? I can always return the ratio as a String, but I don't know if that's the smoothest way of doing it. I am thinking of doing: avg rating * n ratings / n ratings. Is this a good way of returning the ratio as a Double or are there more accurate algorithms for doing it?
Code so far (will return Double when I've figured out which algorithm to use)
public Integer calculatePopularity(List<Integer> values) {
     if(values.size() == 0) {
          return 0;
     try {
          Integer result = 0;
          for(Integer i : values) {
          result = result + i;
          return result * values.size()/values.size();
          } catch (Exception e) {
               e.printStackTrace();
               return 0;
}

You need to come up with some weighting function yourself, and this function would take an average rating and put a 'reliability skew' (between 0 and 1) on it. I'm sure there is material for this online, because I'm certain that this paradigm must come up all the time, what with the wide variety of sites that support some sort of user rating or another.
Just thinking out loud, this might possibly some function on the domain [0, infinity) that zeroes at x=0, then tends exponentially to 1 as x-> inifinity. The initial steepness of the funtion would depend on you, how quickly you see a rating getting reliable as more and more people are adding to it.
Something like
rating = (1-e^(-(steepness)*raters)) * average rating
Of course, there are plenty of other functions you could use, or you could modify this exponential. You can for example round out curve that this relation gives more by adding a coefficient to the exponential term, and then adjusting the -(steepness)* raters with a +k to move the zero back to x=0.
Not being an applied mathematician or a sociologist, I don't know how to quantify and model 'reliability' but, as I say, there is no doubt material on this on the web

Similar Messages

  • I need Due Date by periods (ratios) for my Credit Account

    Hi people,
    I've a problem to obtain the information related with "Due date".
    In my Report I've the info in a internal table. I've KUNNR number (Credit Account), and now, I need find the columns and data that
    you can obtains with "s_alr_87012168" transaction.
    I looked something by the web related with "DETERMINE_DUE_DATE" function, but this function not returns all ratios I hope (like
    "s_alr_87012168" transaction.
    Customer   Total        Not Expired   Expired     0 to 3 months  3 to 6 months  6 to 12 months   >1 year    %Expired/Deud
    Currency                  1 EUR           1 EUR        1 EUR              1 EUR              1 EUR                 1 EUR       1 EUR
    PR, S.L.      1.205,46   0,00          1.205,46     0,00                0,00                  0,00                   1.205,46   100,00
    Result        1.205,46   0,00          1.205,46     0,00                0,00                  0,00                   1.205,46   100,00
    Can someone help me?, Do U know some standard function for my target?
    Thanks in advance...
    Edited by: Sergio Galindo on Oct 6, 2009 4:10 PM

    It's a really bad idea to post your email address - it's an invitation to spam - and I've asked the Hosts to remove it.
    It sounds as if you have already found the method to change your card details, but just to confirm: go to the iTunes Store. Click 'Account' under 'Quick links' at the right. Log in.
    Where it says 'Payment Information' click on 'Edit' to the right of it.
    You should then be able to enter the correct card details.
    Is this not working? Do you get an error message?

  • How to calculate a boolean based on data from a table fed by a BI Query

    Hi Gurus,
    I am currently struggling with the following issue:
    - I have a query in my VC model wich returns 4 ratios
    - I put the result of the query in a table in the VC model
    - then, I added a column in the table. this column is a boolean which should be true if the value of one of my 4 ratios is not 0, otherwise, it is false
    - I want that boolean to be "updatable" by the users.
    I tried to define the default value of the boolean based on the value from the signficant ratio... no luck
    I tried to change the value from the configuration tab of the column, but then I can not update afterwards....
    Has anyone ever seen that issue and found a solution ?
    Thansk for your help
    PY

    Hi Deep!
    Thanks for your feedback! I felt a bit alone in my world before you answered
    Your idea is great and it would work if I hadn't to display the data with a hierarchy.
    Actually, the only thing I did not mention is that we are posting data against fiscal period, and we are budgeting for the next 10 years (no comment on that, and the precision we could reach ). So, to display the information we are using a cusomized hierarchy on 0FISCPER using 0FISCYEAR.
    So when I used your option, the hierarchy has been deactivated on the table. But to be sure I correctly implemented your proposition, here are the steps we used :
    1) connect the query output port "data" to the share
    2) add the boolean in the share
    3) map the boolean with the rule based on the data coming from the query
    4) connect the share to the table.
    Note that we the current version we use of VC I am not able to edit the field mapping between the share and the table...
    Did I miss something ?
    If yes, could you drive me to the correct procedure ?
    If no, would you have any idea ? I already tried to change the default value of the field in the "define Data" maintenance popup of the table. I also tried to assign a value to the boolean based on the Action option of the column used in my condition...
    Thanks for your help
    PY

  • How to embed SWT to swings

    I have found information regarding how to embed Swings in SWT.
    But i have to embed Swt browser in swings
    Please see the links for examples:
    http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/Bringupabrowser.htm
    http://www.java2s.com/Code/Java/SWT-JFace-Eclipse/EmbedSwingandAWTinSWT.htm
    I have to show two browsers in same window which i have partially done by embeding swings in swt. but need the otherway.
    Here is that code:
    import java.awt.Color;
    import java.awt.Frame;
    import java.awt.Panel;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    import javax.swing.JSeparator;
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.awt.SWT_AWT;
    import org.eclipse.swt.browser.Browser;
    import org.eclipse.swt.browser.LocationEvent;
    import org.eclipse.swt.browser.LocationListener;
    import org.eclipse.swt.browser.ProgressEvent;
    import org.eclipse.swt.browser.ProgressListener;
    import org.eclipse.swt.browser.StatusTextEvent;
    import org.eclipse.swt.browser.StatusTextListener;
    import org.eclipse.swt.layout.GridData;
    import org.eclipse.swt.layout.GridLayout;
    import org.eclipse.swt.widgets.Composite;
    import org.eclipse.swt.widgets.Display;
    import org.eclipse.swt.widgets.Event;
    import org.eclipse.swt.widgets.Label;
    import org.eclipse.swt.widgets.Listener;
    import org.eclipse.swt.widgets.ProgressBar;
    import org.eclipse.swt.widgets.Shell;
    import org.eclipse.swt.widgets.Text;
    import org.eclipse.swt.widgets.ToolBar;
    import org.eclipse.swt.widgets.ToolItem;
    import com.jgoodies.forms.layout.CellConstraints;
    import com.jgoodies.forms.layout.FormLayout;
    public class BringUpBrowser {
    public static void main(String[] args) {
         BringUpBrowser browser= new BringUpBrowser();
         browser.showBrowser();
    public void showBrowser(){
    Display display = new Display();
    final Shell shell = new Shell(display);
    GridLayout gridLayout = new GridLayout();
    gridLayout.numColumns = 3;
    shell.setLayout(gridLayout);
    shell.setMaximized(true);
    final Browser browser1 = new Browser(shell, SWT.NONE);
    GridData data1 = new GridData();
    data1.horizontalAlignment = GridData.FILL;
    data1.verticalAlignment = GridData.FILL;
    data1.horizontalSpan = 3;
    data1.grabExcessHorizontalSpace = true;
    data1.grabExcessVerticalSpace = true;
    browser1.setLayoutData(data1);
    browser1.setUrl("www.indussoftware.com");
    ToolBar toolbar = new ToolBar(shell, SWT.NONE);
    ToolItem itemBack = new ToolItem(toolbar, SWT.PUSH);
    itemBack.setText("Back");
    ToolItem itemForward = new ToolItem(toolbar, SWT.PUSH);
    itemForward.setText("Forward");
    ToolItem itemStop = new ToolItem(toolbar, SWT.PUSH);
    itemStop.setText("Stop");
    ToolItem itemRefresh = new ToolItem(toolbar, SWT.PUSH);
    itemRefresh.setText("Refresh");
    ToolItem itemGo = new ToolItem(toolbar, SWT.PUSH);
    itemGo.setText("Go");
    GridData data = new GridData();
    data.horizontalSpan = 3;
    toolbar.setLayoutData(data);
    Label labelAddress = new Label(shell, SWT.NONE);
    labelAddress.setText("Address");
    final Text location = new Text(shell, SWT.BORDER);
    data = new GridData();
    data.horizontalAlignment = GridData.FILL;
    data.horizontalSpan = 2;
    data.grabExcessHorizontalSpace = true;
    location.setLayoutData(data);
    final Browser browser = new Browser(shell, SWT.NONE);
    data = new GridData();
    data.horizontalAlignment = GridData.FILL;
    data.verticalAlignment = GridData.FILL;
    data.horizontalSpan = 3;
    data.grabExcessHorizontalSpace = true;
    data.grabExcessVerticalSpace = true;
    browser.setLayoutData(data);
    final Label status = new Label(shell, SWT.NONE);
    data = new GridData(GridData.FILL_HORIZONTAL);
    data.horizontalSpan = 2;
    status.setLayoutData(data);
    final ProgressBar progressBar = new ProgressBar(shell, SWT.NONE);
    data = new GridData();
    data.horizontalAlignment = GridData.END;
    progressBar.setLayoutData(data);
    Composite composite = new Composite(shell, SWT.EMBEDDED);
    data = new GridData();
    data.horizontalAlignment = GridData.FILL;
    data.verticalAlignment = GridData.CENTER;
    data.horizontalSpan = 3;
    composite.setLayoutData(data);
    Frame frame = SWT_AWT.new_Frame(composite);
    JPanel panel = new JPanel();
    panel.setLayout(new FormLayout("0:grow(0.4),0:grow(0.2),0:grow(0.4)","5dlu,5dlu,16dlu"));
    frame.add(panel);
    CellConstraints cc = new CellConstraints();
    JButton button = new JButton("Close");
    panel.add(new JSeparator(),cc.xyw(1, 1, 3));
    panel.add(button,cc.xy(2, 3));
    button.addActionListener(new ActionListener(){
              public void actionPerformed(ActionEvent e) {
                   //this = null;
    //end of chakri
    /* event handling */
    Listener listener = new Listener() {
    public void handleEvent(Event event) {
    ToolItem item = (ToolItem) event.widget;
    String string = item.getText();
    if (string.equals("Back"))
    browser.back();
    else if (string.equals("Forward"))
    browser.forward();
    else if (string.equals("Stop"))
    browser.stop();
    else if (string.equals("Refresh"))
    browser.refresh();
    else if (string.equals("Go"))
    browser.setUrl(location.getText());
    browser.addProgressListener(new ProgressListener() {
    public void changed(ProgressEvent event) {
    if (event.total == 0)
    return;
    int ratio = event.current * 100 / event.total;
    progressBar.setSelection(ratio);
    public void completed(ProgressEvent event) {
    progressBar.setSelection(0);
    browser.addStatusTextListener(new StatusTextListener() {
    public void changed(StatusTextEvent event) {
    status.setText(event.text);
    browser.addLocationListener(new LocationListener() {
    public void changed(LocationEvent event) {
    if (event.top)
    location.setText(event.location);
    public void changing(LocationEvent event) {
    itemBack.addListener(SWT.Selection, listener);
    itemForward.addListener(SWT.Selection, listener);
    itemStop.addListener(SWT.Selection, listener);
    itemRefresh.addListener(SWT.Selection, listener);
    itemGo.addListener(SWT.Selection, listener);
    location.addListener(SWT.DefaultSelection, new Listener() {
    public void handleEvent(Event e) {
    browser.setUrl(location.getText());
    shell.open();
    browser.setUrl("http://google.co.in");
    while (!shell.isDisposed()) {
    if (!display.readAndDispatch())
    display.sleep();
    display.dispose();
    Here Iam facing problems while adding Listeners.
    Can u help me in this?

    GANGINENI wrote:
    hi i developed a program for timer in applet, i want to include it in to jFrame, can some one help me,i am developing program in netbeansYes.
    1) ....
    h1. Edit:
    in light of camickr's note, I am deleting my post. The original poster is now on my DNH list and will remain there until his behavior changes.
    Edited by: Encephalopathic on Oct 31, 2008 2:20 PM

  • ABAP Logic - This Month This Year to This Month Last Year problem

    Hi All,
    I have a following requirement ... the report currently compares This Month This Year to This Month Last Year. But this is not a valid comparison for the user until the end of the month is reached as only then is it comparing 2 full months. We would like to use a formula replacement path variable to work out which proportion of data we have for this month. ie. if its day 15, we have 50% of data (if there are 30 days in the month - this just an example), therefore we should only show 50% of This Month Last Years column so that the comparison between the 2 is sensical.
    So I'd like the formula variable to return a ratio or percentage which I can then use in a calculated key figure in the query to pro-rata the last year data.
    The query currently displays data by Fiscal Period, so when working out the ratio I would need to check which Fiscal Period we're in and also consider that the data is loaded every night, so on the 1st day of a Fiscal Period we are comparing everything up until yesterday.
    Can anyone see in problem with the logic of this, or better yet, has anyone done this before and maybe has some code for me? Is there another way I could be doing this?
    Edited by: Julius Bussche on Sep 19, 2008 4:31 PM

    Have you tried google for this Error Message...
    http://support.microsoft.com/kb/959077

  • BEX reporting 0amount without tax i need it with tax

    hi guys,
    I have a little problem, I have a ratio that is 0amount but I need through a variable, this ratio goes to a function module that depending on the month in which that amount was to get the Tax and I return the ratio to the Tax added, all this is to file a report on bex-BPS.
    the report show me the ratio without Tax, and i need that the value in the function module look when it was introduced and to compare it with the taxes of that month and then enter in the cell the value with tax add
    Excuse me, for my bad English.
    Thanks and best regards,
    Leon.

    hi Peter, thanks for replying...
    Example:
    month1--- month2-- month3
    Board of Directors--50 $ 60 $----100 $
    Finance Division -
    32 $--10 $--
    40 $
    Maintenance Division--21 $40 $--
    50 $
    tax month1: 10%, month2 15%, month3: 20%
    and should be like this:.
    month1---month2--- month3
    Board of Directors--55 $ 69 $--
    120 $
    Finance Division--35,2 $---11,5 $--
      48 $
    Maintenance Division----23,1 $46 $--
      60 $
    the values come from 0ammount and taxes are in a Table of premises entered by the user,
    Excuse me, for my bad English.
    and Thanks Peter
    Leon.

  • Query on Anonymous Logon Process...Please Help.....Urgent.....

    Hello,
    I am working on EP6 SP4 and trying to implement anonymous login process.
    I read the help giving the implementation process but I have a query abt the same:
    1> As given in the Help Pages, we have to set the former index.html to the iView URL in the location.replace attribute.
    2> There would also be a link for authorized users wherein the authorized persons may use the Portal as before using their username & password resp.
    3> My Query ==> When an authorized user logins into Portal, internally would the changed index.html be set back to the default index.html. That is, location.replace = actual default Portal location.
    If true, how would the anonymous process behave the next time????
    I would appreciate if you would please help me solve this query. I am trying to find the solution since 2 days but failed.......
    Thanking you and Warm Regards,
    Ritu R Hunjan

    David,
    As rightly pointed out , you cannot get the plan value for 9 days if you do not have 0calday. However some things you can do...
    1. Have a virtual KF which gets the number of days from the current calendar day ( system date ) to the first date of the month - this can be written with a simple exit since the first date is fixed.
    2. calculate the plan value from that - pro rated plan value = plan value for month / number of days in month * number of days elapsed. If need be have the virtual KF return the ratio of number of days elapsed/number of days in the month
    3. Now you can do the comparison assuming that the value of actuals will be till the current date and not beyond.
    This is assuming that you can write a Virtual KF and the number of records is less enough to avoid any performance issues
    Hope it helps..
    Arun
    Assign points if helpful
    Message was edited by: Arun Varadarajan

  • Query  -  please help - Urgent

    Hi,
    Currently we have a query (Created on Multicube - one is sales plan cube and another is Sales actuals).
    When we run the query on a particular day (example: 7/10/2006), the report looks like as below:
    Cal.Year/Month       Sales plan     Sales Actuals
    Jan'06               310             305
    Feb'06               280             277
    Mar'06               310             309
    Apr'06               300             300
    MAy'06               310             305
    June'06              300             305
    July'06              310             90
    The current report shows the whole month's Sales Plan (July'06 - 310) with Actual Sales for 9 days(for July'06 - 90). Whereas, We want to compare the sales Plan (first 9 days of the month) against the sales actuals for 9 days.
    We do not have 0calday in both the cubes. Please help.
    Thanks,

    David,
    As rightly pointed out , you cannot get the plan value for 9 days if you do not have 0calday. However some things you can do...
    1. Have a virtual KF which gets the number of days from the current calendar day ( system date ) to the first date of the month - this can be written with a simple exit since the first date is fixed.
    2. calculate the plan value from that - pro rated plan value = plan value for month / number of days in month * number of days elapsed. If need be have the virtual KF return the ratio of number of days elapsed/number of days in the month
    3. Now you can do the comparison assuming that the value of actuals will be till the current date and not beyond.
    This is assuming that you can write a Virtual KF and the number of records is less enough to avoid any performance issues
    Hope it helps..
    Arun
    Assign points if helpful
    Message was edited by: Arun Varadarajan

  • Everytime I open itunes the cover flow size returns to default. How Can I lock the aspect ratio?

    Whenever I shut down my computer and restart it, the aspect ratio of the images in itunes coverflow reset to their default size. How can I keep them where I set them.

    I have an issue somewhat like that, except it doesn't happen when I shut down or restart my computer. Mine resets each time I click the green resize button (using an iMac) to minimize iTunes to the mini player. Oddly enough, if I resize the cover flow, switch to a different view (ie. library without cover flow) and then hit the resize button to switch to mini player, upon maximizing iTunes again, I can switch back to the cover flow and it will have stayed the same size. Obviously I'm not going to go through that process each time I want to minimize iTunes to mini player, but when I simply minimize it when in cover flow view, as you mentioned in your post, it resets the aspect ratio each time. Clearly this isn't a massive issue as I'm still able to use all the other functions of iTunes perfectly fine, but I have to admit it is very annoying and has been persistent for the last few hours. Please if you've found a fix let me know, however I noticed you are using Windows 7 so we likely have two completely different issues.

  • Picking returns false results when aspect ratio is different from 1:1

    Hi,
    When using picking with perspective projection when the aspect ratio is different from 1:1 I get false results.
    Any idea how to fix it ?
    Thanks
    Ophir
    Following is the related code:
    // For the perspective projection
    Transform3D prespective = new Transform3D();
    prespective.perspective(hFov, Math.tan(hFov/2)/Math.tan(vFov/2), 1f, 30f);
    view.setProjectionPolicy(View.PERSPECTIVE_PROJECTION);
    view.setLeftProjection(prespective);
    // Picking code
    Point3d eye_pos = new Point3d();
    Point3d mouse_pos = new Point3d();
    canvas.getCenterEyeInImagePlate(eye_pos);
    canvas.getPixelLocationInImagePlate(x, y, mouse_pos);
    Transform3D motion = new Transform3D();
    canvas.getImagePlateToVworld(motion);
    motion.transform(eye_pos);
    motion.transform(mouse_pos);
    Vector3d direction = new Vector3d(mouse_pos);
    direction.sub(eye_pos);
    PickRay ray = new PickRay(eye_pos, direction);

    I tried to download the FireFox setup from both locations you mentioned. I could not reproduce your problem. Always the same file with the same MD5 hash:
    C:\tmp>md5sum "Firefox Setup 18.0.2.exe
    181ac7211db54e793845e8c7216c1a8b *Firefox Setup 18.0.2.exe
    Is it still reproducible from your location? Where are you located?

  • Query help,  Percentages / ratio to reports / nests

    Hi
    I have a query that returns data like this
    D_NO POINTS COUNT_POINTS ID_COUNT
    4002 L_T_69 12 282
    4219 L_T_69 1 151
    4228 L_T_69 18 193
    4229 L_T_69 7 181
    4230 L_T_69 0 197
    I need to also output a column that works out a percentage of count_points and Id_count. e.g 12/282 * 100 = 4.2
    I had a try with ratio to reports function but no joy for me. I think i need to add in
    another nested select or something but what i was trying wasnt working.
    Can anyone help.
    here is the query so far
    SELECT D_NO,
    GROUPS.POINTS,
    DECODE(GROUPS.POINTS, 'L_T_69' , L_T_69) AS COUNT_POINTS,
    ID_COUNT
    FROM
         (SELECT D_NO,
         Count (CASE WHEN VERBAL <= 69 THEN 1
              END) AS L_T_69,
         COUNT(ID_NUMBER) AS ID_COUNT
         FROM TBL_1
         WHERE VERBAL IS NOT NULL
         group by D_NO)
    TBL_1,
    ( SELECT 'L_T_69' POINTS FROM DUAL )GROUPS
    thank you

    Not sure if this is what you're looking for but it may give you some clues:
    select object_type
          ,has_a_c
          ,type_total
          ,round(100 * (has_a_c / type_total),2) ratio
    from
       select object_type
             ,sum (case when instr(object_name,'C') <> 0 then 1
                        else 0
                   end) has_a_c
             ,count(*) type_total
       from   all_objects
       group by object_type
    OBJECT_TYPE          HAS_A_C   TYPE_TOTAL   RATIO
    CONSUMER GROUP             1            2      50
    EVALUATION CONTEXT         1            1     100
    FUNCTION                  50          113   44.25
    INDEX                      7           20      35
    LIBRARY                    0            2       0
    OPERATOR                   1            2      50
    PACKAGE                  500         1158   43.18
    PACKAGE BODY             487         1126   43.25
    PROCEDURE                 54           86   62.79
    SEQUENCE                  62          116   53.45
    SYNONYM                 1060         2298   46.13
    TABLE                    365          721   50.62
    TABLE PARTITION           15           15     100
    TYPE                     104          272   38.24
    VIEW                     834         1896   43.99
    15 rows selected.

  • How do I return an unopened refurbished iBook for a complete refund?

    I ordered a refurbished 14 inch ibook a while ago and it has been sitting in an unopened box ever since. It cost about $1050. I bought this before the new intel MacBook's came out, and now that they are out, they are much better than the ibook's. Plus the iBook 14 inch is a weird ratio.
    How would i return my unopened ibook for a complete refund and only pay like 50 bucks more for a new macbook?

    Welcome to Apple Discussions!
    It depends on the store you bought it from. Read the policies of the store you bought it from, if they are posted on the web. Your "awhile ago" doesn't tell us anything about the number of days. If you have no idea when you bought it, but bought it by credit card, you can usually call the store and ask them with your credit card number to verify when that was. Most stores I've seen have a time limit on returns. Some do not accept refurbished products back. It is best to check with the individual store.

  • Using Win 10 there is a need for an app to determine the full device display area and aspect ratio programitically; the dimensions are needed to create full-screen bitmap.

    While Windows.Current.Bounds returns the application windows size, in order to create a full-screen bitmap my app would need to retrieve the full display area  of the device. I cannot even get the aspect ratio.
    Pre-Win10, using Windows.Current.Bounds I can create a bitmap of whatever size application window the user is seeing. When the user is showing my app at full screen, I can therefore get the full display area and aspect ratio of the device and create a full-screen
    bitmap.
    With Win10, the user would need to know to hide the taskbar and also display at full-screen before an app can retrieve the display area and aspect ratio using Windows.Current.Bounds.
    Before Win10 it's obvious to the user that full-screen is or is not being used. When I create the bitmap, I create it to fit the application window. When the app is displayed full screen, the bitmap will be full screen. Also, the app starts full-screen so
    I can detect the display area at startup if I need to.
    With Win10, to the user the app "looks like" it is full screen with the taskbar displayed even though it's not really full screen.
    I believe that in Win10 determining the full display area will be useful and not just retrieving the application window size.
    musical9

    Rob, Is this forum best way to get my suggestion to the development team?
    Before Win10 it's obvious to the user that full-screen is or is not being used. When I create the bitmap, I create it to fit the application window. When the app is displayed full screen, the bitmap will be full screen. Also, the app starts full-screen
    so I can detect the display area at startup if I need to.
    With Win10, to the user the app "looks like" it is full screen with the taskbar displayed even though it's not really full screen.
    Yes, Windows.Current.Bounds does work the same, but I believe that in Win10 determining the full display area will be useful and not just the application window.
    musical9

  • Java returning incorrect values for width and height of a Tiff image

    I have some TIFF images (sorry, I cannot post them b/c of there confidential nature) that are returning the incorrect values for the width and height. I am using Image.getWidth(null) and have tried the relevant methods from BufferedImage. When I open the same files in external viewers (Irfanview, MS Office Document Imaging) they look fine and report the "correct" dimensions. When I re-save the files, my code works fine. Obviously, there is something wrong with the files, but why would the Java code fail and not the external viewers? Is there some way I can detect file problems?
    Here is the code, the relevant section is in the print() routine.
    * ImagePrinter.java
    * Created on Feb 27, 2008
    * Created by tso1207
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.print.PageFormat;
    import java.awt.print.PrinterException;
    import java.io.File;
    import java.io.IOException;
    import java.util.Iterator;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageReader;
    import javax.imageio.stream.FileImageInputStream;
    import javax.imageio.stream.ImageInputStream;
    import com.shelter.io.FileTypeIdentifier;
    public class ImagePrinter extends FilePrintable
       private final ImageReader _reader;
       private final int _pageCount;
       private final boolean _isTiff;
       //for speed we will hold current page info in memory
       private Image _image = null;
       private int _imgWidth = 0;
       private int _imgHeight = 0;
       private int _currentPage = -1;
       public ImagePrinter(File imageFile) throws IOException
          super(imageFile);
          ImageInputStream fis = new FileImageInputStream(getFile());
          Iterator readerIter = ImageIO.getImageReaders(fis);
          ImageReader reader = null;
          while (readerIter.hasNext())
             reader = (ImageReader) readerIter.next();
          reader.setInput(fis);
          _reader = reader;
          int pageCount = 1;
          String mimeType = FileTypeIdentifier.getMimeType(imageFile, true);
          if (mimeType.equalsIgnoreCase("image/tiff"))
             _isTiff = true;
             pageCount = reader.getNumImages(true);
          else
             _isTiff = false;
          _pageCount = pageCount;
       public int print(java.awt.Graphics g, java.awt.print.PageFormat pf, int pageIndex)
          throws java.awt.print.PrinterException
          int drawX = 0, drawY = 0;
          double scaleRatio = 1;
          if (getCurrentPage() != (pageIndex - getPageOffset()))
             try
                setCurrentPage(pageIndex - getPageOffset());
                setImage(_reader.read(getCurrentPage()));
                setImgWidth(getImage().getWidth(null));
                setImgHeight(getImage().getHeight(null));
             catch (IndexOutOfBoundsException e)
                return NO_SUCH_PAGE;
             catch (IOException e)
                throw new PrinterException(e.getLocalizedMessage());
             if (!_isTiff && getImgWidth() > getImgHeight())
                pf.setOrientation(PageFormat.LANDSCAPE);
             else
                pf.setOrientation(PageFormat.PORTRAIT);
          Graphics2D g2 = (Graphics2D) g;
          g2.translate(pf.getImageableX(), pf.getImageableY());
          g2.setClip(0, 0, (int) pf.getImageableWidth(), (int) pf.getImageableHeight());
          scaleRatio =
             (double) ((getImgWidth() > getImgHeight())
                ? (pf.getImageableWidth() / getImgWidth())
                : (pf.getImageableHeight() / getImgHeight()));
          //check the scale ratio to make sure that we will not write something off the page
          if ((getImgWidth() * scaleRatio) > pf.getImageableWidth())
             scaleRatio = (pf.getImageableWidth() / getImgWidth());
          else if ((getImgHeight() * scaleRatio) > pf.getImageableHeight())
             scaleRatio = (pf.getImageableHeight() / getImgHeight());
          int drawWidth = getImgWidth();
          int drawHeight = getImgHeight();
          //center image
          if (scaleRatio < 1)
             drawX = (int) ((pf.getImageableWidth() - (getImgWidth() * scaleRatio)) / 2);
             drawY = (int) ((pf.getImageableHeight() - (getImgHeight() * scaleRatio)) / 2);
             drawWidth = (int) (getImgWidth() * scaleRatio);
             drawHeight = (int) (getImgHeight() * scaleRatio);
          else
             drawX = (int) (pf.getImageableWidth() - getImgWidth()) / 2;
             drawY = (int) (pf.getImageableHeight() - getImgHeight()) / 2;
          g2.drawImage(getImage(), drawX, drawY, drawWidth, drawHeight, null);
          g2.dispose();
          return PAGE_EXISTS;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since version XXX
        * @return
       public int getPageCount()
          return _pageCount;
       public void destroy()
          setImage(null);
          try
             _reader.reset();
             _reader.dispose();
          catch (Exception e)
          System.gc();
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @return
       public Image getImage()
          return _image;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @return
       public int getImgHeight()
          return _imgHeight;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @return
       public int getImgWidth()
          return _imgWidth;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @param image
       public void setImage(Image image)
          _image = image;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @param i
       public void setImgHeight(int i)
          _imgHeight = i;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @param i
       public void setImgWidth(int i)
          _imgWidth = i;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @return
       public int getCurrentPage()
          return _currentPage;
        * <br><br>
        * Created By: TSO1207 - John Loyd
        * @since Mar 25, 2008
        * @param i
       public void setCurrentPage(int i)
          _currentPage = i;
    }Edited by: jloyd01 on Jul 3, 2008 8:26 AM

    Figured it out. The files have a different vertical and horizontal resolutions. In this case the horizontal resolution is 200 DPI and the vertical is 100 DPI. The imgage width and height values are based on those resolution values. I wrote a section of code to take care of the problem (at least for TIFF 6.0)
       private void setPageSize(int pageNum) throws IOException
          IIOMetadata imageMetadata = _reader.getImageMetadata(pageNum);
          //Get the IFD (Image File Directory) which is the root of all the tags
          //for this image. From here we can get all the tags in the image.
          TIFFDirectory ifd = TIFFDirectory.createFromMetadata(imageMetadata);
          double xPixles = ifd.getTIFFField(256).getAsDouble(0);
          double yPixles = ifd.getTIFFField(257).getAsDouble(0);
          double xRes = ifd.getTIFFField(282).getAsDouble(0);
          double yres = ifd.getTIFFField(283).getAsDouble(0);
          int resUnits = ifd.getTIFFField(296).getAsInt(0);
          double imageWidth = xPixles / xRes;
          double imageHeight = yPixles / yres;
          //if units are in CM convert ot inches
          if (resUnits == 3)
             imageWidth = imageWidth * 0.3937;
             imageHeight = imageHeight * 0.3937;
          //convert to pixles in 72 DPI
          imageWidth = imageWidth * 72;
          imageHeight = imageHeight * 72;
          setImgWidth((int) Math.round(imageWidth));
          setImgHeight((int) Math.round(imageHeight));
          setImgAspectRatio(imageWidth / imageHeight);
       }

  • How do I restore all images in a collection to original imported aspect ratio?

    Typically I select all images in a catalog, resize the first image to 640x480.  I then right click on the first image (all images are still selected) click on Develop Settings, Sync and choose to sync only the aspect ratio.  All images are then cropped to 640x480 like the first image, which I then export to a folder.
    I then need to restore all images to the original aspect ratio for building a slideshow to export to my website.  I've followed the same procedure i.e. selected all images, click on the first image, change aspect to original, right click on first image and sync aspect ratio for all images.
    The problem is that the rest of the images do not return to their original aspect ratio but revert to 4x6 aspect ratio instead of the original size when imported.  I've changed the lock to unlocked and tried both but still no result.  Now I have to select each image individually, open the crop dialog and choose custom to get it back to the imported aspect ratio.
    How do I batch restore all images in a collection to the aspect ratio when imported?

    Rotating an image is adjusting its crop rotation and crop size.  You originally said you wanted things back to import state which presumably was full resolution w/o any adjustments to ratio, size, or rotation.  If you are wanting to do things in the middle of your other processing I'm less sure what to tell you.
    Taking a crop that you have at 3:2 and setting it to 4:3 shrinks in the longer sides, and resetting the ratio to 3:2 shrinks down the shorter top and bottom--this is how it always works, because a crop box is not ever expanded by setting the ratio to something different, and changing the ratio back and forth like that makes the crop-box smaller and smaller. 
    Are you having an issue because you want to fiddle with the crop in the middle of other processing every time, or is this a special case because you've moved on in your processing after asking your question some time ago? 
    If you routinely need to do this, an easier way might be to export the images at the 3:2 crop, then reimport those JPGs, change the crop on those JPGs, only, then re-export them a second time, and be done with them.  This sounds like you're making proofs?
    If you are making proof-sized images at a different ratio?  Why not just export the 3:2 images at a smallish size, perhaps with a watermark and not have to worry about making them 4:3 ratio?
    Another alternative would be to print the images to JPGs instead of a printer, and set the paper size to a 4:3 ratio and turn on the Fill option--which will chop of the long sides automatically as it prints them.

Maybe you are looking for

  • Preview shows blank pages

    I've just received a 13 page pdf file. Opening it with Preview showed me 13 blank pages. Opening it with Acrobat showed me the pages as they are supposed to look. What's going on? Why can't Preview show the contents? (The file was created on a PC, if

  • FCP XML to Premiere Different Frame Rate

    Hello, I have imported an FCP 7 XML into Premiere 5.04. When my sequence was in FCP it was at a frame rate of 23.976 at 720P. When it came into Premiere, though, it had changed to 59.94 fps at 720P. I wonder how this has happened and if there is any

  • Passing the values from subreport to master report in JasperReports

    Hi All, I want to pass the values from subreport to master report, but my subreport is without any query. Please help me in this regard. its urgent. Thanks & Regards Kris

  • Comm channel missing in comm channel monitoring

    Hi, I have created sender and receiver communication channels of adapter type XI. I am using PI 7.0 version. But I don't see these communication channels in RWB comm channel monitoring. I was going through the help.sap.com and in http://help.sap.com/

  • Purchase group in MRp elements

    Hi gurus, When MRP is run PR is generating with a doc.type and purchase group Where from the doc type and purch group are picked by the system?