Camera View Overlay in iOS

iOS 4 and higher allow for an overlay view to be added to the view hierarchy in the UIImagePickerController when it is in Camera mode. I wanted to use this technique in Interlacer to allow the user to line up multiple shots. It seemed that this would be very straightforward:

1
2
3
4
5
// assume there is an instance of UIImagePickerController* named picker...
// assume that there is a UIImage* property named overlayImage...
UIImageView *overlay = [[UIImageView alloc] initWithImage:self.overlayImage];
overlay.alpha = 0.5f;
picker.cameraOverlayView = overlay;

That code will show the image as a translucent overlay, but it is not lined up correctly in the viewfinder. The image was off by about 50 pixels. To make this work, I needed to resize the image to the correct viewfinder size, place that image in a UIImageView whose frame was the size of the main screen, then position the content (the resized image) at the top of the frame:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// assume there is an instance of UIImagePickerController* named picker...
// assume that there is a UIImage* property named overlayImage...
UIImageView *overlay = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

// with an image sized to fit in the viewfinder window
// (Resize using Trevor Harmon's UIImage+ categories)
overlay.image =
            [self.overlayImage resizedImageWithContentMode:UIViewContentModeScaleAspectFill
                                                    bounds:CGSizeMake(320, 430)
                                       interpolationQuality:kCGInterpolationDefault];
// tell the view to put the image at the top, and make it translucent
overlay.contentMode = UIViewContentModeTop;            
overlay.alpha = 0.5f;
picker.cameraOverlayView = overlay;

This code is in an xcode project that demonstrates the overlay by allowing you to take a photo, then overlaying it in the camera view. You can find the code on github.

This fix will be in the next release of Interlacer.

Happy coding!

Adding EXIF Metadata To Images On The iPhone

EXIF metadata is embedded in most of the images created by digital cameras, and the iPhone is no exception. This can include information about the camera that made the photo, the software used to process it, the data and time, geolocation information, and many other pieces of interesting information.

When I was developing Interlacer, one of my goals was to include information about how the photo was created. Since Interlacer creates a new photo from multiple sources, the EXIF metadata block in the final image is missing. I didn’t want to just copy metadata from the source images, since there is no guarantee that the metadata in the source images would be relevant to the final image. I decided that I wanted to save the name and version of the app, some information about the source images that were used to create the final image, and the date and time the final image was created.

There are a lot of examples of how to manipulate the existing EXIF data in an image on the iPhone, but I didn’t find much information about how to add EXIF data to an image that did not contain any. The solution turned out to be quite straightforward. When an image is saved using the ALAssetsLibrary class, a dictionary of metadata can be included. This dictionary includes some basic metadata and can also include dictionaries of other metadata, such as EXIF and TIFF metadata. The keys for all these metadata values are constants declared in ImageIO/CGImageProperties.h.

Depending on the information you want to save, you may need several dictionaries, each containing a specific type of metadata. In Interlacer, the date and time and image dimensions are saved as EXIF metadata, and information about Interlacer and the source images is saved as TIFF metadata.

Here is the code showing how to create EXIF and TIFF dictionaries and save the information along with an image:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
- (void)saveImageAndAddMetadata:(UIImage *)image
{
    // Format the current date and time
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy:MM:dd HH:mm:ss"];
    NSString *now = [formatter stringFromDate:[NSDate date]];
    [formatter release];
   
    // Exif metadata dictionary
    // Includes date and time as well as image dimensions
    NSMutableDictionary *exifDictionary = [NSMutableDictionary dictionary];
    [exifDictionary setValue:now forKey:(NSString *)kCGImagePropertyExifDateTimeOriginal];
    [exifDictionary setValue:now forKey:(NSString *)kCGImagePropertyExifDateTimeDigitized];
    [exifDictionary setValue:[NSNumber numberWithFloat:image.size.width] forKey:(NSString *)kCGImagePropertyExifPixelXDimension];
    [exifDictionary setValue:[NSNumber numberWithFloat:image.size.height] forKey:(NSString *)kCGImagePropertyExifPixelYDimension];
   
    // Tiff metadata dictionary
    // Includes information about the application used to create the image
    // "Make" is the name of the app, "Model" is the version of the app
    NSMutableDictionary *tiffDictionary = [NSMutableDictionary dictionary];
    [tiffDictionary setValue:now forKey:(NSString *)kCGImagePropertyTIFFDateTime];
    [tiffDictionary setValue:@"Interlacer" forKey:(NSString *)kCGImagePropertyTIFFMake];
   
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    [tiffDictionary setValue:[NSString stringWithFormat:@"%@ (%@)", version, build] forKey:(NSString *)kCGImagePropertyTIFFModel];
   
    // Image metadata dictionary
    // Includes image dimensions, as well as the EXIF and TIFF metadata
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:[NSNumber numberWithFloat:image.size.width] forKey:(NSString *)kCGImagePropertyPixelWidth];
    [dict setValue:[NSNumber numberWithFloat:image.size.height] forKey:(NSString *)kCGImagePropertyPixelHeight];
    [dict setValue:exifDictionary forKey:(NSString *)kCGImagePropertyExifDictionary];
    [dict setValue:tiffDictionary forKey:(NSString *)kCGImagePropertyTIFFDictionary];
   
    ALAssetsLibrary *al = [[ALAssetsLibrary alloc] init];
   
    [al writeImageToSavedPhotosAlbum:[image CGImage]
                            metadata:dict
                     completionBlock:^(NSURL *assetURL, NSError *error) {
                         if (error == nil) {
                             // notify user image was saved
                         } else {
                             // handle error
                         }
                     }];
   
    [al release];
}

