@@ -96,4 +96,43 @@ public static void inputToOutputStream(InputStream in, OutputStream out) throws
9696 out .write (buffer , 0 , len );
9797 }
9898 }
99+
100+ /**
101+ * バイト配列が画像かどうか
102+ *
103+ * @param data 検体
104+ * @return 画像かどうか
105+ */
106+ public static boolean isImage (byte [] data ) {
107+ try {
108+ ImageIO .read (new ByteArrayInputStream (data ));
109+ return true ;
110+ } catch (IOException e ) {
111+ return false ;
112+ }
113+ }
114+
115+ /**
116+ * 画像を指定サイズまで縮小する
117+ *
118+ * @param image 対象画像
119+ * @param size サイズ
120+ * @return 縮小済み
121+ * @throws IOException exception
122+ */
123+ public static BufferedImage reductionSize (BufferedImage image , long size ) throws IOException {
124+ long lastSize = toByteArray (image , "png" ).length ;
125+ if (lastSize <= size ) return image ;
126+ float scale = (float ) size / lastSize ;
127+ BufferedImage nimg = resize (image , (int ) (image .getWidth () * scale ), (int ) (image .getHeight () * scale ));
128+ return reductionSizeW (nimg , size , lastSize );
129+ }
130+
131+ private static BufferedImage reductionSizeW (BufferedImage image , long size , long lastSize ) throws IOException {
132+ byte [] data = toByteArray (image , "png" );
133+ if (data .length == lastSize ) throw new IOException ("Can't be smaller than this" );
134+ if (data .length <= size ) return image ;
135+ BufferedImage nimg = resize (image , image .getWidth () / 2 , image .getHeight () / 2 );
136+ return reductionSizeW (nimg , size , data .length );
137+ }
99138}
0 commit comments