I'm currently working on a project where I'm attempting to download a .ico file, but for some strange reason, I can't seem to open it programmatically once downloaded. I can however, open the image saved using any image editor or viewer. My code:
public static BufferedImage parseImageLocal(String url) throws IOException {
if (url.endsWith(".ico")) {
return ICODecoder.read(new File(url)).get(0);
} else if (url.endsWith(".bmp")) {
return BMPDecoder.read(new File(url));
} else {
return ImageIO.read(new File(url));
}
}
public static void saveImage(BufferedImage img, String path)
throws IOException {
File outputfile = new File(path.replace("http://", ""));
File parent = outputfile.getParentFile();
parent.mkdir();
if (!outputfile.exists()) {
outputfile.createNewFile();
}
if (path.endsWith(".ico")) {
ICOEncoder.write(img, outputfile);
} else if (path.endsWith(".bmp")) {
BMPEncoder.write(img, outputfile);
} else {
ImageIO.write(img, "png", outputfile);
}
}
And this is how i download images from the internet:
public static BufferedImage parseImage(String url) throws IOException {
URL dest = new URL(url);
if (url.endsWith(".ico")) {
return ICODecoder.read(dest.openStream()).get(0);
} else if (url.endsWith(".bmp")) {
return BMPDecoder.read(dest.openStream());
} else {
return ImageIO.read(dest);
}
}
The error is on this line:
return ICODecoder.read(new File(url)).get(0);
It "seems" that you are trying to download the icon from the internet, but you are trying to treat the
URL
as aFile
.Basically, this isn't going to be possible,
File
won't be able to resolve to an actual physical file.Instead, you should be using
ICODecoder#read(InputStream)
andURL#openStream
Something more like...
Updated with example
A web resource is not a
File
, you can not access it as if they were, instead, you need to use the classes designed for interacting with the internet/network.For example...
Update with some more ideas
Now. I could be wrong, but when I ran your code, I ran into a serious of problems with the paths...
Let's assume the original url/path is
https://secure.gravatar.com/favicon.ico
, when you save the image, you do something like...With our original path, this would result in a
outputfile
ofhttps://secure.gravatar.com/favicon.ico
, which is obviously wrong...We can correct for this by using
path.replace("https://", "")
as well...Now, this results in a
outputfile
ofsecure.gravatar.com/favicon.ico
. I become a little unstuck, as I'm not sure if this is what you want...but it does work for me...Now, when you read the file, you do something like this...
Now, with no evidence to the contray, I have to assume the
url
has not changed and is stillhttps://secure.gravatar.com/favicon.ico
...this means thatnew File("https://secure.gravatar.com/favicon.ico")
will produce an invalid file referenceSo, again, I parsed the input...
Which produces
secure.gravatar.com\favicon.ico
This all downloaded, wrote and read without error.