@@ -193,7 +193,7 @@ public static boolean imagesAreEqualsWithDiff(BufferedImage image1, BufferedImag
193193 public static BufferedImage scale (BufferedImage source , double ratio ) {
194194 int w = (int ) (source .getWidth () * ratio );
195195 int h = (int ) (source .getHeight () * ratio );
196- BufferedImage scaledImage = getCompatibleImage (w , h );
196+ BufferedImage scaledImage = getCompatibleImage (w , h , source );
197197 Graphics2D resultGraphics = scaledImage .createGraphics ();
198198 resultGraphics .setRenderingHint (RenderingHints .KEY_INTERPOLATION ,
199199 RenderingHints .VALUE_INTERPOLATION_BICUBIC );
@@ -202,11 +202,42 @@ public static BufferedImage scale(BufferedImage source, double ratio) {
202202 return scaledImage ;
203203 }
204204
205- private static BufferedImage getCompatibleImage (int w , int h ) {
206- GraphicsEnvironment ge = GraphicsEnvironment .getLocalGraphicsEnvironment ();
207- GraphicsDevice gd = ge .getDefaultScreenDevice ();
208- GraphicsConfiguration gc = gd .getDefaultConfiguration ();
209- BufferedImage image = gc .createCompatibleImage (w , h );
210- return image ;
205+ private static BufferedImage getCompatibleImage (int w , int h , BufferedImage source ) {
206+ BufferedImage bimage = null ;
207+ try {
208+ GraphicsEnvironment ge = GraphicsEnvironment .getLocalGraphicsEnvironment ();
209+ GraphicsDevice gd = ge .getDefaultScreenDevice ();
210+ GraphicsConfiguration gc = gd .getDefaultConfiguration ();
211+ bimage = gc .createCompatibleImage (w ,h );
212+ } catch (HeadlessException e ) {
213+ // The system does not have a screen
214+ }
215+ if (bimage == null ) {
216+ boolean hasAlpha = hasAlpha (source );
217+ int type = BufferedImage .TYPE_INT_RGB ;
218+ if (hasAlpha ) {
219+ type = BufferedImage .TYPE_INT_ARGB ;
220+ }
221+ bimage = new BufferedImage (w , h , type );
222+ }
223+ return bimage ;
224+ }
225+
226+ public static boolean hasAlpha (Image image ) {
227+ // If buffered image, the color model is readily available
228+ if (image instanceof BufferedImage ) {
229+ BufferedImage bimage = (BufferedImage )image ;
230+ return bimage .getColorModel ().hasAlpha ();
231+ }
232+ // Use a pixel grabber to retrieve the image's color model;
233+ // grabbing a single pixel is usually sufficient
234+ PixelGrabber pg = new PixelGrabber (image , 0 , 0 , 1 , 1 , false );
235+ try {
236+ pg .grabPixels ();
237+ } catch (InterruptedException e ) {
238+ }
239+ // Get the image's color model
240+ ColorModel cm = pg .getColorModel ();
241+ return cm .hasAlpha ();
211242 }
212243}
0 commit comments