Abstract: We learn how we can download images from within Java and then display them in a JFrame.
Welcome to the 72nd edition of The Java(tm) Specialists' Newsletter. This time we welcome a subscriber from Uganda, bringing our total countries to 97. Three more to go and we will have reached 100 countries. Perhaps we will even reach 100 countries by the end of this year :-)
javaspecialists.teachable.com: Please visit our new self-study course catalog to see how you can upskill your Java knowledge.
Programmers are obliged to read Dilbert. One says that a picture is worth a thousand words, and Scott Adams certainly captures our day-to-day frustrations in his comic. I once verbalised my enthusiasm for Dilbert to a boss, who then suggested that I was like one of the characters, but not necessarily Dilbert. By process of elimination, I have concluded that he was probably thinking of Wally, my hero :-)
Many years ago, I read a book called "Cheaper by the Dozen" by Frank Gilbreth, about a time-and-motion expert and his wife with their twelve kids. The father was an early version of a process reengineering expert. In his study of companies, he would pick the laziest person to study, because they would have already optimised the process to suit their own laziness. For example, he should look at the person who will rather write a batch file once than to repeat the same command over and over again. Windows NT (and beyond) has an autocomplete option in the command prompt, so the person that has that enabled in the registry would be a good candidate.
Wally would be the person I would make in charge of automating the build process of the code, and running the unit tests. You can bet that there would be no manual intervention necessary at all.
So, what does all this have to do with Java? Java
interfaces nicely with the internet, so any tasks that
you would have to do repetitively over and over again
can be automated quite easily. You can interface
with any URL by simply passing it in as a String to the
java.net.URL
class and then calling
openStream()
. With a simple
while
loop, you can read the
bytes from the URL and write them to a local file.
You can convert this URL
to an image with
the javax.swing.ImageIcon
.
If the URL is pointing to an HTML file, you can
search for certain strings, such as
mailto:
. [That last suggestion is
used by spammers. Amazing how many African statespeople
have vast amounts of money lying around at the moment
that they want to dispose of. I get at least one of
those spams a week. Talking of Spamming, I get
challenge-response emails from some subscribers which
they use to filter spams. Please add my email address
to your acceptable filter if you want to receive my
newsletter.]
Let us get back to Dilbert. Imagine Wally wanted to read Dilbert every day. Do you really think that Wally would connect every day to the internet and go to https://dilbert.com? That would be far too much effort! Instead, he would write a small Java program that went to the main Dilbert page, parsed the HTML page to find out what today's GIF URL is, and show it in an ImageIcon. An added benefit is that Wally is then not exposed to the advertising anymore. Here's the code:
import java.io.*; import java.net.URL; import javax.swing.*; public class DilbertComic { public static String todaysDilbert() throws IOException { // open up the webpage to today's comic URL url = new URL("https://dilbert.com"); BufferedReader webRead = new BufferedReader( new InputStreamReader(url.openStream())); String line; while ((line = webRead.readLine()) != null) { if (line.indexOf("ALT=\"Today's Dilbert Comic\"") != -1) { int offset = line.indexOf( "<IMG SRC=\"/comics/dilbert/archive/images/dilbert"); line = line.substring(offset + 10); return "https://dilbert.com" + line.substring(0, line.indexOf('"')); } } return null; } /** * This would allow us to download the URL to a local file. * It is so easy that we do not need any explanation :-) */ public static void download(URL url, File file) throws IOException { InputStream in = url.openStream(); FileOutputStream out = new FileOutputStream(file); byte[] b = new byte[1024]; int len; while((len = in.read(b)) != -1) { out.write(b, 0, len); } out.close(); } public static void main(String[] args) throws IOException { System.out.println("Looking for today's dilbert comic . . ."); String today = todaysDilbert(); if (today == null) { System.out.println("Could not find today's dilbert comic!"); } else { System.out.println("Found today's dilbert: " + today); URL url = new URL(today); // we could download the comic to a local file like this: // download(url, new File("todaydilbert.gif")); // Instead, we are simply going to download it as an ImageIcon // and show it in a JFrame. System.out.println("Downloading the Image . . ."); ImageIcon im = new ImageIcon(url); System.out.println("Downloaded the Image"); JFrame f = new JFrame("Today's Dilbert"); f.getContentPane().add(new JLabel(im)); f.pack(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.show(); } } }
The program could be upgraded to do this automatically once a day. We could save the image for future viewing (since the Dilbert webpage only allows you to see one month's worth of archives).
We did not cover anything earth-shattering in this newsletter, I know. However, when I have shown this to Java programmers, they have, for some reason, been surprised how easy it is to do something like this. I have used this technique to autodownload Garfield going back to 1978, Zapiro (Warning, Zapiro's cartoons has been deemed offensive by some of the most powerful countries in the world. Only read it if you are not sensitive or patriotic - you've been warned!) and a South African cartoon called Madam and Eve that deals with the tensions in South African households.
Kind regards
Heinz
We are always happy to receive comments from our readers. Feel free to send me a comment via email or discuss the newsletter in our JavaSpecialists Slack Channel (Get an invite here)
We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.