aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/cc/polyfrost/oneconfig/images/Image.java
blob: 16957c1aca99763fcf62e81211b11db8819c8fb7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package cc.polyfrost.oneconfig.images;

import cc.polyfrost.oneconfig.utils.IOUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Objects;

/** An Image wrapper class that is used by the OneConfig system.*/
@SuppressWarnings("unused")
public class Image {
    private static final Logger LOGGER = LogManager.getLogger("OneConfig Images");
    private BufferedImage image;
    private Graphics2D graphics = null;
    private final int width, height;

    /**
     * Create a new Image from the file. This can be as a resource location inside your JAR.
     * @param filePath The path to the image file.
     */
    public Image(String filePath) throws IOException {
        image = ImageIO.read(Objects.requireNonNull(Image.class.getResourceAsStream(filePath)));
        width = image.getWidth();
        height = image.getHeight();
    }

    /**
     * Create a new Image from the file.
     * @param is InputStream to the image file.
     */
    public Image(InputStream is) throws IOException {
        image = ImageIO.read(is);
        width = image.getWidth();
        height = image.getHeight();
    }

    /**
     * Create a new Image from the file.
     * @param file File to the image file.
     */
    public Image(File file) throws IOException {
            image = ImageIO.read(Objects.requireNonNull(file));
            width = image.getWidth();
            height = image.getHeight();
    }

    /**
     * Create a new Image from the BufferedImage.
     */
    public Image(BufferedImage image) {
        this.image = image;
        width = image.getWidth();
        height = image.getHeight();
    }

    /** Create a new blank image with the specified width and height. */
    public Image(int width, int height) {
        this.width = width;
        this.height = height;
        image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    }

    /** Get the image as a BufferedImage. */
    public BufferedImage getImage() {
        return image;
    }

    protected void setImage(BufferedImage img) {
        image = img;
    }

    /** Get the graphics object associated with the image. */
    public Graphics2D getG2D() {
        if (graphics == null) {
            graphics = image.createGraphics();
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        }
        return graphics;
    }


    /** Dispose of the graphics object. */
    public void dispose() {
        if(graphics != null) {
            graphics.dispose();
            graphics = null;
        }
    }

    /** Get the width of the image. */
    public int getWidth() {
        return width;
    }

    /** Get the height of the image. */
    public int getHeight() {
        return height;
    }

    /** Crop the image to the specified width and height.
     * @param startX The x coordinate of the top-left corner of the crop.
     * @param startY The y coordinate of the top-left corner of the crop.
     * @param width The width of the crop.
     * @param height The height of the crop.
     */
    public void crop(int startX, int startY, int width, int height) {
        image = image.getSubimage(startX, startY, width, height);
    }

    /** Get the color of a pixel in the image. */
    public void getColorAtPos(int x, int y) {
        image.getRGB(x, y);
    }

    /** Set the color of a pixel in the image. */
    public void setColorAtPos(int x, int y, int argb) {
        image.setRGB(x, y, argb);
    }

    /** Attempt to save the image to the specified file. */
    public void save(String filePath) throws IOException {
        ImageIO.write(image, "png", new File(filePath));
    }

    /** Attempt to upload the image to Imgur, returning the JSON that the server replied with. */
    public JsonObject uploadToImgur() {
        try {
            // thanks stack overflow for the help with this :_)
            URL url = new URL("https://api.imgur.com/3/image");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setRequestMethod("POST");
            con.setRequestProperty("Authorization", "Client-ID " + "6cfc432a9954f4d");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.connect();
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            ImageIO.write(image, "png", byteOut);
            String encoded = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(Base64.getEncoder().encodeToString(byteOut.toByteArray()), "UTF-8");
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
            writer.write(encoded);
            byteOut.close();
            writer.close();
            if(con.getResponseCode() != 200) {
                LOGGER.error("Error uploading image to Imgur: " + con.getResponseCode());
                return null;
            }

            BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
            JsonObject object = new JsonParser().parse(rd).getAsJsonObject();
            rd.close();

            return object;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("Error uploading image to Imgur.");
            return null;
        }
    }

    /** Attempt to upload the image to Imgur, returning the URL that the image is hosted at.
     * @param copy weather or not to copy the URL to the clipboard as well. */
    public String uploadToImgur(boolean copy) {
        JsonObject object = uploadToImgur();
        String link = object.get("data").getAsJsonObject().get("link").getAsString();
        if(copy) IOUtils.copyStringToClipboard(link);
        return link;
    }

    /** Copy the image to the system clipboard and delete the graphics object. */
    public void copyToClipboard() {
        IOUtils.copyImageToClipboard(image);
        dispose();
    }