Knicker, a Wordnik API Library for Java

Wordnik is an online dictionary that bills itself as “The most comprehensive dictionary in the known universe”. Recently I wanted to add the ability to lookup word definitions to one of my applications, so I wrote a Java library to wrap the Wordnik API. The library is called Knicker, and is available under the terms of the GPL.

Using Knicker is simple:

  1. Sign up for a Wordnik API key
  2. Set the system property WORDNIK_API_KEY to your API key
  3. Put the Knicker library in your classpath
  4. Call methods on the library

Here’s an example of how to use the API to get a list of definitions for the word “siren”:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.List;
import net.jeremybrooks.knicker.Knicker;
import net.jeremybrooks.knicker.dto.Definition;
import net.jeremybrooks.knicker.dto.TokenStatus;

public class TestKnicker {


    public static void main(String[] args) throws Exception {
        // use your API key here
        System.setProperty("WORDNIK_API_KEY", "");

   
    // check the status of the API key
    TokenStatus status = Knicker.status();
    if (status.isValid()) {
        System.out.println("API key is valid.");
    } else {
        System.out.println("API key is invalid!");
        System.exit(1);
    }

   
    // get a list of definitions for a word
    List<Definition> def = Knicker.definitions("siren");
    System.out.println("Found " + def.size() + " definitions.");

    int i = 1;
    for (Definition d : def) {
        System.out.println((i++) + ") " + d.getPartOfSpeech() + ": " + d.getText());
    }

    }
}

For more information about the Wordnik API, see their developers page.

Introducing Jinx

Jinx is a Java library that provides access to the Flickr API. It is pure Java, with no external dependencies.

The package structure is straightforward. Each Flickr API section (activity, auth, blogs, etc) has a corresponding class in the net.jeremybrooks.jinx.api package. The API classes are named ActivityApi, AuthApi, BlogsApi, etc. Each API class is implemented as a singleton. You can obtain an instance of an API class with a call to getInstance():

1
BlogsApi bApi = BlogsApi.getInstance();

Each Flickr method has a corresponding method in the API class. So if you want to call the Flickr flickr.blogs.getList method, you will call the getList() method on BlogsApi:

1
BlogsApi.getInstance().getList();

The API methods that return data will generally return instances of the Data Transfer Objects located in the net.jeremybrooks.jinx.dto package. The DTO’s are very simple classes, containing getter and setter methods and no other logic. All DTO’s implement java.io.Serializable.

Flickr returns a status message along with data for every API call. Jinx will check that status message for you. If Flickr reports an error, an instance of net.jeremybrooks.jinx.JinxException will be thrown. The Flickr error code and error message can be retrieved by calling getErrorCode and getErrorMessage.

This project is currently being used in SuprSetr. Currently, the following Flickr API sections are implemented:

  • Activity
  • Auth
  • Blogs
  • Collections
  • Commons
  • Photos
  • Photosets

Other sections of the Flickr API will be implemented over time. If you want to use Jinx now, you can get the source code from github and build it with ant. If you just want the binary jar file, you can download it at the Jinx home page. Javadocs are located here.

The test directory contains sample code showing how to use Jinx to access the Flickr API. Here is the TestAuthorization class, showing how to authorize an application to use Flickr:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.io.File;
import net.jeremybrooks.jinx.Jinx;
import net.jeremybrooks.jinx.JinxConstants;
import net.jeremybrooks.jinx.api.AuthApi;
import net.jeremybrooks.jinx.dto.Frob;
import net.jeremybrooks.jinx.dto.Token;

