Image 转 BufferedImage @param image 图像 @return
(Image image)
| 40 | * @return |
| 41 | */ |
| 42 | private static BufferedImage toBufferedImage(Image image) { |
| 43 | if (image instanceof BufferedImage) { |
| 44 | return (BufferedImage) image; |
| 45 | } |
| 46 | // This code ensures that all the pixels in the image are loaded |
| 47 | image = new ImageIcon(image).getImage(); |
| 48 | BufferedImage bimage = null; |
| 49 | GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); |
| 50 | try { |
| 51 | int transparency = Transparency.OPAQUE; |
| 52 | GraphicsDevice gs = ge.getDefaultScreenDevice(); |
| 53 | GraphicsConfiguration gc = gs.getDefaultConfiguration(); |
| 54 | bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency); |
| 55 | } catch (HeadlessException e) { |
| 56 | // The system does not have a screen |
| 57 | } |
| 58 | if (bimage == null) { |
| 59 | // Create a buffered image using the default color model |
| 60 | int type = BufferedImage.TYPE_INT_RGB; |
| 61 | bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type); |
| 62 | } |
| 63 | // 复制图像到图像缓冲区 |
| 64 | Graphics g = bimage.createGraphics(); |
| 65 | // 将图像绘制到图像缓冲区 |
| 66 | g.drawImage(image, 0, 0, null); |
| 67 | g.dispose(); |
| 68 | return bimage; |
| 69 | } |
| 70 | } |