Skip to content

Commit 7f5cbff

Browse files
committed
Workaround issue #6 . Return empty avatar if download fails.
1 parent 8cac1e5 commit 7f5cbff

File tree

1 file changed

+27
-26
lines changed

1 file changed

+27
-26
lines changed

src/main/java/com/jayfella/website/core/ImageDownloader.java

Lines changed: 27 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@
77
import java.io.IOException;
88
import java.net.URL;
99

10+
import org.slf4j.Logger;
11+
import org.slf4j.LoggerFactory;
1012
public class ImageDownloader {
13+
private static final Logger log = LoggerFactory.getLogger(ImageDownloader.class);
1114

1215
public static byte[] downloadUiAvatar(
1316
int size,
@@ -43,40 +46,38 @@ public static byte[] downloadGravatarAvatar(String emailHash) throws IOException
4346
}
4447

4548
public static byte[] downloadImage(String urlString) throws IOException {
49+
try{
50+
URL url = new URL(urlString);
4651

47-
URL url = new URL(urlString);
52+
BufferedImage imageIn = ImageIO.read(url);
4853

49-
BufferedImage imageIn;
54+
BufferedImage imageOut = new BufferedImage(
55+
imageIn.getWidth(),
56+
imageIn.getHeight(),
57+
BufferedImage.TYPE_INT_RGB);
5058

51-
try {
52-
imageIn = ImageIO.read(url);
53-
}
54-
catch (IOException ex) {
55-
ex.printStackTrace();
56-
return null;
57-
}
58-
59-
if (imageIn == null) {
60-
System.out.println("Downloaded UIAvatar image is null");
61-
return null;
62-
}
63-
64-
BufferedImage imageOut = new BufferedImage(
65-
imageIn.getWidth(),
66-
imageIn.getHeight(),
67-
BufferedImage.TYPE_INT_RGB);
59+
imageOut.createGraphics().drawImage(imageIn, 0, 0, Color.WHITE, null);
6860

69-
imageOut.createGraphics().drawImage(imageIn, 0, 0, Color.WHITE, null);
61+
byte[] imageData;
7062

71-
byte[] imageData;
72-
73-
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
63+
ByteArrayOutputStream baos = new ByteArrayOutputStream();
64+
ImageIO.write(imageOut, "jpg", baos);
65+
imageData = baos.toByteArray();
66+
67+
return imageData;
68+
}catch(Exception e){
69+
log.info( "Can't download "+urlString+". Use empty image.");
70+
e.printStackTrace();
71+
BufferedImage imageOut = new BufferedImage(
72+
64,
73+
64,
74+
BufferedImage.TYPE_INT_RGB);
75+
byte[] imageData;
76+
ByteArrayOutputStream baos = new ByteArrayOutputStream();
7477
ImageIO.write(imageOut, "jpg", baos);
7578
imageData = baos.toByteArray();
79+
return imageData;
7680
}
77-
78-
return imageData;
79-
8081
}
8182

8283
}

0 commit comments

Comments
 (0)