ImageFetcher: Better handling if Image can't be saved as jpg

This commit is contained in:
Hans Mackowiak
2019-08-24 17:51:39 +00:00
committed by Michael Kamensky
parent c31198eaea
commit 5cf1f47047
3 changed files with 38 additions and 10 deletions

View File

@@ -163,6 +163,10 @@ public final class ImageKeys {
for (String ext : FILE_EXTENSIONS) {
File file = new File(dir, filename + ext);
if (file.exists()) {
if (file.isDirectory()) {
file.delete();
continue;
}
return file;
}
}

View File

@@ -14,6 +14,13 @@ final class ImageLoader extends CacheLoader<String, BufferedImage> {
public BufferedImage load(String key) {
File file = ImageKeys.getImageFile(key);
if (file != null) {
if (!file.exists()) {
return null;
}
if (file.isDirectory()) {
file.delete();
return null;
}
try {
return ImageIO.read(file);
}

View File

@@ -28,18 +28,35 @@ public class SwingImageFetcher extends ImageFetcher {
private void doFetch(String urlToDownload) throws IOException {
URL url = new URL(urlToDownload);
System.out.println("Attempting to fetch: " + url);
java.net.URLConnection c = url.openConnection();
c.setRequestProperty("User-Agent", "");
BufferedImage image = ImageIO.read(c.getInputStream());
BufferedImage image = ImageIO.read(url);
// First, save to a temporary file so that nothing tries to read
// a partial download.
File destFile = new File(destPath + ".tmp");
destFile.mkdirs();
ImageIO.write(image, "jpg", destFile);
// need to check directory folder for mkdir
destFile.getParentFile().mkdirs();
if (ImageIO.write(image, "jpg", destFile)) {
// Now, rename it to the correct name.
destFile.renameTo(new File(destPath));
if (destFile.renameTo(new File(destPath))) {
System.out.println("Saved image to " + destPath);
SwingUtilities.invokeLater(notifyObservers);
} else {
System.err.println("Failed to rename image to " + destPath);
}
} else {
System.err.println("Failed to save image from " + url + " as jpeg");
// try to save image as png instead
if (ImageIO.write(image, "png", destFile)) {
String newPath = destPath.replace(".jpg", ".png");
if (destFile.renameTo(new File(newPath))) {
System.out.println("Saved image to " + newPath);
SwingUtilities.invokeLater(notifyObservers);
} else {
System.err.println("Failed to rename image to " + newPath);
}
} else {
System.err.println("Failed to save image from " + url + " as png");
}
}
}
public void run() {
@@ -48,7 +65,7 @@ public class SwingImageFetcher extends ImageFetcher {
doFetch(urlToDownload);
break;
} catch (IOException e) {
System.out.println("Failed to download card [" + destPath + "] image: " + e.getMessage());
System.err.println("Failed to download card [" + destPath + "] image: " + e.getMessage());
}
}
}