    // MASK METHODS
    public void setBrightness(float brightness) {
        maskColor(new Color(0f,0f,0f,brightness));
    }

    public void maskColor(Color color) {
        Graphics2D g2d = getG2D();
        g2d.setColor(color);
        g2d.fillRect(0,0,width,height);
        dispose();
    }

    public void maskPaint(Paint paint) {
        Graphics2D g2d = getG2D();
        g2d.setPaint(paint);
        g2d.fillRect(0,0,width,height);
        dispose();
    }

    // LINE METHODS
    public void drawLine(Stroke stroke, int sx, int sy, int ex, int ey) {
        Graphics2D g2d = getG2D();
        g2d.setStroke(stroke);
        g2d.drawLine(sx, sy, ex, ey);
        dispose();
    }

    public void drawLine(int sx, int sy, int ex, int ey, int width) {
        drawLine(new BasicStroke(width), sx, sy, ex, ey);
    }

    // SHAPE METHODS
    public void drawTexturedRect(TexturePaint paint, int x, int y, int width, int height) {
        Graphics2D g2d = getG2D();
        g2d.setPaint(paint);
        g2d.fillRect(x, y, width, height);
        dispose();
    }

    public void drawRect(int x, int y, int width, int height, int color) {
        Graphics2D g2d = getG2D();
        g2d.setColor(new Color(color, true));
        g2d.drawRect(x, y, width, height);
        dispose();
    }
    public void drawRoundedRect(int x, int y, int width, int height, int radius, int color) {
        Graphics2D g2d = getG2D();
        g2d.setColor(new Color(color, true));
        g2d.fillRoundRect(x, y, width, height, radius, radius);
        dispose();
    }

    public void drawPolygon(int x, int y, Polygon polygon, int color) {
        Graphics2D g2d = getG2D();
        g2d.setColor(new Color(color, true));
        g2d.translate(x, y);
        g2d.fillPolygon(polygon);
        dispose();
    }

    public void drawOval(int x, int y, int width, int height, int color) {
        Graphics2D g2d = getG2D();
        g2d.setColor(new Color(color, true));
        g2d.fillOval(x, y, width, height);
        dispose();
    }

    public void drawTriangle(Point p1, Point p2, Point p3, int color) {
        Graphics2D g2d = getG2D();
        g2d.setColor(new Color(color, true));
        g2d.fillPolygon(new int[] {p1.x, p2.x, p3.x}, new int[] {p1.y, p2.y, p3.y}, 3);
        dispose();
    }

    public void drawCircle(int x, int y, int radius, int color) {
        Graphics2D g2d = getG2D();
        g2d.setColor(new Color(color, true));
        g2d.fillRoundRect(x, y, radius, radius, radius, radius);
        dispose();
    }






    // STRING METHODS
    public void drawString(String text, int x, int y, Font font, int color) {
        Graphics2D g2d = getG2D();
        g2d.setColor(new Color(color, true));
        g2d.setFont(font);
        g2d.drawString(text, x, y);
        dispose();
    }



    // IMAGE METHODS
    /** Scale the image by the given factor (1.0 = no change). */
    public void scale(double sx, double sy) {
        if(sx == 1.0 && sy == 1.0) return;
        BufferedImage old = image;
        image = new BufferedImage((int) (Math.abs(sx * image.getWidth())), (int) (Math.abs(image.getHeight() * sy)), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = getG2D();
        g2d.drawImage(old, new AffineTransformOp(AffineTransform.getScaleInstance(sx, sy), AffineTransformOp.TYPE_BILINEAR), 0, 0);
        dispose();
    }
    /**
     * Scale the image to the specified width and height.
     */
    public void setSize(int width, int height) {
        if(width == this.width && height == this.height) return;
        scale(width / (double) this.width, height / (double) this.height);
    }

    /** Rotate the image by the given angle (in degrees). */
    public void rotate(double angle) {
        if(angle == 0 || angle == 360) return;
        Graphics2D g2d = getG2D();
        g2d.drawImage(image, new AffineTransformOp(AffineTransform.getRotateInstance(Math.toRadians(angle)), AffineTransformOp.TYPE_BILINEAR), 0, 0);
        dispose();
    }

    /** Translate the image by the given amount. */
    public void translate(int moveX, int moveY) {
        Graphics2D g2d = getG2D();
        g2d.drawImage(image, new AffineTransformOp(AffineTransform.getTranslateInstance(moveX, moveY), AffineTransformOp.TYPE_BILINEAR), 0, 0);
        dispose();
    }

    /** Flip the image horizontally. */
    public void flipHorizontal() {
        scale(-1, 1);
    }

    /** Flip the image vertically. */
    public void flipVertical() {
        scale(1, -1);
    }
}