Java apache commons FTP, how to download image file to BufferedImage
So I am trying to download an image file from an FTP site, get some meta data from it, and then return the binary data to a web page using the Play! Framework. Here is the basic code i am using inside a controller action (removed all the error checking for brevity):
FTPClient ftp = new FTPClient();
ftp.connect(site.host, site.port);
ftp.login(site.username, site.password);
InputStream is = ftp.retrieveFileStream("somefile.png");
Response.current().contentType = "image/png";
renderBinary(is);
I know that the true type of the input stream is a SocketInputStream, is there something special i nee开发者_Python百科d to do to be able to use that?
I also tried this:
BufferedImage bimg = ImageIO.read(is);
but 'bimg' comes out as null, so this leads me to believe that the data from the input stream is not valid image data.
Does anyone have any experience doing this and can point me in the right direction?
You might need to somehow convert SocketInputStream
to ImageInputStream
. Here's the javadoc on ImageIO.read()
and it explains why you get a null:-
Returns a BufferedImage as the result of decoding a supplied InputStream with an ImageReader chosen automatically from among those currently registered. The InputStream is wrapped in an ImageInputStream. If no registered ImageReader claims to be able to read the resulting stream, null is returned.
The current cache settings from getUseCacheand getCacheDirectory will be used to control caching in the ImageInputStream that is created.
This method does not attempt to locate ImageReaders that can read directly from an InputStream; that may be accomplished using IIORegistry and ImageReaderSpi.
This method does not close the provided InputStream after the read operation has completed; it is the responsibility of the caller to close the stream, if desired.
So, I assume ImageReader
is not able to read the stream you have, thus you get the null from the call.
UPDATE
You could probably do this:-
BufferedImage bimg = ImageIO.read(ImageIO.createImageInputStream(yourSocketInputStream));
Does this work for you?
精彩评论