1 /*
2  * Copyright (c) 2016 Helmut Neemann
3  * Use of this source code is governed by the GPL v3 license
4  * that can be found in the LICENSE file.
5  */
6 package de.neemann.digital.draw.graphics;
7 
8 import javax.imageio.ImageIO;
9 import java.awt.*;
10 import java.awt.image.BufferedImage;
11 import java.io.Closeable;
12 import java.io.IOException;
13 import java.io.OutputStream;
14 
15 /**
16  * Creates an image
17  */
18 public final class GraphicsImage extends GraphicSwing implements Closeable {
19 
20     private final OutputStream out;
21     private final String format;
22     private final float scale;
23     private BufferedImage bi;
24 
25     /**
26      * Creates a new instance
27      *
28      * @param out    the output stream
29      * @param format the format to write
30      * @param scale  the scaling
31      */
GraphicsImage(OutputStream out, String format, float scale)32     public GraphicsImage(OutputStream out, String format, float scale) {
33         super(null);
34         this.out = out;
35         this.format = format;
36         this.scale = scale;
37     }
38 
39     @Override
setBoundingBox(VectorInterface min, VectorInterface max)40     public Graphic setBoundingBox(VectorInterface min, VectorInterface max) {
41         int thickness = Style.MAXLINETHICK;
42         bi = new BufferedImage(
43                 Math.round((max.getXFloat() - min.getXFloat() + thickness * 2) * scale),
44                 Math.round((max.getYFloat() - min.getYFloat() + thickness * 2) * scale),
45                 BufferedImage.TYPE_INT_ARGB);
46         Graphics2D gr = bi.createGraphics();
47         gr.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
48         gr.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
49         gr.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
50         gr.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
51         gr.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
52 
53         gr.setColor(new Color(255, 255, 255, 0));
54         gr.fillRect(0, 0, bi.getWidth(), bi.getHeight());
55 
56         gr.scale(scale, scale);
57         gr.translate(thickness - min.getXFloat(), thickness - min.getYFloat());
58         setGraphics2D(gr);
59         return this;
60     }
61 
62     @Override
close()63     public void close() throws IOException {
64         if (out != null) {
65             if (bi != null)
66                 ImageIO.write(bi, format, out);
67             out.close();
68         }
69     }
70 
71     /**
72      * @return the created image
73      */
getBufferedImage()74     public BufferedImage getBufferedImage() {
75         return bi;
76     }
77 }
78