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 package info.magnolia.dam.app.ui.field.upload;
35
36 import java.io.File;
37 import java.io.FileInputStream;
38 import java.io.FileNotFoundException;
39 import java.io.InputStream;
40
41 import org.apache.commons.io.IOUtils;
42 import org.devlib.schmidt.imageinfo.ImageInfo;
43
44
45
46
47 final class ImageSize {
48
49 private final long width;
50 private final long height;
51
52 ImageSize(long width, long height) {
53 this.width = width;
54 this.height = height;
55 }
56
57 public long getWidth() {
58 return width;
59 }
60
61 public long getHeight() {
62 return height;
63 }
64
65
66
67
68
69 public ImageSize scaleToFitIfLarger(long boundingWidth, long boundingHeight) {
70
71 if (this.width >= this.height && this.width > boundingWidth) {
72 double scaleFactor = ((double) boundingWidth) / this.width;
73 long scaledHeight = (long) (scaleFactor * this.height);
74 return new ImageSize(boundingWidth, scaledHeight);
75 }
76
77 if (this.height > this.width && this.height > boundingHeight) {
78 double scaleFactor = ((double) boundingHeight) / this.height;
79 long scaledWidth = (long) (scaleFactor * this.width);
80 return new ImageSize(scaledWidth, boundingHeight);
81 }
82
83 return this;
84 }
85
86 @Override
87 public boolean equals(Object o) {
88 if (this == o) {
89 return true;
90 }
91 if (!(o instanceof ImageSize)) {
92 return false;
93 }
94
95 final ImageSize../../../../../info/magnolia/dam/app/ui/field/upload/ImageSize.html#ImageSize">ImageSize imageSize = (ImageSize) o;
96
97 return height == imageSize.height && width == imageSize.width;
98 }
99
100 @Override
101 public int hashCode() {
102 int result = (int) (width ^ (width >>> 32));
103 result = 31 * result + (int) (height ^ (height >>> 32));
104 return result;
105 }
106
107 public static ImageSize valueOf(File file) throws FileNotFoundException {
108 return valueOf(new FileInputStream(file));
109 }
110
111 public static ImageSize valueOf(InputStream inputStream) {
112 InputStream stream = null;
113 try {
114 ImageInfo imageInfo = new ImageInfo();
115 stream = inputStream;
116 imageInfo.setInput(stream);
117 return imageInfo.check() ? new ImageSize(imageInfo.getWidth(), imageInfo.getHeight()) : null;
118 } finally {
119 IOUtils.closeQuietly(stream);
120 }
121 }
122 }