1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.onehippo.forge.gallerymagick.core;
17
18 import java.io.Serializable;
19
20 import org.apache.commons.lang.StringUtils;
21 import org.apache.commons.lang.builder.HashCodeBuilder;
22 import org.apache.commons.lang.math.NumberUtils;
23
24
25
26
27 public class ImageDimension implements Serializable {
28
29 private static final long serialVersionUID = 1L;
30
31 private int width;
32 private int height;
33
34 public ImageDimension() {
35 }
36
37 public ImageDimension(int width, int height) {
38 setWidth(width);
39 setHeight(height);
40 }
41
42 public int getWidth() {
43 return width;
44 }
45
46 public void setWidth(int width) {
47 if (width < 0) {
48 throw new IllegalArgumentException("Invalid width: " + width);
49 }
50
51 this.width = width;
52 }
53
54 public int getHeight() {
55 return height;
56 }
57
58 public void setHeight(int height) {
59 if (height < 0) {
60 throw new IllegalArgumentException("Invalid height: " + height);
61 }
62
63 this.height = height;
64 }
65
66 @Override
67 public boolean equals(Object o) {
68 if (!(o instanceof ImageDimension)) {
69 return false;
70 }
71
72 ImageDimension other = (ImageDimension) o;
73
74 return width == other.width && height == other.height;
75 }
76
77 @Override
78 public int hashCode() {
79 return new HashCodeBuilder().append(width).append(height).toHashCode();
80 }
81
82 @Override
83 public String toString() {
84 return new StringBuilder(20).append(width).append('x').append(height).toString();
85 }
86
87
88
89
90
91
92
93 public String toCommandArgument() {
94 StringBuilder arg = new StringBuilder(20);
95 if (width == 0 && height == 0) {
96 arg.append("100%");
97 }
98 if (width > 0) {
99 arg.append(width);
100 }
101 if (height > 0) {
102 arg.append('x').append(height);
103 }
104
105 return arg.toString();
106 }
107
108 public static ImageDimension from(final int width, final int height) {
109 if (width < 0 || height < 0) {
110 throw new IllegalArgumentException("Invalid width or height.");
111 }
112
113 return new ImageDimension(width, height);
114 }
115
116 public static ImageDimension from(final String dimension) {
117 int width = -1;
118 int height = -1;
119
120 if (StringUtils.isNotBlank(dimension)) {
121 int offset = dimension.indexOf('x');
122
123 if (offset != -1) {
124 width = NumberUtils.toInt(dimension.substring(0, offset));
125 height = NumberUtils.toInt(dimension.substring(offset + 1));
126 }
127 }
128
129 if (width < 0 || height < 0) {
130 throw new IllegalArgumentException("Invalid dimension: '" + dimension + "'.");
131 }
132
133 return new ImageDimension(width, height);
134 }
135 }