/**
 * This test class demonstrates how to perform authorization for your application.
 *
 * Your application must have its own key and secret. These can be obtained here:
 * http://www.flickr.com/services/apps/create/apply/?
 *
 *
 * @author jeremyb
 */

public class TestAuthorizaion {

    /*
     * Get a key for your app here:
     * http://www.flickr.com/services/apps/create/apply/?
     */

    private static final String KEY = "";
    private static final String SECRET = "";

    public static void main(String[] args) {

    File tokenFile = new File("/tmp/myToken");
    Token token = null;

    try {
        // Attempt to initialize with an existing token
        if (tokenFile.exists()) {
        token = new Token();
        token.load(tokenFile);
        Jinx.getInstance().init(KEY, SECRET, token);

        } else {

        // No token exists, so initialize with our key and secret,
        // then prompt user to authorize our application
        Jinx.getInstance().init(KEY, SECRET);
        Frob frob = AuthApi.getInstance().getFrob(JinxConstants.PERMS_READ);

        // Send user to the login URL
        // In a real application, you would probably do this in a GUI
        // of some sort
        System.out.println("Please go to this URL and allow access: " + frob.getLoginUrl());
        System.out.println("After you have authorized this application, press a key.");

        // Wait for user to press a key
        System.in.read();

        // Complete authorization by getting the token and telling
        // Jinx about it
        token = AuthApi.getInstance().getToken(frob);
        Jinx.getInstance().setToken(token);

        System.out.println("Authorization successful.");

        // The token can be stored for future use, and is valid until
        // the user revokes access
        token.store(new File("/tmp/myToken"));
        }
    } catch (Exception e) {
        System.out.println("Oops, something went wrong!");
        e.printStackTrace();
    }
    }
}

Jinx is released under the Gnu General Public License.

Java Network Proxies

Have you ever spent hours lovingly coding your Next Great Program, only to discover that part of your audience cannot use it because they are behind a proxy server? If you are going to be using the network, it pays to plan ahead for this situation. Adding proxy capability to your program is not very difficult. Here’s a quick code snippet that does just that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static void enableProxy(String host, int port, final String username, final char[] password) {
    System.setProperty("http.proxyHost", host);
    System.setProperty("http.proxyPort", String.valueOf(port));

    if (username != null && !username.isEmpty()) {
        Authenticator.setDefault(new Authenticator() {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }

        });
    }
}

Calling this method with a host and port will set up the system properties necessary for proxy access to work. If the username is not null, it will also set up a PasswordAuthentication object to perform authentication as needed. To disable the proxy, call this method:

1
2
3
4
public static void clearProxy() {
    System.clearProperty("http.proxyHost");
    System.clearProperty("http.proxyPort");
}

Now, all you have to do is provide a way for the user to enter the proxy settings, persist the settings, and call the enableProxy method. At application startup, you can read the settings from where you have stored them and enable the proxy.

Another option is to tell the JVM to use your system proxy settings. However, I have had problems with this detecting the system properties in some cases on some operating systems:

1
System.setProperty("java.net.useSystemProxies", "true");

Adding proxy support to your code is easy! Taking the time to add proxy support to your application will save you headaches later on down the road. Happy coding!

Blocking User Input In A Swing GUI

When developing a desktop application, there are times when you want to prevent the user from interacting with the GUI. For example, you may be doing work in the background, and want to make sure you finish before allowing the user to continue. Perhaps the most obvious way to do this is to disable each component in the GUI. This works, but is not a very elegant or maintainable solution. The appearance of each GUI component changes when disabled, and if you add a new component to the window in the future, you will have to remember to disable it as well.

Fortunantly, Swing provides a better way to do this: The glass pane. The glass pane is one of the layers of a JRootPane. It is transparent and normally not visible. However, if you set it as visible, you can effectively block all user interaction with the contents of the window.

Carrying this one step further, it is possible to set the glass pane to be a panel of your own design. By doing this, you can effectively overlay anything you want on top of the current window, including messages to the user, animated progress icons, etc. The screen shot below shows the BlockerPanel in action. The icon and text are on the glass pane, which intercepts all user interaction with the window.

BlockerPanel Demo

The code to implement a BlockerPanel is straightforward, and the resulting class is easy to use. You can download my BlockerPanel class along with a simple demonstration program and use it in any of your projects. The source code is released with no restrictions, so feel free to improve upon it. There are many useful features that could be added, and there are parts of the code that could be improved. I’ll leave this as an exercise for the reader.

BlockerDemo source code and test program.

Further reading:

How to use Root Panes on sun.com