Add geo tags to TIFF image

Hello ..
I struck with adding geotags such as GTModelType_TAG,GTRasterType_TAG,Projection_TAG etc.to TIFF image.Can i add tags to IIOMetadata or TIFFDirectory or anyother.Please suggest me ,if possible give code snippet also.
Is adding geotags is same as adding our own tag to TIFF image.
Thanks in advance.

Try this. This code assumes you hava JAI-ImageIO, and consequently have the ImageReader/Writer plugin for tiff files.
public static IIOMetadata addGeoMeta(
        IIOMetadata existingMeta,
        int[] geoKeyDirectory,
        double[] geoDoubleParams,
        String geoAsciiParams) {
    if(geoKeyDirectory.length%4 != 0) {
        throw new IllegalArgumentException("Keys come in blocks of 4.  The "
                + "geoKeyDirectory needs to have a multiple length of 4.");
    //some declarations from the various specificiations
    final String METADATA_FORMAT =
            "com_sun_media_imageio_plugins_tiff_image_1.0";
    final String GEO_TAGSET =
            "com.sun.media.imageio.plugins.tiff.GeoTIFFTagSet";
    final String GEO_KEY_TAG_NUMBER = "34735";
    final String GEO_KEY_TAG_NAME = "GeoKeyDirectory";
    final String GEO_DOUBLES_TAG_NUMBER = "34736";
    final String GEO_DOUBLES_TAG_NAME = "GeoDoubleParams";
    final String GEO_ASCII_TAG_NUMBER = "34737";
    final String GEO_ASCII_TAG_NAME = "GeoAsciiParams";
    IIOMetadataNode root = 
            (IIOMetadataNode) existingMeta.getAsTree(METADATA_FORMAT);
    IIOMetadataNode ifd =
        (IIOMetadataNode) root.getElementsByTagName("TIFFIFD").item(0);
    //remove old geo data if present
    NodeList children = ifd.getElementsByTagName("TIFFField");
    for(int i = 0; i < children.getLength(); i++) {
        IIOMetadataNode child = (IIOMetadataNode) children.item(i);
        String tagNumber = child.getAttribute("number");
        if(GEO_KEY_TAG_NUMBER.equals(tagNumber) ||
           GEO_DOUBLES_TAG_NUMBER.equals(tagNumber) ||
           GEO_ASCII_TAG_NUMBER.equals(tagNumber)) {
            ifd.removeChild(child);
    /**Metadata tree structure:
     * com_sun_media_imageio_plugins_tiff_image_1.0";
     *   TIFFIFD (attributes: tagSets)
     *     TIFFField (attribues: name & number)
     *     TIFFField (attribues: name & number)
     *     TIFFField (attribues: name & number) <-- GeoKeyDirectory
     *       TIFFShorts
     *         TIFFShort (attribute: value) --
     *         TIFFShort (attribute: value)   | Keys have 4 entries each
     *         TIFFShort (attribute: value)   |
     *         TIFFSshor (attribute: value) --
     *     TIFFField (attributes: name & number) <-- GeoDoubleParams
     *       TIFFDoubles
     *         TIFFDouble (attribute: value)
     *         TIFFDouble (attribute: value)
     *         TIFFDouble (attribute: value)
     *     TIFFField (attributes: name & number) <--GeoAsciiParams
     *       TIFFAsciis
     *         TIFFAscii (atrribute: value) <-- single string containing
     *                                          all ASCII valued GeoKeys
    //construct GeoKeyDirectory
    IIOMetadataNode keyDirectoryTag = new IIOMetadataNode("TIFFField");
    keyDirectoryTag.setAttribute("number",GEO_KEY_TAG_NUMBER);
    keyDirectoryTag.setAttribute("name",GEO_KEY_TAG_NAME);
    IIOMetadataNode keys = new IIOMetadataNode("TIFFShorts");
    for(int i = 0; i < geoKeyDirectory.length; i++) {
        if(geoKeyDirectory[i] < 0 || geoKeyDirectory[i] > 65535)
            throw new IllegalArgumentException("Invalide key value: " +
                    geoKeyDirectory[i] + " Must be unsigned short.");
        IIOMetadataNode tiffShort = new IIOMetadataNode("TIFFShort");
        tiffShort.setAttribute("value",""+geoKeyDirectory);
keys.appendChild(tiffShort);
keyDirectoryTag.appendChild(keys);
ifd.appendChild(keyDirectoryTag);
//construct GeoDoubleParams of needed
if(geoDoubleParams != null) {
IIOMetadataNode doubleParamsTag = new IIOMetadataNode("TIFFField");
doubleParamsTag.setAttribute("number",GEO_DOUBLES_TAG_NUMBER);
doubleParamsTag.setAttribute("name",GEO_DOUBLES_TAG_NAME);
IIOMetadataNode doubles = new IIOMetadataNode("TIFFDoubles");
for(int i = 0; i < geoDoubleParams.length; i++) {
IIOMetadataNode tiffDouble = new IIOMetadataNode("TIFFDouble");
tiffDouble.setAttribute("value",""+geoDoubleParams[i]);
doubles.appendChild(tiffDouble);
doubleParamsTag.appendChild(doubles);
ifd.appendChild(doubleParamsTag);
//construct GeoAsciiParams if needed
if(geoAsciiParams != null) {
IIOMetadataNode asciiParamsTag = new IIOMetadataNode("TIFFField");
asciiParamsTag.setAttribute("number",GEO_ASCII_TAG_NUMBER);
asciiParamsTag.setAttribute("name",GEO_ASCII_TAG_NAME);
IIOMetadataNode asciis = new IIOMetadataNode("TIFFAsciis");
IIOMetadataNode tiffAscii = new IIOMetadataNode("TIFFAscii");
tiffAscii.setAttribute("value",geoAsciiParams);
asciis.appendChild(tiffAscii);
asciiParamsTag.appendChild(asciis);
ifd.appendChild(asciiParamsTag);
//append geo tag set to IFD if needed
String tagSets = ifd.getAttribute("tagSets");
if(!tagSets.contains(GEO_TAGSET)) {
tagSets += "," + GEO_TAGSET;
ifd.setAttribute("tagSets",tagSets);
try {
existingMeta.setFromTree(METADATA_FORMAT,root);
}catch(Exception e) {
//failed to add new geo data
e.printStackTrace();
return existingMeta;
It may be a little easier using JAI, but I don't know how you would do it off the top of my head. JAI is build more for image processing than metadata manipulation.

Similar Messages

  • Unable to Add Alt Tags to Placed Images

    I am developing a flyer that will be distributed as a PDF, and our requirement is that it be "Section 508" compliant, that is, readable by a screen reader. I am trying to add alt tags to the images in order to meet this requirement, but when I go to Object -> Object Export Options and click on the Alt Text tab, theAlt Text Source pull-down menu is greyed out and does not allow me to do anything.
    Does anyone have any idea of what is wrong here?

    It's working for me in the current version of InDesign CC.
    Version of InDesign? Computer platform? What file format is the image in?
    Have you tried restoring your InDesign preferences? Here's how:
    Troubleshooting 101: Replace, or "trash" your InDesign preferences

  • How can I change the geo tag of an image in iPhoto '11?

    A lot of my old photos either have no geo tag, or have incorrect tags (apparently I took some pictures in the middle of the Yellow Sea).
    So, how do I change or at least erase the geo tag for one or more photos?  I've tried "Rescan Location" and nothing happens.

    And did you look at iPhoto help on adding places?
    Add places to your photos
    If you have photos that don’t have GPS information, including print photos that were scanned to a disk, you can still map your photos in Places.
    https://help.apple.com/iphoto/mac/help/index.html?lang=en#
    Watch the movie (about 2 minutes)
    View and organize photos using Places
    iPhoto matches recognizable location names you enter, such as “Seattle” or “Milan,” to a mapping database. When you add a location to a single photo or an entire Event, those photos are marked on the Places map.
    Or, if you have latitude and longitude information for the place where you shot your photos, you can use that information to add the location.
    Important:  You must be connected to the Internet for the Places feature to show photo locations on the map.
    Hide
    To add a place name:
    Select the photo or Event you want to add location information to.Tip:  If you select an Event, the location is added to every photo in that Event. But you can add locations to selected photos without adding locations to them all. To do so, select the photos you want, move your pointer over them, and then click the Info button. Skip to step 3.
    Click the Info button in the toolbar to open the Information pane.
    Select “Assign a Place” and start typing the location name to see the related names iPhoto suggests.You can type city names, place names (such as “Empire State Building”), and addresses (such as “12345 Main St., Lincoln, NE”).Note:  If no locations appear, check to make sure that iPhoto is set to look up locations.
    As related names appear, do one of the following:
    If you see the location you want appear in the pop-up menu, choose it. iPhoto marks your selected location with a red marker pin on the map in the Information pane.
    If you don’t see the exact location you want in the pop-up menu, choose a location that’s nearby. For example, if you took a photo of a star at Mann’s Chinese Theater in Hollywood, you can type “Hollywood” into the location field and then choose the Hollywood, California, option from the pop-up menu. Then go to step 5.A red marker pin appears in the map in the Information pane.
    To fine-tune the location, you can click the marker pin (it turns yellow) and drag it to a different location, such as a neighboring town, or a more specific location, such as a particular intersection.You can click the plus and minus buttons to zoom in or out, and drag the map to show a different area.To center the map on the pin, click the circle icon.Note:  You can move marker pins only in the small map that appears below Places in the Information pane. You can’t drag marker pins on the full-size Places map.
    When you’re satisfied with the location as it appears in the Information pane, click the arrow next to the location name to view the marker on the full Places map.
    HideTo use latitude and longitude to add a place:
    Select the photo or Event you want to add location information to.Tip:  If you select an Event, the location is added to every photo in that Event. But you can add locations to selected photos without adding locations to them all. To do so, select the photos you want, move your pointer over them, and then click the Info button. Skip to step 3.
    Click the Info button to open the Information pane.
    Select “Assign a Place,” and then type the latitude and longitude, separated by a comma.For example, you can type “24, -110” or, if you prefer, you can use a longer format, such as “24.15988731, -110.50838234.”It’s important to always put the latitude first.
    Look at the map to confirm the location, and then do one of the following:
    If the location is correct, continue to step 5.
    If the location is incorrect, retype the latitude and longitude, or drag the pin to a more exact location on the map.You can use the plus and minus buttons to zoom in and out, and drag the map to center it on a better spot.Note:  You can move marker pins only in the small map that appears below Places in the Information pane. You can’t drag marker pins on the full-size Places map.
    If you want, you can view the location marked on the full Places map by clicking the arrow next to the location name.
    HideTo copy the location of one photo to other photos:You can copy the location of one photo to another photo or photos.
    Select a photo that has the location assigned to it that you want to copy, and then choose Edit > Copy.
    Select one or more photos that you want to assign the same location to, and choose Edit > Paste Location.The location is added to the photos, which you can then view using Places.
    Was this page helpful?Send feedback.
    © 2011 Apple Inc. All rights reserved.
    It is very detailed - which is why I suggested it to you
    LN

  • Can you add Geo Tags to images you shoot in Adobe Bridge?

    I was wondering if this could be done?
    -David

    You might try google this as you will see several hits  such as this http://forums.adobe.com/message/4323488.
    No direct way to do this, depending on what you expect to accomplish.

  • Can't find images in Iweb SEO Tools to add alt-tags!

    Hi everyone. I'm trying to add alt-tags to some images on an iweb site with iweb SEO tools but I can't get it to open the containing folder. I have a gallery set up with 6 categories and, in each of these categories, there are a few images. I navigate to the folder that contains each image (it actually contains 4 - the full sized image and three thumnails for use elsewhere - all of them jpgs) but iweb SEO Tools is just not recognising that the folder contains any images at all! I navigate my way through my file structure and, when I finally get to the containing folder, it hits a dead end and will not find the contents of it. Any ideas!?
    An example of my file structure is as follows:
    RRF
    - Gallery
    - Pages
    - Landscapes_files
    - Media
    - dintonpastures [containing folder for images]
    - dintonpastures.jpg [that SEO refuses to see!]
    Any help would be really appreciated!!

    Photo templates are written in Javascript and cannot be accessed by iWeb SEO. Only images you create on a blank page or without using the photo template (HTML generated). They don't tell you that on Rage's website, in fact I find their advertising misleading in that they claim that you can alt tag "all" images in iWeb. But, it's free software, so you get what you pay for.

  • Customised file explorer window for Geo-tagged images

    Dear All,
    I am really stuck on this issue. Did lots of searching but reached nowhere.
    I want to launch a file explorer window which displays only geo-tagged images(can be .jpg,.tiff,.gif) in the form of thumbnails. On selecting any of the images, the latitude adn longitude information is extracted from the image. I have found a few helpful links on the latter part(extracting the EXIF data location coordinates) but have no idea about the first part(thumbnailing geo-tagged images in explorer window). Can anyone provide useful links, references or code?

    Thanks a lot for that link. I am sorry to be asking this but i have run into problems regarding extracting the latitude longitude information from geotagged images using java. Are the same kind of tags always used in all images for storing latitude/longitude values in the EXIF data? I understand i have to use ImageIO but what tag should i exactly look for while parsing the metadata tree and how? Please provide some related links regarding this.

  • How to add a text Component ( text annotation) to the Tiff Image

    Hi.............
    This is the first time I am using Sun Developers Forum.......................
    My problem is.............I want to add a component ( Text or Label ) to the Tiff Image which is displayed on the JIMICanavs [ from JIMI API ].
    Even , if anybody knows about How to add a component to the JIMICanavs , Please help me..................................

    I'm curious: is JIMI still popular? What advantange does it have over the current Java 2D support in the J2SE, or over JAI?

  • How do I add an alt tag to an image in Photoshop CS5 so that it is web ready?

    How do I add an alt tag to an image in Photoshop CS5 so that it is web ready?  My web developer wants me to send him all of my images with an alt-tag assigned so that he can automate the ADA accessibility of the website. I know when I choose to "Save for Web & Devices," I have the option of how much metadata I want to include to the levels of : None, Copyright, Copyright and Contact Info, All Except Camera Info, All.  I don't want the audience to be able to view all of the metadata because a lot of it is sensitive with administrative notes.  Any ideas?

    To anyone else who may encounter this issue in the future, here is a work around:
    File > File Info:
    Sacrifice a metadata field in the description tab.  I chose document title and description. Click OK.
    File > Save for Web and Devices:
    Choose to save All Metadata. 
    Leave things here on your end, and have the web-developer map the code to display only the appropriate metadata field.

  • Is it possible to add keywords, title tags, and alt tags to lightbox images and/or triggers?

    I am building a mobile site that is pretty heavily dependant on lighbox displays for the scroll capability. The issue I have run into is that I need to be able to add alt and title tags to the images in the lightbox (slideshow) to maintain the seo of my site. I have only designed a few of the pages thus far, and the issue I am running across is that once an image is considered a "trigger" by muse I can no longer add the seo elements in the same way I can when it's an image.
    A few ways around this I found are:
    1) export the site to Dreamweaver and then I can go in to the code and add the seo for the images in the lighbox on the backend.
    2) I can build the site image by image and then over lay each trigger for the lighbox slideshow.
    The issue with #1 is that once I export my site to dreamweaver it is then no longer editable in muse. I see this presenting a huge problem as I move forward with new iterations of my website. Any changes made in dreamweaver are not transferable to muse and thus creating two seperate sites. That means I would need to recreate any and all seo built in every time I update the site. This is not really an option and is not efficien at all. Is there a way to jump back and forth between these two products that I am unaware of? That would be most helpful.
    The issue with #2: I have built each project page on the site as mostly large background images with triggers over laid. I did this to try and lower the overall gerth of the site, but it is seeming I am not going to be able to get around this and maintain the seo i am looking for.
    Has any one run into this problem and solved it?
    Here is the site thus far:
    ghatest.businesscatalyst.com
    Thank you for your feedback!

    Placed images and slideshow images support tooltips (the "title" attribute) and alt text via the "Edit Image Properties..." content menu.
    Strictly speaking, background images (fill images) in HTML do not support these tags. That said, in some contexts it may make sense for Muse to enable setting these attributes on an arbitrary object (which may, or may not, have a fill image).

  • Fixed:  TIFF image display / import problems

    Hello All,
    I posted this in the discussion threads where I had previously discussed it with other members. But, felt that it would be good to share with everyone who is importing their photo's into the new iPhoto 6.
    I, like many others, have been having a terrible time getting my iPhoto collection imported into the new iPhoto 6 program.
    I have tried both the upgrade method (on a backup copy of my original library), and a fresh import of all my files.
    Without fail, all of my TIFF images gave me trouble. Some looked like squiggly lines. Some looked like a diagonally distorted image (like you see on old Televisions trying to tune in difficult stations). And, some just plain refused to work.
    All of my problem images look fine in the thumbnail (the library view). But, you quickly discover the problem when viewing the full-size image in the "edit" mode.
    Some of my TIFF images are 30 megabytes in size, and many of them are smaller files of a more typical size. I found that the smaller files were just as unlikely to work as the larger ones.
    And, while converting to JPEG may be an option, I didn't want to lose the depth and detail that TIFF offers (especially on pictures of documents / writing). The original TIFF images will offer greater detail when blown-up than compressed JPG files.
    All of these images worked fine in iPhoto 5, and display perfectly fine in every other program. But, iPhoto 6 just refused to display them properly.
    Well, I think I found the fix.
    Today I downloaded the new iPhoto 6.01 update. But, that didn't fix the problem either. So much for Apple fixing it.
    Anyway, I have been experimenting, and finally found a difference between images that worked and those that didn't.
    The images that worked, have an ICC profile embedded in them from the device that created the image (in my case my scanner).
    So, I set out to find out if simply removing the ICC profile would fix the problem.
    And, through my experimenting, I found that if I opened the image in another program, and then exported it as either a TIFF (the same format) or a JPEG that the resulting image would open in iPhoto 6 just fine.
    Further examination demonstrated that the ICC information was removed from the exported file.
    As I understand it, ICC is basically an image color correction / calibration tag. It enables different devices to properly display and print the image with the proper colors.
    Basically, each device has a color profile (scanner, monitor, printer, camera, etc.). This is to make sure that when you see something on the screen that it looks the same as when you print it out. Likewise, you want the image on the screen to match what the scanner and digital camera saw.
    So, these are essentially conversion tables to make sure that each device properly displays or prints the image as the original source "saw" it.
    Anyway, not wanting to manually strip this information from each file, I looked on the Internet for an automated solution. And, fortunately I found one.
    http://www.colormanagement.com/technicalresources/files_targets_and_utilities/mac_os_xscripts/
    The file you are looking for is "Mac Os X ColorSync Toolbar Script: Remove ICC profile". Click on the title just mentioned to download the script.
    It is a Macintosh Script that you simply download to your desktop (or anywhere else you would prefer). It is in a Stuffit Archive, so you'll need Stuffit Expander to decompress it (basically the Mac equivalent of a ZIP file).
    Once decompressed, you should see a "script" icon that is labeled "Remove Profile".
    Simply "drag" your original files and drop them onto this icon / script. The script will then remove the embedded ICC information from the image file.
    Once you have removed the ICC information from your image's file, try importing it into iPhoto 6 again. Then, see if it works
    It is important that you perform this on a backup / duplicate copy of your original files. You don't want to damage your only copy if something goes wrong.
    Now, one further note: If you do this, you may see the image looks different. In my case, the image is truer to the way it really looked when I scanned it in. The paper texture looks right now.
    If you want to do this while keeping the image's appearance the same as it looks now, then here's another way:
    Open the file in Apple's "Preview" program. This is usually the default image view.
    Then, do a "Save As" or "Export" to create a new copy of the image. If you perform an Export, be sure to set the image quality high or you may inadvertently reduce your pictures detail (especially if you export to JPEG).
    This essentially does the same thing. But, it will take more work if you have multiple images.
    Using the previously mentioned script, you should be able to drag and drop multiple files in a group.
    Anyway, I hope this helps the rest of you out.
    Let me know if it fixes the problem for you as well.

    Hello All,
    I have an update:
    It is definitely not a user account issue. I just completed a fresh install of OS 10.3.9 on my Mac Mini.
    I performed a fresh install (on a freshly formatted hard drive partition), and made the installation as bare as could be for the sake of preventing potential problems.
    I installed OS 10.3.9, and all the standard items in the usual OS 10.3.9 installation. I specifically left-out all the foreign language stuff, all the online programs (for other ISP providers), and misc. garbage.
    I also left off all the iLife programs (every iLife program) that came with the restore disks. I even left-off the original QuickTime installation. My thought here was that I wanted to make sure that there were no problems introduced by upgrading the original iLife Applications to iLife '06.
    So, this way, all the iLife '06 programs are installed fresh with no upgrading being performed.
    So, I installed this bare OS 10.3.9 installation. Then, installed all the updates that were available. I repaired permissions before and after each update. And, installed all the updates from downloads from Apple's website (Not using Software Update).
    After verifying that Software Update could not find any additional updates available, I then installed iLife '06.
    This required first installing Quicktime 7.0.4 from the iLife '06 DVD.
    After installing QuickTime, I then proceeded to install the iLife '06 package (remember that this is a completely new iLife install - not an upgrade install since I avoided installing the older versions).
    Once iLife '06 was installed, I then installed the recent 6.0.1 updates for all the iLife Apps.
    Then, I launched the iPhoto program for the first time to see if it would properly import my TIFF images.
    Unfortunately, it still displays them as if they are scrambled (like a blocked television / cable channel).
    So, with that done, I can confirm that it is not a corrupt file or another program on my system causing the problem. It is definitely a problem with iPhoto 6 / 6.0.1 and OS 10.3.9.
    Just thought I would post the update here for others to add to their knowledge-base. Maybe if we rule out potential problems we'll be able to find the actual solution.
    Again, this same set of images imports just fine into iPhoto 5 on OS 10.3.9 and 10.4.4. And, it also imports just fine into iPhoto 6.0.1 in OS 10.4.5. So, it is a problem apparently specific to OS versions 10.4.4 and older using iPhoto 6 or 6.0.1.
    As mentioned previously, these TIFF images can be made to import fine if I remove the ICC information from the image. So, that may provide some clue as to where the flaw is in the iPhoto 6 / 6.0.1 program.

  • How can I merge two TIFF images in one...?

    I need some help please, I am looking for a way to "resize" black & white single TIFF images.
    The process I need to do is like cutting a small image and paste it over a new blank letter-size image (at 300 dpi), like a template.
    Or better yet, is there a way to do something like this...?
    Open image...
    image.*width* = 2550;
    image.*height* = 3300;
    image.save();Some APIs and topics in the internet do or talk about resizing, but the final images get stretched or shrinked and I need them not to do so at all.
    Also, I do not need to display the images, only to get the TIFF images processed and saved back to a file.
    How can I do this with Java and JAI? Unfortunately I am almost new to this and I don't know how difficult it might be to deal with images.

    If 2550 x 3300 isn't the original aspect ratio of the image, then the image is going to looked streched or shrinked in at least one dimension. There is no way around that. It would be like resizing a 2 pixel by 2 pixel image into a 3 pixel by 6 pixel image. The image would look like it's height shrunk or it's width stretched. Had I resized it to 3 pixels by 3 pixels or 6 pixels by 6 pixels, though, then it wouldn't look shrunken or streched.
    Open image...
    image.*width* = 2550;
    image.*height* = 3300;
    image.save();*1)* To open a TIFF image you can use the javax.swing.ImageIO class. It has these static methods
    read(File input)
    read(ImageInputStream stream)
    read(InputStream input)
    read(URL input) You can use which ever method you want. But first you need to install [JAI-ImageIO|https://jai-imageio.dev.java.net/binary-builds.html]. The default ImageReaders that plug themselves into the ImageIO package are BMP, PNG, GIF, and JPEG. JAI-ImageIO will add TIFF, and a few other formats.
    The downside is that if clients want to you use your program on their machine then they to will need to install JAI-ImageIO to read the tiffs. To get around this, you can go to your Java/jdk1.x.x_xx/jre/lib/ext/ folder and copy the jai_imageio.jar file (after you've installed JAI-ImageIO). You can also obtain this jar from any one of the zip files of the [daily builds|https://jai-imageio.dev.java.net/binary-builds.html#Daily_builds]. If you add this jar to your program's classpath and package it together with your program, then clients won't need to install JAI-ImageIO and you'll still be able to read TIFF's. The downside of simply adding the jar to the classpath is that you won't be able to take advantage of a natively accelerated JPEG reader that comes with installing JAI-ImageIO (instead, ImageIO will use the default one).
    *2)* Once you've installed [JAI-ImageIO|https://jai-imageio.dev.java.net/binary-builds.html] and used ImageIO.read(...), you'll have a BufferedImage. To resize it you can do the following
    BufferedImage newImage = new BufferedImage(2550,3300,BufferedImage.TYPE_BYTE_BINARY);
    Graphics2D g = newImage.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.drawImage(oldImage,0,0,2550,3300,null);
    g.dispose();Here, I simply drew the old image (the one returned by ImageIO.read(...)) onto a new BufferedImage object of the appropriate size. Because you said they were black and white TIFF's, I used BufferedImage.TYPE_BYTE_BINARY, which is a black and white image. If you decide to use one the BufferedImage types that support color, then a 2550x3330 image would require at least 25 megabytes to hold into memory. On the other hand, a binary image of that size will only take up about one meg.
    I specified on the graphics object that I wanted Bilinear Interpolation when scaling. The default is Nearest Neighbor interpolation, which while fast, dosen't look very good. Bilinear offers pretty good results scaling both up or down at fast speeds. Bicubic interpolation is the next step up. If you find the resized image to be subpar, then come back and post. There are a couple of other ways to resize an image.
    Note, however, if 2550 x 3300 is not the same aspect ratio as the the TIFF image you loaded, then the resized image will look shrunk or stretched along one dimension. There is absolutely no way around this no matter what resizing technique you use. You'll need an image whose original dimensions are in a 2550/3300 = .772 ratio if you want the resized image to not look like it's streched (you can crop the opened image if you want).
    *3)* Now we save the "newImage" with the same class we read images with: ImageIO . It has these static methods
    write(RenderedImage im, String formatName, File output)
    write(RenderedImage im, String formatName, ImageOutputStream output)
    write(RenderedImage im, String formatName, OutputStream output)You'll suply the resized BufferedImage as the first parameter, "tiff" as the second parameter and an appropriate output for the third parameter. It's pretty much a one line statement to read or write an image. All in all, the whole thing is about 7 lines of code. Not bad of all.
    Now as for the 300 dpi thing, there is a way to set the dpi in the Image's metadata. I'm pretty good at reading an image's metadata, but I've never really tried writing out my own metadata. I know you can set the dpi, and I have a somewhat vague idea how it might be done, but it's not something I've tried before. I think I'll look more into it.

  • 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 to retain the same resolution while croping a tiff image using jai api

    Hi all,
    I have designed a program to crop a tiff image.But after croping the tiff,the resultant file resolution is not the same as the original source file.
    In the program,the source file Nadeshiko_v1_02.tif has the resolution(X) of 1200 DPI and resolution(Y) has 1200 DPI pixels.
    But after croping the resolution of output file is 100 DPI.
    Please give me some idea on how to retain the same resolution.
    <code>
    package jai;
    import java.awt.Frame;
    import java.awt.image.RenderedImage;
    import java.awt.image.renderable.ParameterBlock;
    import java.awt.image.renderable.RenderableImage;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import javax.imageio.*;
    import javax.imageio.stream.ImageOutputStream;
    import javax.media.jai.Interpolation;
    import javax.media.*;
    import javax.media.jai.JAI;
    import javax.media.jai.PlanarImage;
    import javax.media.jai.RenderedOp;
    import javax.media.jai.widget.ScrollingImagePanel;
    import com.sun.media.jai.codec.FileSeekableStream;
    import com.sun.media.jai.codec.SeekableStream;
    import com.sun.media.jai.codec.TIFFEncodeParam;
    import javax.media.jai.OperationDescriptorImpl;
    import java.io.*;
    import java.util.Iterator;
    import javax.media.jai.operator.*;
    // import javax.media.jai.widget.ScrollingImagePanel;
    public class crop {
              /** The main method. */
    public static void main(String[] args) {
    /* Validate input. */
    /* if (args.length != 1) {
    System.out.println("Usage: java JAISampleProgram " +
    "input_image_filename");
    // System.exit(-1);
    float a=(float) 70.3;
    float b=(float) 70.4;
    float c=(float) 3100.3;
    float d=(float) 5522.4;
    * Create an input stream from the specified file name
    * to be used with the file decoding operator.
    String TIFF="TIFF";
    FileSeekableStream stream = null;
    try {
         stream = new FileSeekableStream("D:\\tif images\\Nadeshiko_v1_02.tif");
    // stream = new FileSeekableStream("D:\\tif images\\Nadeshiko_v1_01.jpg");
    } catch (IOException e) {
    e.printStackTrace();
    System.exit(0);
    // Load the source image from a Stream.
    RenderedImage im = JAI.create("stream", stream);
    RenderedImage image2= CropDescriptor.create(im, a, b, c, d, null);
    ScrollingImagePanel panel = new ScrollingImagePanel(image2, 100, 100);
    // Create a frame to contain the panel.
    Frame window = new Frame("JAI Image Cropping");
    window.add(panel);
    window.pack();
    // window.show();
    // Define the source and destination file names.
    // String inputFile = "D:\\tif images\\Nadeshiko_v1_05.tif";
    String outputFile = "D:\\tif images\\Nadeshiko_v1_04.tif";
    // Save the image on a file. We cannot just store it, we must set the image encoding parameters
    // to ensure that it will be stored as a tiled image.
    TIFFEncodeParam tep = new TIFFEncodeParam();
    tep.setWriteTiled(true);
    tep.setTileSize(80,80);
    JAI.create("filestore",image2,outputFile,"TIFF",null);
    try {
                   stream.close();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    </code>
    Thanks,
    Sanat Meher

    Try the following,
    TIFFEncodeParam tep = new TIFFEncodeParam();
    // Create {X,Y}Resolution fields.
    TIFFField fieldXRes = new TIFFField(0x11A, TIFFField.TIFF_RATIONAL,
                                        1, new long[][] {{DPI_X, 1}});
    TIFFField fieldYRes = new TIFFField(0x11B, TIFFField.TIFF_RATIONAL,
                                        1, new long[][] {{DPI_Y, 1}});
    tep.setExtraFields(new TIFFField[] {fieldXRes, fieldYRes});

  • Displaying TIFF images in Oracle Forms 6i

    Hello, friends!
    I am working in Oracle Forms 6.0.8 (that ancient tool) and encounter a problem with displaying TIFF images.
    I have a number of scanned images and some of them are displayed and some are not. I've tried both extracting them from the database or from the file system (using READ_IMAGE_FILE). Sometimes I am getting just blank field in my image item and sometimes (after using READ_IMAGE_FILE) I get the error FRM-47100 (cannot read image file). Of course I've checked that all the files are displayed using standard tools for displaying TIFFs.
    Basically the question is what kind of TIFF is considered valid and readable by Oracle Forms.
    Analyzing TIFF tags actually gave me nothing: I have a pair of files with tags different only in image width/length and a number of rows/strip (but even those values are close), and one of the file is displayed correctly while the other is not. The thing I noticed is that invalid files are using compression type of CCITT Group 4.
    Possibly Oracle Forms follows TIFF specification only to certain extent and does not support all the extensions, while sometimes the problems are not visible to user.
    As a result of my work I need some automatic tool that converts undisplayable TIFF files to displayable ones but firstly I am to determine where the problem is. And it would be very good to have a prooflink that approves my decision.
    Looking forward to any help! Thanks in advance.

    Thanks to everybody, but I'm afraid my files don't contain any EXIF tags (although TIFF seems to support them). The file doesn't contain any tags with IDs greater than 0x7FFF but only core TIFF tags (with IDs of lower numbers). Moreover I have a file with exactly the same set of tags (but the values are a bit different) which is displayed properly.
    I've shared the issued file (nondisplayable) on the following link: [https://rapidshare.com/files/3137807470/2.tif]
    If anyone could tell me why isn't it displayed in Forms I would be very grateful.

  • How do you add a link to an image item

    I have added an Image Item to a page and want to be able to add a link to that image but dont see any where you can put the link in the Image Item properties

    One easy way to do this would be to add an image page, upload your image to the page, then create an html portlet with the appropriate tags to refer to the image and your link.

Maybe you are looking for

  • Missing Features in the new design preview

    So today Microsoft officially unveiled the new design preview for Skype for Windows desktop that we have been able to test on a field trial basis or by manipulating the URL to download. Apart from the new design, this new version also brings a change

  • Multiple HTML objects not aligning

    In the footer of my muse site, I have two HTML objects that should appear side-by-side. One is a live feed from a ratings website, the other is a Facebook like box. Both are pulling approved code, both appear great in Muse, Muse has previously publis

  • Why don't i have enough memory to upgrade to lion?

    I have a 2 year old intel imac that i'm trying to upgrade to lion. I can't installsays I need 2GB of memory, I have 1. Seriously...this is arelatively new computer..I have to buy more memory?

  • Problems opening outline: Not enough memory available

    Dear all, since about 3 or 4 weeks I have problems with opening an outline in EAS console: After a double klick on the outline and about 1 minute waiting the following message pops up: "There is not enough memory available on the Administration Serve

  • File Encryption: New to Java encryption plz help

    ive been looking at some code i got from a friends java book about how to encode/decode stuff. It seems to me that the key that is generated would be a one time thing and you would get a new one the next time you tried. If that happened i would think