|
7 | 7 | import java.io.IOException;
|
8 | 8 | import java.net.URL;
|
9 | 9 |
|
| 10 | +import org.slf4j.Logger; |
| 11 | +import org.slf4j.LoggerFactory; |
10 | 12 | public class ImageDownloader {
|
| 13 | + private static final Logger log = LoggerFactory.getLogger(ImageDownloader.class); |
11 | 14 |
|
12 | 15 | public static byte[] downloadUiAvatar(
|
13 | 16 | int size,
|
@@ -43,40 +46,38 @@ public static byte[] downloadGravatarAvatar(String emailHash) throws IOException
|
43 | 46 | }
|
44 | 47 |
|
45 | 48 | public static byte[] downloadImage(String urlString) throws IOException {
|
| 49 | + try{ |
| 50 | + URL url = new URL(urlString); |
46 | 51 |
|
47 |
| - URL url = new URL(urlString); |
| 52 | + BufferedImage imageIn = ImageIO.read(url); |
48 | 53 |
|
49 |
| - BufferedImage imageIn; |
| 54 | + BufferedImage imageOut = new BufferedImage( |
| 55 | + imageIn.getWidth(), |
| 56 | + imageIn.getHeight(), |
| 57 | + BufferedImage.TYPE_INT_RGB); |
50 | 58 |
|
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); |
68 | 60 |
|
69 |
| - imageOut.createGraphics().drawImage(imageIn, 0, 0, Color.WHITE, null); |
| 61 | + byte[] imageData; |
70 | 62 |
|
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(); |
74 | 77 | ImageIO.write(imageOut, "jpg", baos);
|
75 | 78 | imageData = baos.toByteArray();
|
| 79 | + return imageData; |
76 | 80 | }
|
77 |
| - |
78 |
| - return imageData; |
79 |
| - |
80 | 81 | }
|
81 | 82 |
|
82 | 83 | }
|
0 commit comments