SHOW:
|
|
- or go back to the newest paste.
1 | import javax.imageio.ImageIO; | |
2 | import java.awt.image.BufferedImage; | |
3 | import java.io.BufferedOutputStream; | |
4 | import java.io.File; | |
5 | import java.io.FileOutputStream; | |
6 | import java.io.IOException; | |
7 | import java.util.concurrent.ExecutorService; | |
8 | import java.util.concurrent.Executors; | |
9 | import java.util.concurrent.TimeUnit; | |
10 | ||
11 | public class CustomImageWriter { | |
12 | ||
13 | private ExecutorService executorService; | |
14 | ||
15 | public CustomImageWriter() { | |
16 | this.executorService = Executors.newFixedThreadPool(1); | |
17 | } | |
18 | ||
19 | public void writeImage(final BufferedImage image, final File file) throws IOException { | |
20 | //Slow | |
21 | ImageIO.write(image, "PNG", file); | |
22 | ||
23 | //My suggestion | |
24 | Runnable r = new Runnable() { | |
25 | @Override | |
26 | public void run() { | |
27 | try { | |
28 | BufferedOutputStream imageOutputStream = new BufferedOutputStream(new FileOutputStream(file)); | |
29 | ImageIO.write(image, "PNG", imageOutputStream); | |
30 | imageOutputStream.close(); | |
31 | - | } catch (Exception e) { |
31 | + | } catch (IOException e) { |
32 | e.printStackTrace(); | |
33 | } | |
34 | } | |
35 | }; | |
36 | executorService.submit(r); | |
37 | } | |
38 | ||
39 | public void waitForImages() { | |
40 | executorService.shutdown(); | |
41 | ||
42 | try { | |
43 | executorService.awaitTermination(1, TimeUnit.DAYS); | |
44 | } catch (InterruptedException e) { | |
45 | e.printStackTrace(); | |
46 | } | |
47 | } | |
48 | ||
49 | } |