Java Reference
In-Depth Information
JavaScript, PHP and Python. In fact, the overhead of building up a Web page to use
applets for transferring multimedia fi les over the Internet and the security restrictions
placed upon applets can often make the transfer of fi les via Java applications prefer-
able to the use of applets. In such applications, the use of interface
Serializable
(described in Sect.
4.6
)
is crucial.
Java's original support for audio was restricted to
Sun Audio fi le format
(
.au
fi les). Nowadays, Windows
Wave
format (
.wav
fi les), Macintosh
AIFF
format (
.aif
fi les) and the
MIDI
format (
.mid
or
.rmf
fi les) are all supported by the standard Java
libraries. For the transfer of image fi les, the original release of Java accepted only
GIF format (
.gif
fi les). Support for the JPEG format (
.jpg
and
.jpeg
fi les) was added
in JDK1.1. In order to play video clips and most other fi le formats, however, it is
necessary to download the Java Media Framework. This API will be covered in a
later section of this chapter, but we shall restrict our attention to the standard Java
SE provision for the time being.
11.1
Transferring and Displaying Images Easily
In Java, classes
Image
(from package
java.awt
) and
ImageIcon
(package
javax.
swing
) are used for holding and manipulating images. Either may be used on its
own, but
ImageIcon
is particularly useful for loading an image from the current
directory into an application. For example:
ImageIcon image = new ImageIcon("pic.gif");
ImageIcon
is also useful for transferring the image across a network, since it
implements the
Serializable
interface. There are more ways than one of transferring
image fi les across a network via Java. However, since
ImageIcon
implements
Serializable
, it is particularly convenient to use the method described below.
1. Create an
ObjectOutputStream
object from the relevant
Socket
object at the
sending end.
2. Transmit the
ImageIcon
object via method
writeObject
of
ObjectOutputStream
.
3. Create an
ObjectInputStream
object from the relevant
Socket
object at the receiving
end.
4. Receive the transmitted object via method
readObject
of
ObjectInputStream
.
5. Typecast the received object (from type
Object
) into
ImageIcon
.
As might be expected, there will often be a client-server relationship between
the two ends of such a communication (though it may be that the two ends are actu-
ally peers and are using the client-server relationship merely as a convenience).
The basic code for the two ends of the communication will be very similar to that
which was featured in several of the examples in earlier chapters, of course.
Because of that, such lines will not be commented or explained (again) here. The
lines of code corresponding to steps 1-5 above, however, will be commented
clearly in bold type.
Search WWH ::
Custom Search